Example usage for javax.persistence TypedQuery setMaxResults

List of usage examples for javax.persistence TypedQuery setMaxResults

Introduction

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

Prototype

TypedQuery<X> setMaxResults(int maxResult);

Source Link

Document

Set the maximum number of results to retrieve.

Usage

From source file:org.openmeetings.app.data.user.Usermanagement.java

/**
 * @param user_level//from w w  w.  j  a  v  a  2  s . c o  m
 * @param start
 * @param max
 * @param orderby
 * @param asc
 * @param search
 * @return
 */
public SearchResult<Users> getUsersListWithSearch(Long user_level, int start, int max, String orderby,
        boolean asc, String search) {
    try {
        if (authLevelManagement.checkAdminLevel(user_level)) {

            String hql = "select c from Users c " + "where c.deleted = 'false' " + "AND ("
                    + "lower(c.login) LIKE :search " + "OR lower(c.firstname) LIKE :search "
                    + "OR lower(c.lastname) LIKE :search " + ")";

            if (orderby.startsWith("c.")) {
                hql += "ORDER BY " + orderby;
            } else {
                hql += "ORDER BY " + "c." + orderby;
            }

            if (asc) {
                hql += " ASC";
            } else {
                hql += " DESC";
            }

            if (search.length() == 0) {
                search = "%";
            } else {
                search = "%" + search + "%";
            }
            log.debug("getUsersList search: " + search);

            SearchResult<Users> sresult = new SearchResult<Users>();
            sresult.setObjectName(Users.class.getName());
            sresult.setRecords(usersDao.selectMaxFromUsersWithSearch(search));

            // get all users
            TypedQuery<Users> query = em.createQuery(hql, Users.class);
            query.setParameter("search", StringUtils.lowerCase(search));
            query.setMaxResults(max);
            query.setFirstResult(start);

            sresult.setResult(query.getResultList());

            return sresult;
        }
    } catch (Exception ex2) {
        log.error("[getUsersList] " + ex2);
    }
    return null;
}

From source file:com.hp.triclops.repository.VehicleRepositoryDAO.java

/**
 * /*from   w  w  w.  j ava2s .co m*/
 * @param id ?null""??
 * @param vin ?null""??
 * @param vendor ?null""??
 * @param model ?null""??
 * @param t_flag 0 ? 1  ??
 * @param displacement ?null""??
 * @param license_plate ?null""??
 * @param start_date ?null??
 * @param end_date ??null??
 * @param orderByProperty ?? Vehicle?,vin
 * @param ascOrDesc ??? "ASC""DESC"  ???,ASC
 * @param pageSize ??? 0
 * @param currentPage ??? 0
 * @param fuzzy ?
 * @param oid id
 * @return  ????Page
 */
public Page findVehiclesByKeys(Integer id, String vin, String vendor, String model, Integer t_flag,
        String displacement, String license_plate, Date start_date, Date end_date, String orderByProperty,
        String ascOrDesc, Integer pageSize, Integer currentPage, Integer fuzzy, Integer oid) {
    String jpql = "select v FROM Vehicle v";
    String jpql_count = "";
    id = (id == null) ? -1 : id;
    vin = (vin == null) ? "" : EscapeStringUtil.toEscape(vin);
    vendor = (vendor == null) ? "" : vendor;
    model = (model == null) ? "" : model;
    displacement = (displacement == null) ? "" : displacement;
    license_plate = (license_plate == null) ? "" : EscapeStringUtil.toEscape(license_plate);
    orderByProperty = (orderByProperty == null) ? "vin" : orderByProperty;
    ascOrDesc = (ascOrDesc == null) ? "ASC" : ascOrDesc;
    t_flag = (t_flag == null) ? -1 : t_flag;
    pageSize = (pageSize == null) ? 10 : pageSize;
    pageSize = (pageSize <= 0) ? 10 : pageSize;
    currentPage = (currentPage == null) ? 1 : currentPage;
    currentPage = (currentPage <= 0) ? 1 : currentPage;

    if (oid != null && oid >= 0) {
        jpql = jpql + " join v.organizationSet O where O.id =:oid";
    } else {
        jpql = jpql + " where 1=1";
    }
    if (id >= 0) {
        jpql = jpql + " And v.id =:id";
    }
    if (!vin.equals("")) {
        jpql = jpql + " And v.vin like :vin";
    }
    if (!vendor.equals("")) {
        jpql = jpql + " And v.vendor like :vendor";
    }
    if (!model.equals("")) {
        jpql = jpql + " And v.model like :model";
    }
    if (!displacement.equals("")) {
        jpql = jpql + " And v.displacement like :displacement";
    }
    if (!license_plate.equals("")) {
        jpql = jpql + " And v.license_plate like :license_plate";
    }
    if (t_flag == 0 || t_flag == 1) {
        jpql = jpql + " And v.t_flag =:t_flag";
    }
    if (start_date != null) {
        jpql = jpql + " And v.product_date >= :start_date";
    }
    if (end_date != null) {
        jpql = jpql + " And v.product_date <= :end_date";
    }
    jpql = jpql + " Order by v." + orderByProperty + " " + ascOrDesc;
    jpql_count = jpql;

    TypedQuery query = em.createQuery(jpql, Vehicle.class);
    TypedQuery queryCount = em.createQuery(jpql_count, Vehicle.class);
    if (oid != null && oid >= 0) {
        query.setParameter("oid", oid);
        queryCount.setParameter("oid", oid);
    }
    if (id >= 0) {
        query.setParameter("id", id);
        queryCount.setParameter("id", id);
    }
    if (!vin.equals("")) {
        query.setParameter("vin", "%" + vin + "%");
        queryCount.setParameter("vin", "%" + vin + "%");
    }
    if (!vendor.equals("")) {
        query.setParameter("vendor", "%" + vendor + "%");
        queryCount.setParameter("vendor", "%" + vendor + "%");
    }
    if (!model.equals("")) {
        query.setParameter("model", "%" + model + "%");
        queryCount.setParameter("model", "%" + model + "%");
    }
    if (!displacement.equals("")) {
        query.setParameter("displacement", "%" + displacement + "%");
        queryCount.setParameter("displacement", "%" + displacement + "%");
    }
    if (!license_plate.equals("")) {
        query.setParameter("license_plate", "%" + license_plate + "%");
        queryCount.setParameter("license_plate", "%" + license_plate + "%");
    }
    if (t_flag == 0 || t_flag == 1) {
        query.setParameter("t_flag", t_flag);
        queryCount.setParameter("t_flag", t_flag);
    }
    if (start_date != null) {
        query.setParameter("start_date", start_date);
        queryCount.setParameter("start_date", start_date);
    }
    if (end_date != null) {
        query.setParameter("end_date", end_date);
        queryCount.setParameter("end_date", end_date);
    }
    query.setFirstResult((currentPage - 1) * pageSize);
    query.setMaxResults(pageSize);
    List items = query.getResultList();
    Long count = (long) queryCount.getResultList().size();
    return new Page(currentPage, pageSize, count, items);
}

From source file:org.openmeetings.app.data.user.Usermanagement.java

public SearchResult<Users> getAllUserByRange(String search, int start, int max, String orderby, boolean asc) {
    try {// www. j  a  va2 s .c o  m
        SearchResult<Users> sresult = new SearchResult<Users>();
        sresult.setObjectName(Users.class.getName());
        sresult.setRecords(usersDao.getAllUserMax(search));

        String[] searchItems = search.split(" ");

        log.debug("getUserContactsBySearch: " + search);
        // log.debug("getUserContactsBySearch: "+ userId);

        String hql = "select u from  Users u " + "WHERE u.deleted = 'false' ";

        hql += "AND ( ";
        for (int i = 0; i < searchItems.length; i++) {
            if (i != 0) {
                hql += " OR ";
            }
            hql += "( " + "lower(u.lastname) LIKE '" + StringUtils.lowerCase("%" + searchItems[i] + "%") + "' "
                    + "OR lower(u.firstname) LIKE '" + StringUtils.lowerCase("%" + searchItems[i] + "%") + "' "
                    + "OR lower(u.login) LIKE '" + StringUtils.lowerCase("%" + searchItems[i] + "%") + "' "
                    + "OR lower(u.adresses.email) LIKE '" + StringUtils.lowerCase("%" + searchItems[i] + "%")
                    + "' " + ") ";

        }

        hql += " ) ";
        if (orderby != null && orderby.length() > 0) {
            hql += "ORDER BY " + orderby;
        }

        if (asc) {
            hql += " ASC ";
        } else {
            hql += " DESC ";
        }

        log.debug("Show HQL: " + hql);

        TypedQuery<Users> query = em.createQuery(hql, Users.class);
        // query.setParameter("macomUserId", userId);

        // query
        // if (asc) ((Criteria) query).addOrder(Order.asc(orderby));
        // else ((Criteria) query).addOrder(Order.desc(orderby));
        query.setFirstResult(start);
        query.setMaxResults(max);
        List<Users> ll = query.getResultList();

        sresult.setResult(ll);

        return sresult;

    } catch (Exception ex2) {
        log.error("[getAllUserByRange] ", ex2);
        ex2.printStackTrace();
    }
    return null;
}

From source file:com.enioka.jqm.api.HibernateClient.java

@Override
public List<com.enioka.jqm.api.JobInstance> getJobs(Query query) {
    if ((query.getFirstRow() != null || query.getPageSize() != null) && query.isQueryLiveInstances()
            && query.isQueryHistoryInstances()) {
        throw new JqmInvalidRequestException("cannot use paging on live instances");
    }// w ww  .j  ava 2s  . c  o m
    if (query.isQueryLiveInstances() && query.isQueryHistoryInstances() && query.getSorts().size() > 0) {
        throw new JqmInvalidRequestException(
                "cannot use sorting when querying both live and historical instances");
    }

    EntityManager em = null;
    try {
        em = getEm();

        // Not using CriteriaBuilder - too much hassle for too little benefit
        String wh = "";
        Map<String, Object> prms = new HashMap<String, Object>();

        // String predicates
        wh += getStringPredicate("userName", query.getUser(), prms);
        wh += getStringPredicate("sessionId", query.getSessionId(), prms);
        wh += getStringPredicate("instanceKeyword1", query.getInstanceKeyword1(), prms);
        wh += getStringPredicate("instanceKeyword2", query.getInstanceKeyword2(), prms);
        wh += getStringPredicate("instanceKeyword3", query.getInstanceKeyword3(), prms);
        wh += getStringPredicate("instanceModule", query.getInstanceModule(), prms);
        wh += getStringPredicate("instanceApplication", query.getInstanceApplication(), prms);

        // Integer
        wh += getIntPredicate("parentId", query.getParentId(), prms);
        wh += getIntPredicate("id", query.getJobInstanceId(), prms);
        wh += getIntPredicate("queue.id", query.getQueueId() == null ? null : query.getQueueId(), prms);

        // Now, run queries...
        List<com.enioka.jqm.api.JobInstance> res2 = new ArrayList<com.enioka.jqm.api.JobInstance>();

        // ////////////////////////////////////////
        // Job Instance query
        if (query.isQueryLiveInstances()) {
            // Sort
            String sort = "";
            for (SortSpec s : query.getSorts()) {
                sort += s.col.getJiField() == null ? ""
                        : ",h." + s.col.getJiField() + " "
                                + (s.order == Query.SortOrder.ASCENDING ? "ASC" : "DESC");
            }
            if (sort.isEmpty()) {
                sort = " ORDER BY h.id";
            } else {
                sort = " ORDER BY " + sort.substring(1);
            }

            // Finish query string
            String wh2 = "" + wh;
            Map<String, Object> prms2 = new HashMap<String, Object>();
            prms2.putAll(prms);
            wh2 += getStringPredicate("queue.name", query.getQueueName(), prms2);

            // tag fields should be looked for in linked object for active JI
            wh2 += getStringPredicate("jd.applicationName", query.getApplicationName(), prms2);
            wh2 += getStringPredicate("jd.keyword1", query.getJobDefKeyword1(), prms2);
            wh2 += getStringPredicate("jd.keyword2", query.getJobDefKeyword2(), prms2);
            wh2 += getStringPredicate("jd.keyword3", query.getJobDefKeyword3(), prms2);
            wh2 += getStringPredicate("jd.module", query.getJobDefModule(), prms2);
            wh2 += getStringPredicate("jd.application", query.getJobDefApplication(), prms2);
            wh2 += getStringPredicate("node.name", query.getNodeName(), prms2);

            // Calendar fields are specific (no common fields between History and JobInstance)
            wh2 += getCalendarPredicate("creationDate", query.getEnqueuedAfter(), ">=", prms2);
            wh2 += getCalendarPredicate("creationDate", query.getEnqueuedBefore(), "<=", prms2);
            wh2 += getCalendarPredicate("executionDate", query.getBeganRunningAfter(), ">=", prms2);
            wh2 += getCalendarPredicate("executionDate", query.getBeganRunningBefore(), "<=", prms2);
            wh2 += getStatusPredicate("state", query.getStatus(), prms2);
            if (wh2.length() >= 3) {
                wh2 = " WHERE " + wh2.substring(3);
            }

            TypedQuery<JobInstance> q2 = em.createQuery(
                    "SELECT h FROM JobInstance h LEFT JOIN FETCH h.jd LEFT JOIN FETCH h.node " + wh2 + sort,
                    JobInstance.class);
            for (Map.Entry<String, Object> entry : prms2.entrySet()) {
                q2.setParameter(entry.getKey(), entry.getValue());
            }
            if (query.getFirstRow() != null) {
                q2.setFirstResult(query.getFirstRow());
            }
            if (query.getPageSize() != null) {
                q2.setMaxResults(query.getPageSize());
            }
            if (query.getFirstRow() != null || query.getPageSize() != null) {
                TypedQuery<Long> qCount = em.createQuery("SELECT COUNT(h) FROM JobInstance h " + wh2,
                        Long.class);
                for (Map.Entry<String, Object> entry : prms2.entrySet()) {
                    qCount.setParameter(entry.getKey(), entry.getValue());
                }
                query.setResultSize(new BigDecimal(qCount.getSingleResult()).intValueExact());
            }

            for (JobInstance ji : q2.getResultList()) {
                res2.add(getJob(ji, em));
            }
        }

        // ////////////////////////////////////////
        // History query
        if (query.isQueryHistoryInstances()) {
            wh += getStringPredicate("queueName", query.getQueueName(), prms);

            // tag fields should be looked directly in the denormalized fields for history.
            wh += getStringPredicate("applicationName", query.getApplicationName(), prms);
            wh += getStringPredicate("keyword1", query.getJobDefKeyword1(), prms);
            wh += getStringPredicate("keyword2", query.getJobDefKeyword2(), prms);
            wh += getStringPredicate("keyword3", query.getJobDefKeyword3(), prms);
            wh += getStringPredicate("module", query.getJobDefModule(), prms);
            wh += getStringPredicate("application", query.getJobDefApplication(), prms);
            wh += getStringPredicate("nodeName", query.getNodeName(), prms);

            // Calendar fields are specific (no common fields between History and JobInstance)
            wh += getCalendarPredicate("enqueueDate", query.getEnqueuedAfter(), ">=", prms);
            wh += getCalendarPredicate("enqueueDate", query.getEnqueuedBefore(), "<=", prms);
            wh += getCalendarPredicate("executionDate", query.getBeganRunningAfter(), ">=", prms);
            wh += getCalendarPredicate("executionDate", query.getBeganRunningBefore(), "<=", prms);
            wh += getCalendarPredicate("endDate", query.getEndedAfter(), ">=", prms);
            wh += getCalendarPredicate("endDate", query.getEndedBefore(), "<=", prms);
            wh += getStatusPredicate("status", query.getStatus(), prms);
            if (wh.length() >= 3) {
                wh = " WHERE " + wh.substring(3);
            }

            // Order by
            String sort = "";
            for (SortSpec s : query.getSorts()) {
                sort += ",h." + s.col.getHistoryField() + " "
                        + (s.order == Query.SortOrder.ASCENDING ? "ASC" : "DESC");
            }
            if (sort.isEmpty()) {
                sort = " ORDER BY h.id";
            } else {
                sort = " ORDER BY " + sort.substring(1);
            }

            TypedQuery<History> q1 = em.createQuery(
                    "SELECT h FROM History h LEFT JOIN FETCH h.jd LEFT JOIN FETCH h.node LEFT JOIN FETCH h.queue "
                            + wh + sort,
                    History.class);
            for (Map.Entry<String, Object> entry : prms.entrySet()) {
                q1.setParameter(entry.getKey(), entry.getValue());
            }
            if (query.getFirstRow() != null) {
                q1.setFirstResult(query.getFirstRow());
            }
            if (query.getPageSize() != null) {
                q1.setMaxResults(query.getPageSize());
            }
            if (query.getFirstRow() != null || query.getPageSize() != null) {
                TypedQuery<Long> qCount = em.createQuery("SELECT COUNT(h) FROM History h " + wh, Long.class);
                for (Map.Entry<String, Object> entry : prms.entrySet()) {
                    qCount.setParameter(entry.getKey(), entry.getValue());
                }
                query.setResultSize(new BigDecimal(qCount.getSingleResult()).intValueExact());
            }

            // Optimization: fetch messages and parameters in one go.
            List<History> results = q1.getResultList();
            List<Integer> ids = new ArrayList<Integer>();
            for (History ji : results) {
                ids.add(ji.getId());
            }
            if (!ids.isEmpty()) {
                List<RuntimeParameter> rps = em
                        .createQuery("SELECT rp FROM RuntimeParameter rp WHERE rp.ji IN (:p)",
                                RuntimeParameter.class)
                        .setParameter("p", ids).getResultList();
                List<Message> msgs = em
                        .createQuery("SELECT rp FROM Message rp WHERE rp.ji IN (:p)", Message.class)
                        .setParameter("p", ids).getResultList();

                for (History ji : results) {
                    res2.add(getJob(ji, em, rps, msgs));
                }
            }
        }

        query.setResults(res2);
        return res2;
    } catch (Exception e) {
        throw new JqmClientException("an error occured during query execution", e);
    } finally {
        closeQuietly(em);
    }
}

From source file:io.apiman.manager.api.jpa.JpaStorage.java

/**
 * @see io.apiman.manager.api.core.IStorageQuery#getPermissions(java.lang.String)
 */// w ww.j  a va 2  s. co m
@Override
public Set<PermissionBean> getPermissions(String userId) throws StorageException {
    Set<PermissionBean> permissions = new HashSet<>();
    beginTx();
    try {
        EntityManager entityManager = getActiveEntityManager();
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<RoleMembershipBean> criteriaQuery = builder.createQuery(RoleMembershipBean.class);
        Root<RoleMembershipBean> from = criteriaQuery.from(RoleMembershipBean.class);
        criteriaQuery.where(builder.equal(from.get("userId"), userId));
        TypedQuery<RoleMembershipBean> typedQuery = entityManager.createQuery(criteriaQuery);
        typedQuery.setMaxResults(500);
        List<RoleMembershipBean> resultList = typedQuery.getResultList();
        for (RoleMembershipBean membership : resultList) {
            RoleBean role = getRoleInternal(membership.getRoleId());
            String qualifier = membership.getOrganizationId();
            for (PermissionType permission : role.getPermissions()) {
                PermissionBean p = new PermissionBean();
                p.setName(permission);
                p.setOrganizationId(qualifier);
                permissions.add(p);
            }
        }
        return permissions;
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        throw new StorageException(t);
    } finally {
        rollbackTx();
    }
}

From source file:gov.opm.scrd.batchprocessing.jobs.BatchProcessingJob.java

/**
 * Initialize today's audit batch.//from   w  ww . ja v a 2  s .c  o  m
 *
 * @param today The today.
 * @throws BatchProcessingException If major error occurred.
 */
private void initTodayAuditBatch(Date today) throws BatchProcessingException {
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(today.getTime());
    int year = cal.get(Calendar.YEAR);
    int month = cal.get(Calendar.MONTH) + 1;
    int day = cal.get(Calendar.DAY_OF_MONTH);

    try {
        // Query today's AuditBatch with max id
        TypedQuery<AuditBatch> query = entityManager
                .createQuery("select e from AuditBatch e where e.eventYear=:eventYear "
                        + "AND e.eventMonth=:eventMonth AND e.eventDay=:eventDay "
                        + "AND e.userKey=:userKey order by e.id desc", AuditBatch.class);
        query.setParameter("eventYear", year);
        query.setParameter("eventMonth", month);
        query.setParameter("eventDay", day);
        query.setParameter("userKey", batchProcessUser.getId());

        query.setMaxResults(1);

        List<AuditBatch> result = query.getResultList();

        if (result == null || result.isEmpty()) {
            // Today's AuditBatch not exist yet, create it
            AuditBatch ab = new AuditBatch();
            ab.setEventYear(year);
            ab.setEventMonth(month);
            ab.setEventDay(day);
            ab.setUserKey(batchProcessUser.getId());
            ab.setBatchTime(today);
            ab.setAmountImported(BigDecimal.ZERO);
            ab.setAmountProcessed(BigDecimal.ZERO);
            ab.setErrorImporting(false);
            ab.setErrorProcessing(false);
            ab.setErrorCountProcessing(0);
            ab.setErrorCountImporting(0);
            ab.setNumberChangeRequests(0);
            ab.setAchStopLetters(0);
            ab.setInitialBillsProcessed(0);
            ab.setPaymentsProcessed(0);
            ab.setRefundMemos(0);
            ab.setReversedProcessed(0);
            ab.setNumberAccepted(0);
            ab.setNumberSuspended(0);
            ab.setNumberUnresolved(0);
            ab.setNumberAchAccepted(0);
            ab.setNumberAchSuspended(0);
            ab.setNumberAchUnresolved(0);
            todayAuditBatch = persistEntity(ab);
        } else {
            todayAuditBatch = result.get(0);
        }

    } catch (PersistenceException pe) {
        throw new BatchProcessingException("Database error while getting audit batch log", pe);
    }
}

From source file:gov.osti.services.Metadata.java

/**
 * Get previous snapshot info for use in backfill process that occurs after current snapshot is updated.
 *
 * @param em the EntityManager to control commits.
 * @param md the Metadata to evaluate for RI backfilling.
 * @return List of RelatedIdentifier objects.
 *//*from  w w w.  ja  va  2 s .c o  m*/
private List<RelatedIdentifier> getPreviousRiList(EntityManager em, DOECodeMetadata md) throws IOException {
    // if current project has no DOI, there is nothing to process later on, so do not pull previous info
    if (StringUtils.isBlank(md.getDoi()))
        return null;

    long codeId = md.getCodeId();

    // pull last know Approved info
    TypedQuery<MetadataSnapshot> querySnapshot = em
            .createNamedQuery("MetadataSnapshot.findByCodeIdAndStatus", MetadataSnapshot.class)
            .setParameter("codeId", codeId).setParameter("status", DOECodeMetadata.Status.Approved);

    List<MetadataSnapshot> results = querySnapshot.setMaxResults(1).getResultList();

    // get previous Approved RI list, if applicable
    List<RelatedIdentifier> previousList = new ArrayList<>();
    for (MetadataSnapshot ms : results) {
        try {
            DOECodeMetadata pmd = DOECodeMetadata.parseJson(new StringReader(ms.getJson()));

            previousList = pmd.getRelatedIdentifiers();

            if (previousList == null)
                previousList = new ArrayList<>();

            // filter to targeted RI
            previousList = previousList.stream().filter(p -> p.getIdentifierType() == RelatedIdentifier.Type.DOI
                    && (p.getRelationType() == RelatedIdentifier.RelationType.IsNewVersionOf
                            || p.getRelationType() == RelatedIdentifier.RelationType.IsPreviousVersionOf))
                    .collect(Collectors.toList());

        } catch (IOException ex) {
            // unable to parse JSON, but for this process
            String msg = "Unable to parse previously 'Approved' Snapshot JSON for " + codeId + ": "
                    + ex.getMessage();
            throw new IOException(msg);
        }
        break; // failsafe: there should only ever be one, at most
    }

    return previousList;
}

From source file:ca.uhn.fhir.jpa.dao.BaseFhirResourceDao.java

@Override
public IBundleProvider history(final IdDt theId, final Date theSince) {
    final InstantDt end = createHistoryToTimestamp();
    final String resourceType = getContext().getResourceDefinition(myResourceType).getName();

    T currentTmp;/* www . j  a  v a  2 s.  c o m*/
    try {
        BaseHasResource entity = readEntity(theId.toVersionless(), false);
        validateResourceType(entity);
        currentTmp = toResource(myResourceType, entity);
        if (ResourceMetadataKeyEnum.UPDATED.get(currentTmp).after(end.getValue())) {
            currentTmp = null;
        }
    } catch (ResourceNotFoundException e) {
        currentTmp = null;
    }

    final T current = currentTmp;

    String querySring = "SELECT count(h) FROM ResourceHistoryTable h "
            + "WHERE h.myResourceId = :PID AND h.myResourceType = :RESTYPE" + " AND h.myUpdated < :END"
            + (theSince != null ? " AND h.myUpdated >= :SINCE" : "");
    TypedQuery<Long> countQuery = myEntityManager.createQuery(querySring, Long.class);
    countQuery.setParameter("PID", translateForcedIdToPid(theId));
    countQuery.setParameter("RESTYPE", resourceType);
    countQuery.setParameter("END", end.getValue(), TemporalType.TIMESTAMP);
    if (theSince != null) {
        countQuery.setParameter("SINCE", theSince, TemporalType.TIMESTAMP);
    }
    int historyCount = countQuery.getSingleResult().intValue();

    final int offset;
    final int count;
    if (current != null) {
        count = historyCount + 1;
        offset = 1;
    } else {
        offset = 0;
        count = historyCount;
    }

    if (count == 0) {
        throw new ResourceNotFoundException(theId);
    }

    return new IBundleProvider() {

        @Override
        public InstantDt getPublished() {
            return end;
        }

        @Override
        public List<IResource> getResources(int theFromIndex, int theToIndex) {
            ArrayList<IResource> retVal = new ArrayList<IResource>();
            if (theFromIndex == 0 && current != null) {
                retVal.add(current);
            }

            TypedQuery<ResourceHistoryTable> q = myEntityManager.createQuery(
                    "SELECT h FROM ResourceHistoryTable h WHERE h.myResourceId = :PID AND h.myResourceType = :RESTYPE AND h.myUpdated < :END "
                            + (theSince != null ? " AND h.myUpdated >= :SINCE" : "")
                            + " ORDER BY h.myUpdated ASC",
                    ResourceHistoryTable.class);
            q.setParameter("PID", translateForcedIdToPid(theId));
            q.setParameter("RESTYPE", resourceType);
            q.setParameter("END", end.getValue(), TemporalType.TIMESTAMP);
            if (theSince != null) {
                q.setParameter("SINCE", theSince, TemporalType.TIMESTAMP);
            }

            int firstResult = Math.max(0, theFromIndex - offset);
            q.setFirstResult(firstResult);

            int maxResults = (theToIndex - theFromIndex) + 1;
            q.setMaxResults(maxResults);

            List<ResourceHistoryTable> results = q.getResultList();
            for (ResourceHistoryTable next : results) {
                if (retVal.size() == maxResults) {
                    break;
                }
                retVal.add(toResource(myResourceType, next));
            }

            return retVal;
        }

        @Override
        public Integer preferredPageSize() {
            return null;
        }

        @Override
        public int size() {
            return count;
        }
    };

}

From source file:gov.osti.services.Metadata.java

/**
 * Acquire a List of records in pending ("Submitted") state, to be approved
 * for indexing and searching./*from w w w  .j  ava  2  s  .c om*/
 *
 * JSON response is of the form:
 *
 * {"records":[{"code_id":n, ...} ],
 *  "start":0, "rows":20, "total":100}
 *
 * Where records is an array of DOECodeMetadata JSON, start is the beginning
 * row number, rows is the number requested (or total if less available),
 * and total is the total number of rows matching the filter.
 *
 * Return Codes:
 * 200 - OK, JSON is returned as above
 * 401 - Unauthorized, login is required
 * 403 - Forbidden, insufficient privileges (role required)
 * 500 - unexpected error
 *
 * @param start the starting row number (from 0)
 * @param rows number of rows desired (0 is unlimited)
 * @param siteCode (optional) a SITE OWNERSHIP CODE to filter by site
 * @param state the WORKFLOW STATE if desired (default Submitted and Announced). One of
 * Approved, Saved, Submitted, or Announced, if supplied.
 * @return JSON of a records response
 */
@GET
@Path("/projects/pending")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@RequiresAuthentication
@RequiresRoles("OSTI")
public Response listProjectsPending(@QueryParam("start") int start, @QueryParam("rows") int rows,
        @QueryParam("site") String siteCode, @QueryParam("state") String state) {
    EntityManager em = DoeServletContextListener.createEntityManager();

    try {
        // get a JPA CriteriaBuilder instance
        CriteriaBuilder cb = em.getCriteriaBuilder();
        // create a CriteriaQuery for the COUNT
        CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
        Root<DOECodeMetadata> md = countQuery.from(DOECodeMetadata.class);
        countQuery.select(cb.count(md));

        Expression<String> workflowStatus = md.get("workflowStatus");
        Expression<String> siteOwnershipCode = md.get("siteOwnershipCode");

        // default requested STATE; take Submitted and Announced as the default values if not supplied
        List<DOECodeMetadata.Status> requestedStates = new ArrayList();
        String queryState = (StringUtils.isEmpty(state)) ? "" : state.toLowerCase();
        switch (queryState) {
        case "approved":
            requestedStates.add(DOECodeMetadata.Status.Approved);
            break;
        case "saved":
            requestedStates.add(DOECodeMetadata.Status.Saved);
            break;
        case "submitted":
            requestedStates.add(DOECodeMetadata.Status.Submitted);
            break;
        case "announced":
            requestedStates.add(DOECodeMetadata.Status.Announced);
            break;
        default:
            requestedStates.add(DOECodeMetadata.Status.Submitted);
            requestedStates.add(DOECodeMetadata.Status.Announced);
            break;
        }

        Predicate statusPredicate = workflowStatus.in(requestedStates);
        ParameterExpression<String> site = cb.parameter(String.class, "site");

        if (null == siteCode) {
            countQuery.where(statusPredicate);
        } else {
            countQuery.where(cb.and(statusPredicate, cb.equal(siteOwnershipCode, site)));
        }
        // query for the COUNT
        TypedQuery<Long> cq = em.createQuery(countQuery);
        cq.setParameter("status", requestedStates);
        if (null != siteCode)
            cq.setParameter("site", siteCode);

        long rowCount = cq.getSingleResult();
        // rows count should be less than 100 for pagination; 0 is a special case
        rows = (rows > 100) ? 100 : rows;

        // create a CriteriaQuery for the ROWS
        CriteriaQuery<DOECodeMetadata> rowQuery = cb.createQuery(DOECodeMetadata.class);
        rowQuery.select(md);

        if (null == siteCode) {
            rowQuery.where(statusPredicate);
        } else {
            rowQuery.where(cb.and(statusPredicate, cb.equal(siteOwnershipCode, site)));
        }

        TypedQuery<DOECodeMetadata> rq = em.createQuery(rowQuery);
        rq.setParameter("status", requestedStates);
        if (null != siteCode)
            rq.setParameter("site", siteCode);
        rq.setFirstResult(start);
        if (0 != rows)
            rq.setMaxResults(rows);

        RecordsList records = new RecordsList(rq.getResultList());
        records.setTotal(rowCount);
        records.setStart(start);

        return Response.ok().entity(mapper.valueToTree(records).toString()).build();
    } finally {
        em.close();
    }
}

From source file:com.clustercontrol.jobmanagement.factory.SelectJob.java

/**
 * ???????<BR>//  ww  w. j a  v a 2 s. c om
 * ?????????
 * <p>
 * <ol>
 * <li>???????</li>
 * <li>?????????</li>
 *  <ol>
 *  <li>?????</li>
 *  <li>?????</li>
 *  <li>1??{@link com.clustercontrol.jobmanagement.bean.HistoryTableDefine}??{@link ArrayList}????</li>
 *   <dl>
 *   <dt>Object?2?</dt>
 *   <dd>{ 1 {1?, 2?,  }, 2{1?, 2?, },  }</dd>
 *  </dl>
 *  </ol>
 *  <li>?{@link com.clustercontrol.jobmanagement.bean.JobHistoryList}?????</li>
 * </ol>
 *
 * @param userId ?ID
 * @param property ?
 * @param histories 
 * @return 
 * @throws JobInfoNotFound
 *
 * @see com.clustercontrol.bean.JobConstant
 */
public JobHistoryList getHistoryList(String userId, JobHistoryFilter property, int histories)
        throws JobInfoNotFound {

    m_log.debug("getHistoryList() start : userId = " + userId + ", histories = " + histories);

    Long startFromDate = null;
    Long startToDate = null;
    Long endFromDate = null;
    Long endToDate = null;
    String jobId = null;
    Integer status = null;
    Integer endStatus = null;
    Integer triggerType = null;
    String triggerInfo = null;
    String ownerRoleId = null;

    if (property != null) {
        if (property.getStartFromDate() != null) {
            startFromDate = property.getStartFromDate();
        }
        if (property.getStartToDate() != null) {
            startToDate = property.getStartToDate();
        }
        if (property.getEndFromDate() != null) {
            endFromDate = property.getEndFromDate();
        }
        if (property.getEndToDate() != null) {
            endToDate = property.getEndToDate();
        }
        jobId = property.getJobId();
        status = property.getStatus();
        endStatus = property.getEndStatus();
        triggerType = property.getTriggerType();
        triggerInfo = property.getTriggerInfo();
        ownerRoleId = property.getOwnerRoleId();

        m_log.debug("getHistoryList() property" + " startFromDate = " + startFromDate + ", startToDate = "
                + startToDate + ", endFromDate = " + endFromDate + ", endToDate = " + endToDate + ", jobId = "
                + jobId + ", status = " + status + ", endStatus = " + endStatus + ", triggerType = "
                + triggerType + ", triggerInfo = " + triggerInfo + ", ownerRoleId = " + ownerRoleId);
    } else {
        m_log.debug("getHistoryList() property is null");
    }

    JobHistoryList list = new JobHistoryList();
    ArrayList<JobHistory> historyList = new ArrayList<JobHistory>();
    int total = 0;

    if (histories <= 0) {
        histories = MAX_DISPLAY_NUMBER;
    }
    Integer limit = histories + 1;

    //????
    TypedQuery<?> typedQuery = getHistoryFilterQuery(startFromDate, startToDate, endFromDate, endToDate, jobId,
            status, endStatus, triggerType, triggerInfo, ownerRoleId, false);
    if (limit != null) {
        typedQuery = typedQuery.setMaxResults(limit);
    }

    @SuppressWarnings("unchecked")
    List<JobSessionJobEntity> sessionJobList = (List<JobSessionJobEntity>) typedQuery.getResultList();

    if (sessionJobList == null) {
        JobInfoNotFound je = new JobInfoNotFound();
        je.setJobId(jobId);
        m_log.info("getHistoryList() : " + je.getClass().getSimpleName() + ", " + je.getMessage());
    }
    m_log.debug("getHistoryList() target sessionList exist");

    if (sessionJobList != null) {

        //
        if (sessionJobList.size() > histories) {
            //????
            TypedQuery<?> countTypedQuery = getHistoryFilterQuery(startFromDate, startToDate, endFromDate,
                    endToDate, jobId, status, endStatus, triggerType, triggerInfo, ownerRoleId, true);
            total = (int) ((Long) countTypedQuery.getSingleResult()).longValue();
        } else {
            total = sessionJobList.size();
        }
        m_log.debug("getHistoryList() total = " + total);

        for (JobSessionJobEntity sessionJob : sessionJobList) {
            // JobSession?
            JobSessionEntity session = sessionJob.getJobSessionEntity();
            // JobInfoEntity?
            JobInfoEntity jobInfo = sessionJob.getJobInfoEntity();
            //??
            JobHistory info = new JobHistory();
            info.setStatus(sessionJob.getStatus());
            info.setEndStatus(sessionJob.getEndStatus());
            info.setEndValue(sessionJob.getEndValue());
            info.setSessionId(sessionJob.getId().getSessionId());
            info.setJobId(sessionJob.getId().getJobId());
            info.setJobunitId(sessionJob.getId().getJobunitId());
            info.setJobName(jobInfo.getJobName());
            info.setJobType(jobInfo.getJobType());
            if (jobInfo.getJobType() == JobConstant.TYPE_JOB
                    || jobInfo.getJobType() == JobConstant.TYPE_APPROVALJOB
                    || jobInfo.getJobType() == JobConstant.TYPE_MONITORJOB) {
                info.setFacilityId(jobInfo.getFacilityId());
                info.setScope(sessionJob.getScopeText());
            }
            info.setOwnerRoleId(sessionJob.getOwnerRoleId());
            if (session.getScheduleDate() != null) {
                info.setScheduleDate(session.getScheduleDate());
            }
            if (sessionJob.getStartDate() != null) {
                info.setStartDate(sessionJob.getStartDate());
            }
            if (sessionJob.getEndDate() != null) {
                info.setEndDate(sessionJob.getEndDate());
            }
            if (session.getTriggerInfo() != null && !session.getTriggerInfo().equals("")) {
                info.setJobTriggerType(session.getTriggerType());
                info.setTriggerInfo(session.getTriggerInfo());
            }
            historyList.add(info);

            //????????
            if (historyList.size() >= histories)
                break;
        }
    }
    list.setTotal(total);
    list.setList(historyList);

    return list;
}