Example usage for javax.persistence EntityManager createNamedQuery

List of usage examples for javax.persistence EntityManager createNamedQuery

Introduction

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

Prototype

public Query createNamedQuery(String name);

Source Link

Document

Create an instance of Query for executing a named query (in the Java Persistence query language or in native SQL).

Usage

From source file:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * {@inheritDoc}//w  w w.  j  a v a  2  s.  co  m
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#getEntryCounts()
 */
@Override
public Map<String, Long> getEntryCounts() {
    final HashMap<String, Long> entryCounts = new HashMap<String, Long>();
    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        try {
            final Query query = em.createNamedQuery(DeltaIndexingDao.NAMED_QUERY_COUNT_ENTRIES);
            final List<Object[]> list = query.getResultList();
            for (final Object[] entryCount : list) {
                entryCounts.put((String) entryCount[0], (Long) entryCount[1]);
            }
        } finally {
            closeEntityManager(em);
        }
    } catch (final DeltaIndexingException ex) {
        if (_log.isErrorEnabled()) {
            _log.error("error getting entry counts for all data source ids", ex);
        }
    } finally {
        _lock.readLock().unlock();
    }

    return entryCounts;
}

From source file:org.opencastproject.messages.MailService.java

/**
 * @return Finds the total number of message signatures for the current user.
 * @throws UserSettingsServiceException//www.  ja va  2s .c om
 */
public int getSignatureTotalByUserName() throws MailServiceException {
    EntityManager em = null;
    try {
        em = emf.createEntityManager();
        String orgId = securityService.getOrganization().getId();
        String username = securityService.getUser().getUsername();
        Query q = em.createNamedQuery("MessageSignature.countByCreator").setParameter("username", username)
                .setParameter("org", orgId);
        Number countResult = (Number) q.getSingleResult();
        return countResult.intValue();
    } catch (Exception e) {
        logger.error("Could not count message signatures: {}", ExceptionUtils.getStackTrace(e));
        throw new MailServiceException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * {@inheritDoc}//www . ja v  a  2  s  . c o m
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#obsoleteIdIterator(String, String)
 */
@Override
public Iterator<ConnectivityId> obsoleteIdIterator(final String sessionId, final String dataSourceID)
        throws DeltaIndexingSessionException, DeltaIndexingException {
    if (dataSourceID == null) {
        throw new DeltaIndexingException("parameter dataSourceID is null");
    }
    _lock.readLock().lock();
    try {
        assertSession(sessionId, dataSourceID);
        final EntityManager em = createEntityManager();
        try {
            final Query query = em.createNamedQuery(DeltaIndexingDao.NAMED_QUERY_FIND_OBSOLETE_IDS_BY_SOURCE);
            final List<DeltaIndexingDao> daos = query
                    .setParameter(DeltaIndexingDao.NAMED_QUERY_PARAM_SOURCE, dataSourceID).getResultList();
            if (daos.isEmpty() && _log.isInfoEnabled()) {
                _log.info("obsoleteIdIterator could not find any obsolete ids for source: " + dataSourceID);
            }
            return new IdIterator(daos.iterator());
        } catch (final Exception e) {
            throw new DeltaIndexingException("error executing loadRecords with source: " + dataSourceID, e);
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }

}

From source file:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * {@inheritDoc}//from   w  w  w .j a v a  2  s. c o  m
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#getLockStates()
 */
@Override
public Map<String, LockState> getLockStates() {
    final HashMap<String, LockState> lockStates = new HashMap<String, LockState>();
    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        try {
            final Query query = em.createNamedQuery(DataSourceDao.NAMED_QUERY_SELECT_ALL);
            final List<DataSourceDao> list = query.getResultList();
            for (final DataSourceDao dao : list) {
                LockState state = LockState.UNLOCKED;
                if (dao.getSessionId() != null) {
                    state = LockState.LOCKED;
                }
                lockStates.put(dao.getDataSourceId(), state);
            }
        } finally {
            closeEntityManager(em);
        }
    } catch (final DeltaIndexingException ex) {
        if (_log.isErrorEnabled()) {
            _log.error("error getting lock states for all data source ids", ex);
        }
    } finally {
        _lock.readLock().unlock();
    }

    return lockStates;
}

From source file:org.opencastproject.messages.MailService.java

/**
 * Get all of the message signatures for the current user.
 * @return A list of all of the message signatures.
 * @throws UserSettingsServiceException/* w w w.ja  va2s .  c  om*/
 */
@SuppressWarnings("unchecked")
public List<MessageSignature> getMessageSignaturesByUserName() throws MailServiceException {
    EntityManager em = null;
    try {
        em = emf.createEntityManager();
        String orgId = securityService.getOrganization().getId();
        String username = securityService.getUser().getUsername();
        Query q = em.createNamedQuery("MessageSignature.findByCreator").setParameter("username", username)
                .setParameter("org", orgId);
        List<MessageSignature> signatures = new ArrayList<MessageSignature>();
        List<MessageSignatureDto> result = q.getResultList();
        for (MessageSignatureDto m : result) {
            signatures.add(m.toMessageSignature(userDirectoryService));
        }
        return signatures;
    } catch (Exception e) {
        logger.error("Could not get message signatures: {}", ExceptionUtils.getStackTrace(e));
        throw new MailServiceException(e);
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

From source file:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * Resets the visited and modified flags of a data source. Must be used with an entity manager.
 * /*w  ww  .j a v  a  2 s . co m*/
 * @param em
 *          the EntityManager
 * @param dataSourceId
 *          the id of the data source
 * @throws DeltaIndexingException
 *           if any error occurs
 */
private void resetFlags(final EntityManager em, final String dataSourceId) throws DeltaIndexingException {
    try {
        final Query query = em.createNamedQuery(DeltaIndexingDao.NAMED_QUERY_RESET_FLAGS);
        query.setParameter(DeltaIndexingDao.NAMED_QUERY_PARAM_SOURCE, dataSourceId).executeUpdate();
        if (_log.isInfoEnabled()) {
            _log.info("reset visited flags for data source id: " + dataSourceId);
        }
    } catch (final Exception e) {
        throw new DeltaIndexingException("error resetting visited flags for data source id: " + dataSourceId,
                e);
    }
}

From source file:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * Internal method to find a DataSourceDao object by sessionId.
 * //www  . j a  v  a  2s .c  o  m
 * @param em
 *          the EntityManager
 * @param sessionId
 *          the id of the session
 * @return the found DataSourceDao or null if none exists
 * @throws DeltaIndexingException
 *           if any error occurs
 */
private DataSourceDao findDataSourceDaoBySession(final EntityManager em, final String sessionId)
        throws DeltaIndexingException {
    try {
        final Query query = em.createNamedQuery(DataSourceDao.NAMED_QUERY_FIND_BY_SESSION_ID);
        final List<DataSourceDao> daos = query
                .setParameter(DataSourceDao.NAMED_QUERY_PARAM_SESSION_ID, sessionId).getResultList();
        if (daos != null && !daos.isEmpty()) {
            return daos.get(0);
        }
        return null;
    } catch (final Exception e) {
        throw new DeltaIndexingException("error searching for sessionId " + sessionId, e);
    }

}

From source file:com.headissue.pigeon.service.AdminSurveyService.java

void mergeQuestion(Survey _survey, SurveyValue _value, EntityManager _manager) {
    List<Question> _items = new ArrayList<Question>(_survey.getQuestions());
    int _orderBy = 0;
    Question q = null;//from  w  w w .  j av a 2 s  .  co  m
    for (QuestionValue qv : _value.getQuestions()) {
        if (!_items.isEmpty()) {
            q = beanService.copy(_items.remove(0), qv, QUESTION_PROPERTIES);
            q.setOrderBy(++_orderBy);
            LogUtils.debug(log, "recycle question %s: '%s'", q.getId(), q.getText());
        } else {
            q = beanService.copy(Question.class, qv, QUESTION_PROPERTIES);
            _survey.addQuestion(q, ++_orderBy);
            LogUtils.debug(log, "add a new question:  '%s'", q.getText());
        }
        mergeQuestionText(q, qv, _manager);
    }
    if (!_items.isEmpty()) {
        for (Question qq : _items) {
            LogUtils.debug(log, "remove question %s", qq.getId());
            Query query = _manager.createNamedQuery("answer.deleteAnswerByQuestion");
            query.setParameter("question", qq);
            query.executeUpdate();
            _survey.getQuestions().remove(qq);
        }
    }
}

From source file:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * {@inheritDoc}/*from  w  w  w  .  j  av a  2 s.  c o  m*/
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#unlockDatasources()
 */
@Override
public void unlockDatasources() throws DeltaIndexingException {
    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        final EntityTransaction transaction = em.getTransaction();
        try {
            transaction.begin();
            final Query query = em.createNamedQuery(DataSourceDao.NAMED_QUERY_KILL_ALL_SESSIONS);
            query.executeUpdate();
            transaction.commit();
            if (_log.isInfoEnabled()) {
                _log.info("removed all delta indexing sessions and unlocked all data sources");
            }
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new DeltaIndexingException("error unlocking delta indexing data sources", e);
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }
}

From source file:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * {@inheritDoc}/*from   w  w w .jav  a  2  s. c  o m*/
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#unlockDatasource(String)
 */
@Override
public void unlockDatasource(final String dataSourceID) throws DeltaIndexingException {
    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        final EntityTransaction transaction = em.getTransaction();
        try {
            transaction.begin();
            final Query query = em.createNamedQuery(DataSourceDao.NAMED_QUERY_KILL_SESSION);
            query.setParameter(DeltaIndexingDao.NAMED_QUERY_PARAM_SOURCE, dataSourceID);
            query.executeUpdate();
            transaction.commit();
            if (_log.isInfoEnabled()) {
                _log.info("removed delta indexing sessions and unlocked data source " + dataSourceID);
            }
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new DeltaIndexingException("error unlocking delta indexing data source " + dataSourceID, e);
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }
}