Example usage for javax.persistence Query setMaxResults

List of usage examples for javax.persistence Query setMaxResults

Introduction

In this page you can find the example usage for javax.persistence Query setMaxResults.

Prototype

Query setMaxResults(int maxResult);

Source Link

Document

Set the maximum number of results to retrieve.

Usage

From source file:org.nuxeo.ecm.rating.LikesCountActivityStreamFilter.java

@Override
public ActivitiesList query(ActivityStreamService activityStreamService, Map<String, Serializable> parameters,
        long offset, long limit) {
    QueryType queryType = (QueryType) parameters.get(QUERY_TYPE_PARAMETER);
    if (queryType == null) {
        return new ActivitiesListImpl();
    }/*from ww w  .j  a  va2 s.c om*/

    Query query = null;
    String queryStr = "";
    String innerStr = "";
    EntityManager em = ((ActivityStreamServiceImpl) activityStreamService).getEntityManager();
    Serializable actor = parameters.get(ACTOR_PARAMETER);

    switch (queryType) {
    case GET_DOCUMENTS_COUNT:
        // InnerQuery indicates if the actor has alredy liked or not
        innerStr = "SELECT COUNT(activity2) FROM Activity activity2 WHERE activity2.verb = :verb";
        innerStr += " AND activity2.context = :context AND activity2.object = :object";
        innerStr += " AND activity2.actor = :actor AND activity2.target = activity.target";
        if (parameters.containsKey(FROMDT_PARAMETER)) {
            innerStr += " AND activity2.publishedDate BETWEEN :fromDt AND :toDt";
        }
        queryStr = "SELECT activity.target, count(activity), (" + innerStr + ") FROM Activity activity";
        queryStr += " WHERE activity.verb = :verb and activity.context  = :context";
        queryStr += " AND activity.object = :object";
        if (parameters.containsKey(FROMDT_PARAMETER)) {
            queryStr += " AND activity.publishedDate BETWEEN :fromDt AND :toDt";
        }
        queryStr += " GROUP BY activity.target ORDER BY COUNT(activity) DESC";

        Serializable object = String.valueOf(parameters.get(OBJECT_PARAMETER));
        query = em.createQuery(queryStr);
        query.setParameter(OBJECT_PARAMETER, object);

        break;
    case GET_MINI_MESSAGE_COUNT:
        // InnerQuery indicates if the actor has alredy liked or not
        innerStr = "Select count(likes2) from Activity as likes2 ";
        innerStr += " where likes.target = likes2.target and likes2.actor = :actor";
        if (parameters.containsKey(FROMDT_PARAMETER)) {
            innerStr += " AND likes2.publishedDate BETWEEN :fromDt AND :toDt";
        }
        queryStr = "Select likes.target, count(likes), (" + innerStr
                + ") from Activity as likes, Activity as minimessage";
        queryStr += " where concat('activity:', cast(minimessage.id as string)) = likes.target";
        queryStr += " and minimessage.verb = :verbMiniMessage and minimessage.context  = :context";
        queryStr += " and likes.verb = :verb";
        if (parameters.containsKey(FROMDT_PARAMETER)) {
            queryStr += " AND likes.publishedDate BETWEEN :fromDt AND :toDt";
        }
        queryStr += " group by likes.target order by count(likes) desc";

        query = em.createQuery(queryStr);
        query.setParameter(VERB_MINIMESSAGE_PARAMETER, "minimessage");

        break;
    default:
        log.info("Unknown query type: " + queryType);
        return new ActivitiesListImpl();
    }

    // Default parameters
    query.setParameter(CONTEXT_PARAMETER, parameters.get(CONTEXT_PARAMETER));
    query.setParameter(VERB_PARAMETER, RATING_VERB_PREFIX + LIKE_ASPECT);
    query.setParameter(ACTOR_PARAMETER, actor);
    if (parameters.containsKey(FROMDT_PARAMETER)) {
        query.setParameter(FROMDT_PARAMETER, parameters.get(FROMDT_PARAMETER));
        query.setParameter(TODT_PARAMETER, parameters.get(TODT_PARAMETER));
    }

    if (limit > 0) {
        query.setMaxResults((int) limit);
    }
    if (offset > 0) {
        query.setFirstResult((int) offset);
    }

    ActivitiesList likesCount = new ActivitiesListImpl();
    for (Object result : query.getResultList()) {
        Object[] objects = (Object[]) result;
        ActivityBuilder ab = new ActivityBuilder().verb(RATING_VERB_PREFIX + LIKE_ASPECT).actor((String) actor)
                .object(String.valueOf(objects[1])).target((String) objects[0])
                .context(String.valueOf(objects[2]));
        likesCount.add(ab.build());
    }

    return likesCount;
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

public Query getSelectQuery(int rowsPerPage, String orderBy, EntityManager em, String jpql, List<Date> dtParams,
        int lastTotal, List<String> idFieldNames) {
    if (orderBy != null && orderBy.length() > 0) {
        int join = orderBy.indexOf("@");
        if (join > 0) {
            int k = jpql.indexOf("where");
            if (k > 0) {
                jpql = jpql.substring(0, k) + orderBy.substring(0, join) + jpql.substring(k)
                        + orderBy.substring(join + 1);
            } else {
                jpql = jpql + " " + orderBy.substring(0, join) + orderBy.substring(join + 1);
            }//from   www. j  a  v a2 s .co  m
        } else
            jpql = jpql + " " + orderBy;
        jpql = jpql + ", " + toString(idFieldNames);
    }
    Query q = em.createQuery(jpql);
    if (!dtParams.isEmpty()) {
        for (int i = 0; i < dtParams.size(); i++) {
            q.setParameter("dt" + i, dtParams.get(i));
        }
    }
    setQueryTimeout(q);
    if (lastTotal >= 0 && rowsPerPage > 0) {
        q.setFirstResult(lastTotal);
        q.setMaxResults(rowsPerPage);
    }
    return q;
}

From source file:org.ejbca.core.model.era.RaMasterApiSessionBean.java

@SuppressWarnings("unchecked")
@Override/*from   w  ww. j  a  v a2 s  . c om*/
public RaEndEntitySearchResponse searchForEndEntities(AuthenticationToken authenticationToken,
        RaEndEntitySearchRequest request) {
    final RaEndEntitySearchResponse response = new RaEndEntitySearchResponse();
    final List<Integer> authorizedLocalCaIds = new ArrayList<>(
            caSession.getAuthorizedCaIds(authenticationToken));
    // Only search a subset of the requested CAs if requested
    if (!request.getCaIds().isEmpty()) {
        authorizedLocalCaIds.retainAll(request.getCaIds());
    }
    if (authorizedLocalCaIds.isEmpty()) {
        // Empty response since there were no authorized CAs
        if (log.isDebugEnabled()) {
            log.debug("Client '" + authenticationToken
                    + "' was not authorized to any of the requested CAs and the search request will be dropped.");
        }
        return response;
    }
    // Check Certificate Profile authorization
    final List<Integer> authorizedCpIds = new ArrayList<>(
            certificateProfileSession.getAuthorizedCertificateProfileIds(authenticationToken, 0));
    final boolean accessAnyCpAvailable = authorizedCpIds
            .containsAll(certificateProfileSession.getCertificateProfileIdToNameMap().keySet());
    if (!request.getCpIds().isEmpty()) {
        authorizedCpIds.retainAll(request.getCpIds());
    }
    if (authorizedCpIds.isEmpty()) {
        // Empty response since there were no authorized Certificate Profiles
        if (log.isDebugEnabled()) {
            log.debug("Client '" + authenticationToken
                    + "' was not authorized to any of the requested CPs and the search request will be dropped.");
        }
        return response;
    }
    // Check End Entity Profile authorization
    final Collection<Integer> authorizedEepIds = new ArrayList<>(endEntityProfileSession
            .getAuthorizedEndEntityProfileIds(authenticationToken, AccessRulesConstants.VIEW_END_ENTITY));
    final boolean accessAnyEepAvailable = authorizedEepIds
            .containsAll(endEntityProfileSession.getEndEntityProfileIdToNameMap().keySet());
    if (!request.getEepIds().isEmpty()) {
        authorizedEepIds.retainAll(request.getEepIds());
    }
    if (authorizedEepIds.isEmpty()) {
        // Empty response since there were no authorized End Entity Profiles
        if (log.isDebugEnabled()) {
            log.debug("Client '" + authenticationToken
                    + "' was not authorized to any of the requested EEPs and the search request will be dropped.");
        }
        return response;
    }
    final String subjectDnSearchString = request.getSubjectDnSearchString();
    final String subjectAnSearchString = request.getSubjectAnSearchString();
    final String usernameSearchString = request.getUsernameSearchString();
    final StringBuilder sb = new StringBuilder("SELECT a.username FROM UserData a WHERE (a.caId IN (:caId))");
    if (!subjectDnSearchString.isEmpty() || !subjectAnSearchString.isEmpty()
            || !usernameSearchString.isEmpty()) {
        sb.append(" AND (");
        boolean firstAppended = false;
        if (!subjectDnSearchString.isEmpty()) {
            sb.append("a.subjectDN LIKE :subjectDN");
            firstAppended = true;
        }
        if (!subjectAnSearchString.isEmpty()) {
            if (firstAppended) {
                sb.append(" OR ");
            } else {
                firstAppended = true;
            }
            sb.append("a.subjectAltName LIKE :subjectAltName");
        }
        if (!usernameSearchString.isEmpty()) {
            if (firstAppended) {
                sb.append(" OR ");
            } else {
                firstAppended = true;
            }
            sb.append("a.username LIKE :username");
        }
        sb.append(")");
    }

    if (request.isModifiedAfterUsed()) {
        sb.append(" AND (a.timeModified > :modifiedAfter)");
    }
    if (request.isModifiedBeforeUsed()) {
        sb.append(" AND (a.timeModified < :modifiedBefore)");
    }
    if (!request.getStatuses().isEmpty()) {
        sb.append(" AND (a.status IN (:status))");
    }
    // Don't constrain results to certain end entity profiles if root access is available and "any" CP is requested
    if (!accessAnyCpAvailable || !request.getCpIds().isEmpty()) {
        sb.append(" AND (a.certificateProfileId IN (:certificateProfileId))");
    }
    // Don't constrain results to certain end entity profiles if root access is available and "any" EEP is requested
    if (!accessAnyEepAvailable || !request.getEepIds().isEmpty()) {
        sb.append(" AND (a.endEntityProfileId IN (:endEntityProfileId))");
    }
    final Query query = entityManager.createQuery(sb.toString());
    query.setParameter("caId", authorizedLocalCaIds);
    if (!accessAnyCpAvailable || !request.getCpIds().isEmpty()) {
        query.setParameter("certificateProfileId", authorizedCpIds);
    }
    if (!accessAnyEepAvailable || !request.getEepIds().isEmpty()) {
        query.setParameter("endEntityProfileId", authorizedEepIds);
    }
    if (log.isDebugEnabled()) {
        log.debug(" CA IDs: " + Arrays.toString(authorizedLocalCaIds.toArray()));
        if (!accessAnyCpAvailable || !request.getCpIds().isEmpty()) {
            log.debug(" certificateProfileId: " + Arrays.toString(authorizedCpIds.toArray()));
        } else {
            log.debug(" certificateProfileId: Any (even deleted) profile(s) due to root access.");
        }
        if (!accessAnyEepAvailable || !request.getEepIds().isEmpty()) {
            log.debug(" endEntityProfileId: " + Arrays.toString(authorizedEepIds.toArray()));
        } else {
            log.debug(" endEntityProfileId: Any (even deleted) profile(s) due to root access.");
        }
    }
    if (!subjectDnSearchString.isEmpty()) {
        if (request.isSubjectDnSearchExact()) {
            query.setParameter("subjectDN", subjectDnSearchString);
        } else {
            query.setParameter("subjectDN", "%" + subjectDnSearchString + "%");
        }
    }
    if (!subjectAnSearchString.isEmpty()) {
        if (request.isSubjectAnSearchExact()) {
            query.setParameter("subjectAltName", subjectAnSearchString);
        } else {
            query.setParameter("subjectAltName", "%" + subjectAnSearchString + "%");
        }
    }
    if (!usernameSearchString.isEmpty()) {
        if (request.isUsernameSearchExact()) {
            query.setParameter("username", usernameSearchString);
        } else {
            query.setParameter("username", "%" + usernameSearchString + "%");
        }
    }
    if (request.isModifiedAfterUsed()) {
        query.setParameter("modifiedAfter", request.getModifiedAfter());
    }
    if (request.isModifiedBeforeUsed()) {
        query.setParameter("modifiedBefore", request.getModifiedBefore());
    }
    if (!request.getStatuses().isEmpty()) {
        query.setParameter("status", request.getStatuses());
    }
    final int maxResults = Math.min(getGlobalCesecoreConfiguration().getMaximumQueryCount(),
            request.getMaxResults());
    query.setMaxResults(maxResults);
    /* Try to use the non-portable hint (depends on DB and JDBC driver) to specify how long in milliseconds the query may run. Possible behaviors:
     * - The hint is ignored
     * - A QueryTimeoutException is thrown
     * - A PersistenceException is thrown (and the transaction which don't have here is marked for roll-back)
     */
    final long queryTimeout = getGlobalCesecoreConfiguration().getMaximumQueryTimeout();
    if (queryTimeout > 0L) {
        query.setHint("javax.persistence.query.timeout", String.valueOf(queryTimeout));
    }
    final List<String> usernames;
    try {
        usernames = query.getResultList();
        for (final String username : usernames) {
            response.getEndEntities().add(endEntityAccessSession.findUser(username));
        }
        response.setMightHaveMoreResults(usernames.size() == maxResults);
        if (log.isDebugEnabled()) {
            log.debug("Certificate search query: " + sb.toString() + " LIMIT " + maxResults + " \u2192 "
                    + usernames.size() + " results. queryTimeout=" + queryTimeout + "ms");
        }
    } catch (QueryTimeoutException e) {
        log.info("Requested search query by " + authenticationToken + " took too long. Query was "
                + e.getQuery().toString() + ". " + e.getMessage());
        response.setMightHaveMoreResults(true);
    } catch (PersistenceException e) {
        log.info("Requested search query by " + authenticationToken + " failed, possibly due to timeout. "
                + e.getMessage());
        response.setMightHaveMoreResults(true);
    }
    return response;
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

@Override
public NakedObjectsList getSortedCollection(String nakedObjectName, com.hiperf.common.ui.shared.util.Id id,
        String attributeName, String sortAttribute, Boolean asc, int page, int rowsPerPage,
        ObjectsToPersist toPersist) throws PersistenceException {
    EntityManager em = null;/* ww w  .  ja va2  s.co m*/
    TransactionContext tc = null;
    Map<com.hiperf.common.ui.shared.util.Id, INakedObject> res = new HashMap<com.hiperf.common.ui.shared.util.Id, INakedObject>();
    try {
        Map<Object, IdHolder> newIdByOldId = new HashMap<Object, IdHolder>();
        tc = createTransactionalContext();
        em = tc.getEm();
        ITransaction tx = tc.getTx();
        tx.begin();
        doPersist(toPersist, null, res, newIdByOldId, em, true, null);
        String jpql = "select count(*) from " + nakedObjectName + " o";
        String currentFilter = getIdClause(id, attributeName);
        jpql += " where " + currentFilter;
        Query q = em.createQuery(jpql);
        Long count = getCount(id, newIdByOldId, q);
        int lastTotal = rowsPerPage * (page - 1);
        if (count > 0 && count > lastTotal) {
            jpql = "select o from " + nakedObjectName + " o ";
            jpql += "where " + currentFilter;
            if (asc != null) {
                if (asc) {
                    jpql += " order by o." + sortAttribute + " asc";
                } else {
                    jpql += " order by o." + sortAttribute + " desc";
                }
            }
            q = em.createQuery(jpql);
            int i = 0;
            for (Object idObj : id.getFieldValues()) {
                if (id.isLocal() && newIdByOldId.containsKey(idObj))
                    q.setParameter("id" + i, newIdByOldId.get(idObj).getId());
                else
                    q.setParameter("id" + i, idObj);
            }
            q.setFirstResult(lastTotal);
            q.setMaxResults(rowsPerPage);

            List<INakedObject> list = q.getResultList();
            if (list != null && !list.isEmpty()) {
                String name = list.get(0).getClass().getName();
                Map<String, Map<Object, Object>> oldIdByNewIdMap = buildInverseIdMap(newIdByOldId);
                list = deproxyEntities(name, list, true, oldIdByNewIdMap);
            }
            NakedObjectsList l = new NakedObjectsList(list, count.intValue(), rowsPerPage, currentFilter);
            l.setConstantFilterFields(new String[] { attributeName });
            return l;
        } else
            return null;
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception in getCollection " + e.getMessage(), e);
        throw new PersistenceException("Exception in getCollection " + e.getMessage(), e);
    } finally {
        finalizeTx(tc);
    }
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

@Override
public NakedObjectsList getCollectionInverse(String wrappedClassName, String attribute,
        com.hiperf.common.ui.shared.util.Id id, int page, int nbRows, ObjectsToPersist toPersist,
        String sortAttribute, Boolean asc) throws PersistenceException {
    INakedObject o = null;/*from w  w  w.j a  v  a 2s .  c om*/
    EntityManager em = null;
    TransactionContext tc = null;
    Map<com.hiperf.common.ui.shared.util.Id, INakedObject> res = new HashMap<com.hiperf.common.ui.shared.util.Id, INakedObject>();
    try {
        Map<Object, IdHolder> newIdByOldId = new HashMap<Object, IdHolder>();
        tc = createTransactionalContext();
        em = tc.getEm();
        ITransaction tx = tc.getTx();
        tx.begin();
        doPersist(toPersist, null, res, newIdByOldId, em, true, null);
        String jpql = "select size(o." + attribute + ") from " + wrappedClassName + " o";
        String currentFilter = getIdClause(id);
        jpql += " where " + currentFilter;
        Query q = em.createQuery(jpql);
        Integer count = getSize(id, newIdByOldId, q);
        int lastTotal = nbRows * (page - 1);
        if (count > 0 && count > lastTotal) {
            jpql = "select j from " + wrappedClassName + " o inner join o." + attribute + " j ";
            jpql += "where " + currentFilter;
            if (asc != null && sortAttribute != null) {
                if (asc) {
                    jpql += " order by j." + sortAttribute + " asc";
                } else {
                    jpql += " order by j." + sortAttribute + " desc";
                }
            }
            q = em.createQuery(jpql);
            int i = 0;
            for (Object idObj : id.getFieldValues()) {
                if (id.isLocal() && newIdByOldId.containsKey(idObj))
                    q.setParameter("id" + i, newIdByOldId.get(idObj).getId());
                else
                    q.setParameter("id" + i, idObj);
            }
            q.setFirstResult(lastTotal);
            q.setMaxResults(nbRows);

            List<INakedObject> list = q.getResultList();
            if (list != null && !list.isEmpty()) {
                String name = list.get(0).getClass().getName();
                Map<String, Map<Object, Object>> oldIdByNewMap = buildInverseIdMap(newIdByOldId);
                list = deproxyEntities(name, list, true, oldIdByNewMap);
            }
            return new NakedObjectsList(list, count.intValue(), nbRows, currentFilter);
        } else
            return null;
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception in getCollection " + e.getMessage(), e);
        throw new PersistenceException("Exception in getCollection " + e.getMessage(), e);
    } finally {
        finalizeTx(tc);
    }
}

From source file:org.ejbca.core.model.era.RaMasterApiSessionBean.java

@SuppressWarnings("unchecked")
@Override/*from   w  ww  .ja  va  2s .c o  m*/
public RaCertificateSearchResponse searchForCertificates(AuthenticationToken authenticationToken,
        RaCertificateSearchRequest request) {
    final RaCertificateSearchResponse response = new RaCertificateSearchResponse();
    final List<Integer> authorizedLocalCaIds = new ArrayList<>(
            caSession.getAuthorizedCaIds(authenticationToken));
    // Only search a subset of the requested CAs if requested
    if (!request.getCaIds().isEmpty()) {
        authorizedLocalCaIds.retainAll(request.getCaIds());
    }
    final List<String> issuerDns = new ArrayList<>();
    for (final int caId : authorizedLocalCaIds) {
        try {
            final String issuerDn = CertTools
                    .stringToBCDNString(StringTools.strip(caSession.getCAInfoInternal(caId).getSubjectDN()));
            issuerDns.add(issuerDn);
        } catch (CADoesntExistsException e) {
            log.warn("CA went missing during search operation. " + e.getMessage());
        }
    }
    if (issuerDns.isEmpty()) {
        // Empty response since there were no authorized CAs
        if (log.isDebugEnabled()) {
            log.debug("Client '" + authenticationToken
                    + "' was not authorized to any of the requested CAs and the search request will be dropped.");
        }
        return response;
    }
    // Check Certificate Profile authorization
    final List<Integer> authorizedCpIds = new ArrayList<>(
            certificateProfileSession.getAuthorizedCertificateProfileIds(authenticationToken, 0));
    final boolean accessAnyCpAvailable = authorizedCpIds
            .containsAll(certificateProfileSession.getCertificateProfileIdToNameMap().keySet());
    if (!request.getCpIds().isEmpty()) {
        authorizedCpIds.retainAll(request.getCpIds());
    }
    if (authorizedCpIds.isEmpty()) {
        // Empty response since there were no authorized Certificate Profiles
        if (log.isDebugEnabled()) {
            log.debug("Client '" + authenticationToken
                    + "' was not authorized to any of the requested CPs and the search request will be dropped.");
        }
        return response;
    }
    // Check End Entity Profile authorization
    final Collection<Integer> authorizedEepIds = new ArrayList<>(endEntityProfileSession
            .getAuthorizedEndEntityProfileIds(authenticationToken, AccessRulesConstants.VIEW_END_ENTITY));
    final boolean accessAnyEepAvailable = authorizedEepIds
            .containsAll(endEntityProfileSession.getEndEntityProfileIdToNameMap().keySet());
    if (!request.getEepIds().isEmpty()) {
        authorizedEepIds.retainAll(request.getEepIds());
    }
    if (authorizedEepIds.isEmpty()) {
        // Empty response since there were no authorized End Entity Profiles
        if (log.isDebugEnabled()) {
            log.debug("Client '" + authenticationToken
                    + "' was not authorized to any of the requested EEPs and the search request will be dropped.");
        }
        return response;
    }
    final String subjectDnSearchString = request.getSubjectDnSearchString();
    final String subjectAnSearchString = request.getSubjectAnSearchString();
    final String usernameSearchString = request.getUsernameSearchString();
    final String serialNumberSearchStringFromDec = request.getSerialNumberSearchStringFromDec();
    final String serialNumberSearchStringFromHex = request.getSerialNumberSearchStringFromHex();
    final StringBuilder sb = new StringBuilder(
            "SELECT a.fingerprint FROM CertificateData a WHERE (a.issuerDN IN (:issuerDN))");
    if (!subjectDnSearchString.isEmpty() || !subjectAnSearchString.isEmpty() || !usernameSearchString.isEmpty()
            || !serialNumberSearchStringFromDec.isEmpty() || !serialNumberSearchStringFromHex.isEmpty()) {
        sb.append(" AND (");
        boolean firstAppended = false;
        if (!subjectDnSearchString.isEmpty()) {
            sb.append("a.subjectDN LIKE :subjectDN");
            firstAppended = true;
        }
        if (!subjectAnSearchString.isEmpty()) {
            if (firstAppended) {
                sb.append(" OR ");
            } else {
                firstAppended = true;
            }
            sb.append("a.subjectAltName LIKE :subjectAltName");
        }
        if (!usernameSearchString.isEmpty()) {
            if (firstAppended) {
                sb.append(" OR ");
            } else {
                firstAppended = true;
            }
            sb.append("a.username LIKE :username");
        }
        if (!serialNumberSearchStringFromDec.isEmpty()) {
            if (firstAppended) {
                sb.append(" OR ");
            } else {
                firstAppended = true;
            }
            sb.append("a.serialNumber LIKE :serialNumberDec");
        }
        if (!serialNumberSearchStringFromHex.isEmpty()) {
            if (firstAppended) {
                sb.append(" OR ");
            }
            sb.append("a.serialNumber LIKE :serialNumberHex");
        }
        sb.append(")");
    }
    // NOTE: notBefore is not indexed.. we might want to disallow such search.
    if (request.isIssuedAfterUsed()) {
        sb.append(" AND (a.notBefore > :issuedAfter)");
    }
    if (request.isIssuedBeforeUsed()) {
        sb.append(" AND (a.notBefore < :issuedBefore)");
    }
    if (request.isExpiresAfterUsed()) {
        sb.append(" AND (a.expireDate > :expiresAfter)");
    }
    if (request.isExpiresBeforeUsed()) {
        sb.append(" AND (a.expireDate < :expiresBefore)");
    }
    // NOTE: revocationDate is not indexed.. we might want to disallow such search.
    if (request.isRevokedAfterUsed()) {
        sb.append(" AND (a.revocationDate > :revokedAfter)");
    }
    if (request.isRevokedBeforeUsed()) {
        sb.append(" AND (a.revocationDate < :revokedBefore)");
    }
    if (!request.getStatuses().isEmpty()) {
        sb.append(" AND (a.status IN (:status))");
        if ((request.getStatuses().contains(CertificateConstants.CERT_REVOKED)
                || request.getStatuses().contains(CertificateConstants.CERT_ARCHIVED))
                && !request.getRevocationReasons().isEmpty()) {
            sb.append(" AND (a.revocationReason IN (:revocationReason))");
        }
    }
    // Don't constrain results to certain certificate profiles if root access is available and "any" CP is requested
    if (!accessAnyCpAvailable || !request.getCpIds().isEmpty()) {
        sb.append(" AND (a.certificateProfileId IN (:certificateProfileId))");
    }
    // Don't constrain results to certain end entity profiles if root access is available and "any" EEP is requested
    if (!accessAnyEepAvailable || !request.getEepIds().isEmpty()) {
        sb.append(" AND (a.endEntityProfileId IN (:endEntityProfileId))");
    }
    final Query query = entityManager.createQuery(sb.toString());
    query.setParameter("issuerDN", issuerDns);
    if (!accessAnyCpAvailable || !request.getCpIds().isEmpty()) {
        query.setParameter("certificateProfileId", authorizedCpIds);
    }
    if (!accessAnyEepAvailable || !request.getEepIds().isEmpty()) {
        query.setParameter("endEntityProfileId", authorizedEepIds);
    }
    if (log.isDebugEnabled()) {
        log.debug(" issuerDN: " + Arrays.toString(issuerDns.toArray()));
        if (!accessAnyCpAvailable || !request.getCpIds().isEmpty()) {
            log.debug(" certificateProfileId: " + Arrays.toString(authorizedCpIds.toArray()));
        } else {
            log.debug(" certificateProfileId: Any (even deleted) profile(s) due to root access.");
        }
        if (!accessAnyEepAvailable || !request.getEepIds().isEmpty()) {
            log.debug(" endEntityProfileId: " + Arrays.toString(authorizedEepIds.toArray()));
        } else {
            log.debug(" endEntityProfileId: Any (even deleted) profile(s) due to root access.");
        }
    }
    if (!subjectDnSearchString.isEmpty()) {
        if (request.isSubjectDnSearchExact()) {
            query.setParameter("subjectDN", subjectDnSearchString);
        } else {
            query.setParameter("subjectDN", "%" + subjectDnSearchString + "%");
        }
    }
    if (!subjectAnSearchString.isEmpty()) {
        if (request.isSubjectAnSearchExact()) {
            query.setParameter("subjectAltName", subjectAnSearchString);
        } else {
            query.setParameter("subjectAltName", "%" + subjectAnSearchString + "%");
        }
    }
    if (!usernameSearchString.isEmpty()) {
        if (request.isUsernameSearchExact()) {
            query.setParameter("username", usernameSearchString);
        } else {
            query.setParameter("username", "%" + usernameSearchString + "%");
        }
    }
    if (!serialNumberSearchStringFromDec.isEmpty()) {
        query.setParameter("serialNumberDec", serialNumberSearchStringFromDec);
        if (log.isDebugEnabled()) {
            log.debug(" serialNumberDec: " + serialNumberSearchStringFromDec);
        }
    }
    if (!serialNumberSearchStringFromHex.isEmpty()) {
        query.setParameter("serialNumberHex", serialNumberSearchStringFromHex);
        if (log.isDebugEnabled()) {
            log.debug(" serialNumberHex: " + serialNumberSearchStringFromHex);
        }
    }
    if (request.isIssuedAfterUsed()) {
        query.setParameter("issuedAfter", request.getIssuedAfter());
    }
    if (request.isIssuedBeforeUsed()) {
        query.setParameter("issuedBefore", request.getIssuedBefore());
    }
    if (request.isExpiresAfterUsed()) {
        query.setParameter("expiresAfter", request.getExpiresAfter());
    }
    if (request.isExpiresBeforeUsed()) {
        query.setParameter("expiresBefore", request.getExpiresBefore());
    }
    if (request.isRevokedAfterUsed()) {
        query.setParameter("revokedAfter", request.getRevokedAfter());
    }
    if (request.isRevokedBeforeUsed()) {
        query.setParameter("revokedBefore", request.getRevokedBefore());
    }
    if (!request.getStatuses().isEmpty()) {
        query.setParameter("status", request.getStatuses());
        if ((request.getStatuses().contains(CertificateConstants.CERT_REVOKED)
                || request.getStatuses().contains(CertificateConstants.CERT_ARCHIVED))
                && !request.getRevocationReasons().isEmpty()) {
            query.setParameter("revocationReason", request.getRevocationReasons());
        }
    }
    final int maxResults = Math.min(getGlobalCesecoreConfiguration().getMaximumQueryCount(),
            request.getMaxResults());
    query.setMaxResults(maxResults);
    /* Try to use the non-portable hint (depends on DB and JDBC driver) to specify how long in milliseconds the query may run. Possible behaviors:
     * - The hint is ignored
     * - A QueryTimeoutException is thrown
     * - A PersistenceException is thrown (and the transaction which don't have here is marked for roll-back)
     */
    final long queryTimeout = getGlobalCesecoreConfiguration().getMaximumQueryTimeout();
    if (queryTimeout > 0L) {
        query.setHint("javax.persistence.query.timeout", String.valueOf(queryTimeout));
    }
    final List<String> fingerprints;
    try {
        fingerprints = query.getResultList();
        for (final String fingerprint : fingerprints) {
            response.getCdws().add(certificateStoreSession.getCertificateData(fingerprint));
        }
        response.setMightHaveMoreResults(fingerprints.size() == maxResults);
        if (log.isDebugEnabled()) {
            log.debug("Certificate search query: " + sb.toString() + " LIMIT " + maxResults + " \u2192 "
                    + fingerprints.size() + " results. queryTimeout=" + queryTimeout + "ms");
        }
    } catch (QueryTimeoutException e) {
        // Query.toString() does not return the SQL query executed just a java object hash. If Hibernate is being used we can get it using:
        // query.unwrap(org.hibernate.Query.class).getQueryString()
        // We don't have access to hibernate when building this class though, all querying should be moved to the ejbca-entity package.
        // See ECA-5341
        String queryString = e.getQuery().toString();
        //            try {
        //                queryString = e.getQuery().unwrap(org.hibernate.Query.class).getQueryString();
        //            } catch (PersistenceException pe) {
        //                log.debug("Query.unwrap(org.hibernate.Query.class) is not supported by JPA provider");
        //            }
        log.info("Requested search query by " + authenticationToken + " took too long. Query was '"
                + queryString + "'. " + e.getMessage());
        response.setMightHaveMoreResults(true);
    } catch (PersistenceException e) {
        log.info("Requested search query by " + authenticationToken + " failed, possibly due to timeout. "
                + e.getMessage());
        response.setMightHaveMoreResults(true);
    }
    return response;
}

From source file:com.lp.server.fertigung.ejbfac.FertigungFacBean.java

public BigDecimal getMengeDerLetztenLosablieferungEinerAuftragsposition(Integer auftragIId,
        Integer artikelIId) {/*from   www. jav a2 s .  c om*/

    String sQuery = "select la.n_menge from FLRLosablieferung la WHERE la.flrlos.flrauftrag.i_id=" + auftragIId
            + " AND la.flrlos.flrstueckliste.flrartikel.i_id=" + artikelIId + " ORDER BY la.t_aendern DESC";

    SessionFactory factory = FLRSessionFactory.getFactory();
    Session session = factory.openSession();

    org.hibernate.Query letzes = session.createQuery(sQuery);
    letzes.setMaxResults(1);
    List<?> resultList = letzes.list();

    if (resultList.size() > 0) {
        Iterator<?> resultListIterator = resultList.iterator();
        return (BigDecimal) resultListIterator.next();
    } else {
        return null;
    }

}

From source file:com.lp.server.fertigung.ejbfac.FertigungFacBean.java

public Integer holeTageslos(Integer lagerIId, String mandantCNr, int iStandarddurchlaufzeit,
        boolean bSofortverbrauch, TheClientDto theClientDto) {

    Integer losIId = null;/* ww  w  .jav a2s . c  o m*/

    TageslosDto tageslosDto = null;
    try {
        tageslosDto = getKuecheFac().tageslosFindByLagerIIdBSofortverbrauch(lagerIId,
                Helper.boolean2Short(bSofortverbrauch));
    } catch (RemoteException e) {
        throwEJBExceptionLPRespectOld(e);
    }

    if (tageslosDto != null) {
        // Nun das erste ausgegebene Los mit der angegebenen Kostenstelle
        // des heutigen Tages suchen
        Session session = FLRSessionFactory.getFactory().openSession();
        String sQuery3 = "FROM FLRLosReport AS l WHERE l.kostenstelle_i_id=" + tageslosDto.getKostenstelleIId()
                + " AND l.stueckliste_i_id IS NULL AND l.status_c_nr IN('" + FertigungFac.STATUS_IN_PRODUKTION
                + "','" + FertigungFac.STATUS_TEILERLEDIGT + "') AND l.t_produktionsbeginn='"
                + Helper.formatDateWithSlashes(new java.sql.Date(System.currentTimeMillis())) + "' ";

        if (bSofortverbrauch) {
            sQuery3 += " AND l.flrfertigungsgruppe.c_bez='" + StuecklisteFac.FERTIGUNGSGRUPPE_SOFORTVERBRAUCH
                    + "' ";
        } else {
            sQuery3 += " AND l.flrfertigungsgruppe.c_bez NOT IN('"
                    + StuecklisteFac.FERTIGUNGSGRUPPE_SOFORTVERBRAUCH + "') ";
        }
        sQuery3 += " ORDER BY l.t_produktionsbeginn DESC";

        org.hibernate.Query hquery3 = session.createQuery(sQuery3);
        hquery3.setMaxResults(1);
        List<?> resultList3 = hquery3.list();
        Iterator<?> resultListIterator3 = resultList3.iterator();

        if (resultListIterator3.hasNext()) {
            FLRLosReport rep = (FLRLosReport) resultListIterator3.next();
            losIId = rep.getI_id();
        } else {
            // Wenn keines gefunden wurde, dann ein neues anlegen
            Timestamp tHeute = Helper.cutTimestamp(new Timestamp(System.currentTimeMillis()));

            Calendar cTemp = Calendar.getInstance();
            cTemp.set(Calendar.DAY_OF_YEAR, cTemp.get(Calendar.DAY_OF_YEAR) + iStandarddurchlaufzeit);

            LosDto losDto = new LosDto();
            losDto.setTProduktionsbeginn(new java.sql.Date(tHeute.getTime()));
            losDto.setTProduktionsende(new java.sql.Date(cTemp.getTimeInMillis()));
            losDto.setKostenstelleIId(tageslosDto.getKostenstelleIId());
            losDto.setMandantCNr(mandantCNr);
            losDto.setNLosgroesse(new BigDecimal(1));
            try {
                FertigungsgruppeDto[] fgDto = getStuecklisteFac().fertigungsgruppeFindByMandantCNr(mandantCNr,
                        theClientDto);

                if (fgDto != null && fgDto.length > 0) {
                    losDto.setFertigungsgruppeIId(fgDto[0].getIId());
                }

                if (bSofortverbrauch) {
                    Fertigungsgruppe fertigungsgruppe;
                    try {
                        Query query = em.createNamedQuery("FertigungsgruppefindByMandantCNrCBez");
                        query.setParameter(1, mandantCNr);
                        query.setParameter(2, StuecklisteFac.FERTIGUNGSGRUPPE_SOFORTVERBRAUCH);
                        fertigungsgruppe = (Fertigungsgruppe) query.getSingleResult();

                        losDto.setFertigungsgruppeIId(fertigungsgruppe.getIId());

                    } catch (javax.persistence.NoResultException e) {
                        FertigungsgruppeDto fertigungsgruppeDto = new FertigungsgruppeDto();

                        fertigungsgruppeDto.setCBez(StuecklisteFac.FERTIGUNGSGRUPPE_SOFORTVERBRAUCH);
                        fertigungsgruppeDto.setISort(getStuecklisteFac().getNextFertigungsgruppe(theClientDto));

                        Integer i = getStuecklisteFac().createFertigungsgruppe(fertigungsgruppeDto,
                                theClientDto);
                        losDto.setFertigungsgruppeIId(i);
                    }

                }

                MandantDto mandantDto = getMandantFac().mandantFindByPrimaryKey(mandantCNr, theClientDto);
                losDto.setPartnerIIdFertigungsort(mandantDto.getPartnerIId());

                LagerDto lagerDtoAbbuchungslager = getLagerFac()
                        .lagerFindByPrimaryKey(tageslosDto.getLagerIIdAbbuchung());

                String projekt = "Tageslos " + Helper.formatDatum(tHeute, theClientDto.getLocUi()) + " "
                        + lagerDtoAbbuchungslager.getCNr();

                losDto.setCProjekt(projekt);
                losDto.setLagerIIdZiel(getLagerFac().getHauptlagerDesMandanten(theClientDto).getIId());

                losIId = getFertigungFac().createLos(losDto, theClientDto).getIId();

                getFertigungFac().gebeLosAus(losIId, true, false, theClientDto, null);

            } catch (RemoteException e) {
                throwEJBExceptionLPRespectOld(e);
            }

        }
        session.close();
    }
    return losIId;
}

From source file:com.lp.server.fertigung.ejbfac.FertigungFacBean.java

public AuftragNachkalkulationDto getWerteAusUnterlosen(LosDto losDto, BigDecimal bdMenge,
        AuftragNachkalkulationDto abNachkalkulationDto, TheClientDto theClientDto) {

    LossollmaterialDto[] sollmat = lossollmaterialFindByLosIId(losDto.getIId());

    try {/*from   www. j a  va 2 s.  c o m*/

        BigDecimal bdWert = new BigDecimal(0);
        for (int i = 0; i < sollmat.length; i++) {
            LossollmaterialDto lossollmaterialDto = sollmat[i];
            LosistmaterialDto[] istMatDtos = losistmaterialFindByLossollmaterialIId(
                    lossollmaterialDto.getIId());

            for (int j = 0; j < istMatDtos.length; j++) {
                LosistmaterialDto istMatDto = istMatDtos[j];
                Query query = em.createNamedQuery("LagerbewegungfindByBelegartCNrBelegartPositionIId");
                query.setParameter(1, LocaleFac.BELEGART_LOS);
                query.setParameter(2, istMatDto.getIId());
                Collection cl = query.getResultList();

                Iterator it = cl.iterator();

                while (it.hasNext()) {
                    Lagerbewegung l = (Lagerbewegung) it.next();

                    LagerabgangursprungDto[] dtos = getLagerFac()
                            .lagerabgangursprungFindByLagerbewegungIIdBuchung(l.getIIdBuchung());

                    for (int m = 0; m < dtos.length; m++) {
                        // nun die Ursprungsbuchungen suchen
                        Session session2 = FLRSessionFactory.getFactory().openSession();
                        String sQuery2 = "from FLRLagerbewegung lagerbewegung WHERE lagerbewegung.i_id_buchung="
                                + dtos[m].getILagerbewegungidursprung()
                                + " order by lagerbewegung.t_buchungszeit DESC";
                        org.hibernate.Query ursrungsbuchung = session2.createQuery(sQuery2);
                        ursrungsbuchung.setMaxResults(1);

                        java.util.List resultList2 = ursrungsbuchung.list();

                        Iterator itUrsprung = resultList2.iterator();

                        while (itUrsprung.hasNext()) {
                            com.lp.server.artikel.fastlanereader.generated.FLRLagerbewegung lagerbewegung_ursprung = (com.lp.server.artikel.fastlanereader.generated.FLRLagerbewegung) itUrsprung
                                    .next();

                            // Wenn diese aus einer Losablieferung kommt
                            if (lagerbewegung_ursprung.getC_belegartnr()
                                    .equals(LocaleFac.BELEGART_LOSABLIEFERUNG)) {

                                LosablieferungDto laDto = losablieferungFindByPrimaryKey(
                                        lagerbewegung_ursprung.getI_belegartpositionid(), true, theClientDto);

                                LosDto losDtoUnterlos = losFindByPrimaryKey(laDto.getLosIId());
                                BigDecimal sollsatzgroesse = lossollmaterialDto.getNMenge()
                                        .divide(losDto.getNLosgroesse(), 4, BigDecimal.ROUND_HALF_EVEN);

                                abNachkalkulationDto.setBdGestehungswertmaterialist(
                                        abNachkalkulationDto.getBdGestehungswertmaterialist().subtract(
                                                laDto.getNArbeitszeitwertdetailliert().multiply(bdMenge)));
                                abNachkalkulationDto.setBdGestehungswertarbeitist(
                                        abNachkalkulationDto.getBdGestehungswertarbeitist()
                                                .add(laDto.getNArbeitszeitwertdetailliert().multiply(bdMenge)));

                                BigDecimal bdGesamtAbgeliefert = getErledigteMenge(laDto.getLosIId(),
                                        theClientDto);
                                Double dPers = getZeiterfassungFac().getSummeZeitenEinesBeleges(
                                        LocaleFac.BELEGART_LOS, losDtoUnterlos.getIId(), null, null, null, null,
                                        theClientDto);

                                BigDecimal arbeitszeitsoll = new BigDecimal(0);

                                BigDecimal maschinenzeitsoll = new BigDecimal(0);
                                LossollarbeitsplanDto[] sollarbeitsplanDtos = getFertigungFac()
                                        .lossollarbeitsplanFindByLosIId(losDtoUnterlos.getIId());

                                for (int u = 0; u < sollarbeitsplanDtos.length; u++) {
                                    LossollarbeitsplanDto sollarbeitsplanDto = sollarbeitsplanDtos[u];

                                    BigDecimal menge = sollarbeitsplanDto.getNGesamtzeit()
                                            .divide(losDtoUnterlos.getNLosgroesse(), 4,
                                                    BigDecimal.ROUND_HALF_EVEN)
                                            .multiply(bdMenge);
                                    /*
                                     * ArtikelDto artikelDto =
                                     * getArtikelFac()
                                     * .artikelFindByPrimaryKeySmall(
                                     * sollarbeitsplanDto
                                     * .getArtikelIIdTaetigkeit(),
                                     * theClientDto);
                                     * 
                                     * myLogger.warn("Los:" +
                                     * losDto.getCNr() + " Unterlos:" +
                                     * losDtoUnterlos.getCNr() + " AZ:" +
                                     * artikelDto.getCNr() + " Zeit:" +
                                     * Helper.rundeKaufmaennisch( menge,
                                     * 4));
                                     */

                                    if (sollarbeitsplanDto.getMaschineIId() == null) {
                                        arbeitszeitsoll = arbeitszeitsoll.add(menge);
                                    } else {
                                        maschinenzeitsoll = maschinenzeitsoll.add(menge);
                                        if (!Helper.short2boolean(sollarbeitsplanDto.getBNurmaschinenzeit())) {
                                            arbeitszeitsoll = arbeitszeitsoll.add(menge);
                                        }

                                    }
                                }

                                abNachkalkulationDto
                                        .setDdArbeitszeitsoll(abNachkalkulationDto.getDdArbeitszeitsoll()
                                                + arbeitszeitsoll.doubleValue());
                                abNachkalkulationDto
                                        .setDdMaschinenzeitsoll(abNachkalkulationDto.getDdMaschinenzeitsoll()
                                                + maschinenzeitsoll.doubleValue());

                                // Zeit duch die Gesamtablieferungen
                                // dividieren und mal bMenge
                                dPers = dPers / bdGesamtAbgeliefert.doubleValue() * bdMenge.doubleValue();
                                abNachkalkulationDto.setDdArbeitszeitist(
                                        abNachkalkulationDto.getDdArbeitszeitist() + dPers);

                                Double dMasch = getZeiterfassungFac().getSummeMaschinenZeitenEinesBeleges(
                                        losDtoUnterlos.getIId(), null, null, theClientDto);

                                dMasch = dMasch / bdGesamtAbgeliefert.doubleValue() * bdMenge.doubleValue();
                                abNachkalkulationDto.setDdMaschinenzeitist(
                                        abNachkalkulationDto.getDdMaschinenzeitist() + dMasch);

                                /*
                                 * System.out.println("Los: " +
                                 * losDto.getCNr() + " Stueckliste: " +
                                 * stklDto.getArtikelDto().getCNr() +
                                 * " UnterlosLos: " +
                                 * losDtoUnterlos.getCNr() + " Artikel: " +
                                 * aDto.getCNr() + " Menge:" + bdMenge);
                                 */

                                abNachkalkulationDto = getWerteAusUnterlosen(losDtoUnterlos,
                                        sollsatzgroesse.multiply(bdMenge), abNachkalkulationDto, theClientDto);

                            }

                        }

                        session2.close();
                    }

                }

            }

        }
    } catch (RemoteException ex) {
        throwEJBExceptionLPRespectOld(ex);

    }
    return abNachkalkulationDto;
}

From source file:uk.ac.horizon.ug.locationbasedgame.client.InformLocation.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {//ww w.  j a v  a  2 s.c  o  m
        // expects: { "conversationId":"...", "clientId":"...", "latitudeE6":123, "longitudeE6":123, 
        // "radiusMetres":1.0, "altitudeMetres":1.0}
        JSONObject jreq = parseObject(req);

        String conversationId = jreq.getString(CONVERSATION_ID);
        Key gameKey = null;
        EntityManager em = EMF.get().createEntityManager();
        try {
            Query q = em.createQuery("SELECT x FROM " + GameClient.class.getSimpleName()
                    + " x WHERE x.currentConversationId = :currentConversationId");
            q.setParameter("currentConversationId", conversationId);
            q.setMaxResults(2);
            List results = q.getResultList();
            if (results.size() > 1)
                logger.log(Level.WARNING, "More than one GameClient with conversationId " + conversationId);
            if (results.size() == 0)
                throw new RequestException(HttpServletResponse.SC_BAD_REQUEST,
                        "conversationId unknonwn: " + conversationId);

            GameClient gc = (GameClient) results.get(0);
            // sanity check
            String clientId = jreq.getString(CLIENT_ID);
            if (!gc.getClientId().equals(clientId))
                throw new RequestException(HttpServletResponse.SC_BAD_REQUEST,
                        "conversationId -> GameClient " + gc + " with different clientId cf. " + clientId);

            ClientLocation cloc = new ClientLocation();
            cloc.setCreatedTime(System.currentTimeMillis());
            cloc.setKey(ClientLocation.makeKey(gc, cloc.getCreatedTime()));
            cloc.setAltitudeMetres((float) jreq.getDouble(ALTITUDE_METRES));
            cloc.setCurrent(true);
            cloc.setGameClientKey(gc.getKey());
            gameKey = gc.getGameKey();
            cloc.setGameKey(gameKey);
            cloc.setLatitudeE6(jreq.getInt(LATITUDE_E6));
            cloc.setLongitudeE6(jreq.getInt(LONGITUDE_E6));
            cloc.setRadiusMetres((float) jreq.getDouble(RADIUS_METRES));

            em.persist(cloc);
            logger.log(Level.FINE, "added ClientLocation: " + cloc);

            // non-current any old one...
            q = em.createQuery("SELECT x FROM " + ClientLocation.class.getSimpleName()
                    + " x WHERE x.gameClientKey= :gameClientKey AND x.current= TRUE AND x.createdTime < :createdTime");
            q.setParameter("gameClientKey", gc.getKey());
            q.setParameter("createdTime", cloc.getCreatedTime());
            List<ClientLocation> clocs = (List<ClientLocation>) q.getResultList();
            for (ClientLocation cl : clocs) {
                cl.setCurrent(false);
                logger.log(Level.FINER, "Marked not current ClientLocation " + cl);
            }
        } finally {
            em.close();
        }

        returnLocations(resp, gameKey);
    } catch (RequestException re) {
        resp.sendError(re.getErrorCode(), re.getMessage());
    } catch (JSONException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.toString());
    }
}