Example usage for javax.persistence EntityManager isOpen

List of usage examples for javax.persistence EntityManager isOpen

Introduction

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

Prototype

public boolean isOpen();

Source Link

Document

Determine whether the entity manager is open.

Usage

From source file:org.opencastproject.usertracking.impl.UserTrackingServiceImpl.java

public Report getReport(String from, String to, int offset, int limit) throws ParseException {
    Report report = new ReportImpl();
    report.setLimit(limit);//from w w w  . j  av a2  s  .  co  m
    report.setOffset(offset);

    Calendar calBegin = new GregorianCalendar();
    Calendar calEnd = new GregorianCalendar();
    SimpleDateFormat complex = new SimpleDateFormat("yyyyMMddhhmm");
    SimpleDateFormat simple = new SimpleDateFormat("yyyyMMdd");

    //Try to parse the from calendar
    try {
        calBegin.setTime(complex.parse(from));
    } catch (ParseException e) {
        calBegin.setTime(simple.parse(from));
    }

    //Try to parse the to calendar
    try {
        calEnd.setTime(complex.parse(to));
    } catch (ParseException e) {
        calEnd.setTime(simple.parse(to));
    }

    EntityManager em = null;
    try {
        em = emf.createEntityManager();
        Query q = em.createNamedQuery("countSessionsGroupByMediapackageByIntervall");
        q.setFirstResult(offset);
        q.setMaxResults(limit);
        q.setParameter("begin", calBegin, TemporalType.TIMESTAMP);
        q.setParameter("end", calEnd, TemporalType.TIMESTAMP);

        @SuppressWarnings("unchecked")
        List<Object[]> result = q.getResultList();
        ReportItem item;

        for (Object[] a : result) {
            item = new ReportItemImpl();
            item.setEpisodeId((String) a[0]);
            item.setViews((Long) a[1]);
            item.setPlayed((Long) a[2]);
            report.add(item);
        }
        return report;
    } finally {
        if (em != null && em.isOpen()) {
            em.close();
        }
    }
}

From source file:org.opencastproject.usertracking.impl.UserTrackingServiceImpl.java

public FootprintList getFootprints(String mediapackageId, String userId) {
    EntityManager em = null;
    try {/*  www  .  j a  va 2  s . co m*/
        em = emf.createEntityManager();
        Query q = null;
        if (StringUtils.trimToNull(userId) == null) {
            q = em.createNamedQuery("findUserActionsByTypeAndMediapackageIdOrderByOutpointDESC");
        } else {
            q = em.createNamedQuery("findUserActionsByTypeAndMediapackageIdByUserOrderByOutpointDESC");
            q.setParameter("userid", userId);
        }
        q.setParameter("type", FOOTPRINT_KEY);
        q.setParameter("mediapackageId", mediapackageId);
        @SuppressWarnings("unchecked")
        Collection<UserAction> userActions = q.getResultList();

        int[] resultArray = new int[1];
        boolean first = true;

        for (UserAction a : userActions) {
            if (first) {
                // Get one more item than the known outpoint to append a footprint of 0 views at the end of the result set
                resultArray = new int[a.getOutpoint() + 1];
                first = false;
            }
            for (int i = a.getInpoint(); i < a.getOutpoint(); i++) {
                resultArray[i]++;
            }
        }
        FootprintList list = new FootprintsListImpl();
        int current = -1;
        int last = -1;
        for (int i = 0; i < resultArray.length; i++) {
            current = resultArray[i];
            if (last != current) {
                Footprint footprint = new FootprintImpl();
                footprint.setPosition(i);
                footprint.setViews(current);
                list.add(footprint);
            }
            last = current;
        }
        return list;
    } finally {
        if (em != null && em.isOpen()) {
            em.close();
        }
    }
}

From source file:org.opencastproject.usertracking.impl.UserTrackingServiceImpl.java

/**
 * {@inheritDoc}/*from   w w w  .j  a  va 2s  .  c  o m*/
 * 
 * @see org.opencastproject.usertracking.api.UserTrackingService#getUserAction(java.lang.Long)
 */
@Override
public UserAction getUserAction(Long id) throws UserTrackingException, NotFoundException {
    EntityManager em = null;
    UserActionImpl result = null;
    try {
        em = emf.createEntityManager();
        result = em.find(UserActionImpl.class, id);
    } catch (Exception e) {
        throw new UserTrackingException(e);
    } finally {
        if (em != null && em.isOpen()) {
            em.close();
        }
    }
    if (result == null) {
        throw new NotFoundException("No UserAction found with id='" + id + "'");
    } else {
        return result;
    }
}

From source file:org.opentides.persistence.interceptor.SynchronizableInterceptor.java

/**
 * Saves the change log into the database.
 * @param shortMessage/*from   w ww .  j a  v  a 2  s .c  o m*/
 * @param message
 * @param entity
 */
public static void saveLog(BaseEntity entity, int action, String updateFields, String sqlCommand) {
    EntityManager em = DatabaseUtil.getEntityManager();
    try {
        em.getTransaction().begin();
        ChangeLog cl = new ChangeLog(entity.getId(), entity.getClass(), action, updateFields, sqlCommand);
        em.persist(cl);
        em.flush();
        em.getTransaction().commit();
    } catch (Exception ex) {
        _log.error("Failed to save change log on [" + entity.getClass().getSimpleName() + "]", ex);
    } finally {
        if (em != null && em.isOpen()) {
            em.close();
        }
    }
}

From source file:org.springframework.orm.jpa.EntityManagerFactoryUtils.java

/**
 * Close the given JPA EntityManager,//from  w w w. ja va2s  .  c o m
 * catching and logging any cleanup exceptions thrown.
 * @param em the JPA EntityManager to close (may be {@code null})
 * @see javax.persistence.EntityManager#close()
 */
public static void closeEntityManager(@Nullable EntityManager em) {
    if (em != null) {
        logger.debug("Closing JPA EntityManager");
        try {
            if (em.isOpen()) {
                em.close();
            }
        } catch (PersistenceException ex) {
            logger.debug("Could not close JPA EntityManager", ex);
        } catch (Throwable ex) {
            logger.debug("Unexpected exception on closing JPA EntityManager", ex);
        }
    }
}

From source file:utilities.PopulateDatabase.java

public static void main(String[] args) throws Throwable {
    ApplicationContext applicationContext;
    EntityManagerFactory entityManagerFactory;
    EntityManager entityManager;
    EntityTransaction entityTransaction;

    applicationContext = new ClassPathXmlApplicationContext("classpath:PopulateDatabase.xml");

    entityManagerFactory = Persistence.createEntityManagerFactory(PersistenceUnit);
    entityManager = entityManagerFactory.createEntityManager();
    entityTransaction = entityManager.getTransaction();

    initialise(entityManagerFactory, entityManager);

    entityTransaction.begin();//from   w  w  w  .j av a 2s. co m
    try {
        for (Entry<String, Object> entry : applicationContext.getBeansWithAnnotation(Entity.class).entrySet()) {
            String beanName;
            DomainEntity entity;

            beanName = entry.getKey();
            entity = (DomainEntity) entry.getValue();
            entityManager.persist(entity);
            System.out.println(String.format("Persisting (%s, %s, %d)", beanName, entity.getClass().getName(),
                    entity.getId()));
        }
        entityTransaction.commit();
    } catch (Exception oops) {
        oops.printStackTrace();
        entityTransaction.rollback();
    } finally {
        if (entityManager.isOpen())
            entityManager.close();
        if (entityManagerFactory.isOpen())
            entityManagerFactory.close();
    }
}