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:gov.gtas.repository.CaseDispositionRepositoryImpl.java

@Override
public Pair<Long, List<Case>> findByCriteria(CaseRequestDto dto) {

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Case> q = cb.createQuery(Case.class);
    Root<Case> root = q.from(Case.class);
    List<Predicate> predicates = new ArrayList<>();

    TypedQuery<Case> typedQuery = em.createQuery(q);

    // sorting/*from  www  .  j  av a  2s  .  co m*/
    if (dto.getSort() != null) {
        List<Order> orders = new ArrayList<>();
        for (SortOptionsDto sort : dto.getSort()) {
            Expression<?> e = root.get(sort.getColumn());
            Order order;
            if ("desc".equalsIgnoreCase(sort.getDir())) {
                order = cb.desc(e);
            } else {
                order = cb.asc(e);
            }
            orders.add(order);
        }
        q.orderBy(orders);
    }

    if (dto.getFlightId() != null) {
        predicates.add(cb.equal(root.<Long>get("flightId"), dto.getFlightId()));
    }

    if (dto.getPaxId() != null) {
        predicates.add(cb.equal(root.<Long>get("paxId"), dto.getPaxId()));
    }

    if (dto.getPaxName() != null) {
        String likeString = String.format("%%%s%%", dto.getPaxName().toUpperCase());
        predicates.add(cb.like(root.<String>get("paxName"), likeString));
    }

    if (dto.getLastName() != null) { // map this to full pax name
        String likeString = String.format("%%%s%%", dto.getLastName().toUpperCase());
        predicates.add(cb.like(root.<String>get("paxName"), likeString));
    }

    if (dto.getStatus() != null) {
        String likeString = String.format("%%%s%%", dto.getStatus().toUpperCase());
        predicates.add(cb.like(root.<String>get("status"), likeString));
    }

    if (dto.getFlightNumber() != null) {
        predicates.add(cb.equal(root.<Long>get("flightNumber"), dto.getFlightNumber()));
    }

    if (dto.getRuleCatId() != null) {
        predicates.add(cb.equal(root.<Long>get("highPriorityRuleCatId"), dto.getRuleCatId()));
    }

    Predicate etaCondition;
    if (dto.getEtaStart() != null && dto.getEtaEnd() != null) {

        Path<Date> eta = root.<Date>get("flightETADate");
        Predicate startPredicate = cb.or(cb.isNull(eta), cb.greaterThanOrEqualTo(eta, dto.getEtaStart()));
        Predicate endPredicate = cb.or(cb.isNull(eta), cb.lessThanOrEqualTo(eta, dto.getEtaEnd()));
        etaCondition = cb.and(startPredicate, endPredicate);
        predicates.add(etaCondition);
    }

    q.select(root).where(predicates.toArray(new Predicate[] {}));
    typedQuery = em.createQuery(q);

    // total count
    CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
    countQuery.select(cb.count(countQuery.from(Case.class))).where(predicates.toArray(new Predicate[] {}));
    Long count = em.createQuery(countQuery).getSingleResult();

    // pagination
    int pageNumber = dto.getPageNumber();
    int pageSize = dto.getPageSize();
    int firstResultIndex = (pageNumber - 1) * pageSize;
    typedQuery.setFirstResult(firstResultIndex);
    typedQuery.setMaxResults(dto.getPageSize());

    logger.debug(typedQuery.unwrap(org.hibernate.Query.class).getQueryString());
    List<Case> results = typedQuery.getResultList();

    return new ImmutablePair<>(count, results);

}

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

/**
 * Handle SUBMIT workflow logic.//from   w  ww.j  a  va 2  s. c  o  m
 *
 * @param json JSON String containing the METADATA object to SUBMIT
 * @param file (optional) a FILE associated with this METADATA
 * @param fileInfo (optional) the FILE disposition information, if any
 * @param container (optional) a CONTAINER IMAGE associated with this METADATA
 * @param containerInfo (optional) the CONTAINER IMAGE disposition information, if any
 * @return an appropriate Response object to the caller
 */
private Response doSubmit(String json, InputStream file, FormDataContentDisposition fileInfo,
        InputStream container, FormDataContentDisposition containerInfo) {
    EntityManager em = DoeServletContextListener.createEntityManager();
    Subject subject = SecurityUtils.getSubject();
    User user = (User) subject.getPrincipal();

    try {
        validateUploads(fileInfo, containerInfo);

        DOECodeMetadata md = DOECodeMetadata.parseJson(new StringReader(json));

        Long currentCodeId = md.getCodeId();
        boolean previouslySaved = false;
        if (currentCodeId != null) {
            DOECodeMetadata emd = em.find(DOECodeMetadata.class, currentCodeId);

            if (emd != null)
                previouslySaved = Status.Saved.equals(emd.getWorkflowStatus());
        }

        // lookup Announced Snapshot status
        TypedQuery<MetadataSnapshot> querySnapshot = em
                .createNamedQuery("MetadataSnapshot.findByCodeIdAndStatus", MetadataSnapshot.class)
                .setParameter("codeId", currentCodeId).setParameter("status", DOECodeMetadata.Status.Announced);

        List<MetadataSnapshot> results = querySnapshot.setMaxResults(1).getResultList();
        if (results.size() > 0) {
            log.error("Cannot Submit, Previously Announced: " + currentCodeId);
            return ErrorResponse.internalServerError(
                    "This record was previously Announced to E-Link, if you need to update the metadata, please change your endpoint to \"/announce.\"")
                    .build();
        }

        em.getTransaction().begin();

        performDataNormalization(md);

        // set the ownership and workflow status
        md.setOwner(user.getEmail());
        md.setWorkflowStatus(Status.Submitted);
        md.setSiteOwnershipCode(user.getSiteId());

        // store it
        store(em, md, user);

        // re-attach metadata to transaction in order to store any changes beyond this point
        md = em.find(DOECodeMetadata.class, md.getCodeId());

        // if there's a FILE associated here, store it
        String fullFileName = "";
        if (null != file && null != fileInfo) {
            try {
                fullFileName = writeFile(file, md.getCodeId(), fileInfo.getFileName(), FILE_UPLOADS);
                md.setFileName(fullFileName);
            } catch (IOException e) {
                log.error("File Upload Failed: " + e.getMessage());
                return ErrorResponse.internalServerError("File upload failed.").build();
            }
        }

        // if there's a CONTAINER IMAGE associated here, store it
        String fullContainerName = "";
        if (null != container && null != containerInfo) {
            try {
                fullContainerName = writeFile(container, md.getCodeId(), containerInfo.getFileName(),
                        CONTAINER_UPLOADS);
                md.setContainerName(fullContainerName);
            } catch (IOException e) {
                log.error("Container Image Upload Failed: " + e.getMessage());
                return ErrorResponse.internalServerError("Container Image upload failed.").build();
            }
        }

        // check validations for Submitted workflow
        List<String> errors = validateSubmit(md);
        if (!errors.isEmpty()) {
            // generate a JSONAPI errors object
            return ErrorResponse.badRequest(errors).build();
        }

        // create OSTI Hosted project, as needed
        try {
            // process local GitLab, if needed
            processOSTIGitLab(md);
        } catch (Exception e) {
            log.error("OSTI GitLab failure: " + e.getMessage());
            return ErrorResponse.internalServerError("Unable to create OSTI Hosted project: " + e.getMessage())
                    .build();
        }

        // send this file upload along to archiver if configured
        try {
            // if no file/container, but previously Saved with a file/container, we need to attach to those streams and send to Archiver
            if (previouslySaved) {
                if (null == file && !StringUtils.isBlank(md.getFileName())) {
                    java.nio.file.Path destination = Paths.get(FILE_UPLOADS, String.valueOf(md.getCodeId()),
                            md.getFileName());
                    fullFileName = destination.toString();
                    file = Files.newInputStream(destination);
                }
                if (null == container && !StringUtils.isBlank(md.getContainerName())) {
                    java.nio.file.Path destination = Paths.get(CONTAINER_UPLOADS,
                            String.valueOf(md.getCodeId()), md.getContainerName());
                    fullContainerName = destination.toString();
                    container = Files.newInputStream(destination);
                }
            }

            // if a FILE or CONTAINER was sent, create a File Object from it
            File archiveFile = (null == file) ? null : new File(fullFileName);
            File archiveContainer = null; //(null==container) ? null : new File(fullContainerName);
            if (DOECodeMetadata.Accessibility.CO.equals(md.getAccessibility()))
                // if CO project type, no need to archive the repo because it is local GitLab
                sendToArchiver(md.getCodeId(), null, archiveFile, archiveContainer);
            else
                sendToArchiver(md.getCodeId(), md.getRepositoryLink(), archiveFile, archiveContainer);
        } catch (IOException e) {
            log.error("Archiver call failure: " + e.getMessage());
            return ErrorResponse.internalServerError("Unable to archive project.").build();
        }

        // send to DataCite if needed (and there is a RELEASE DATE set)
        if (null != md.getDoi() && null != md.getReleaseDate()) {
            try {
                DataCite.register(md);
            } catch (IOException e) {
                // tell why the DataCite registration failed
                log.warn("DataCite ERROR: " + e.getMessage());
                return ErrorResponse.internalServerError(
                        "The DOI registration service is currently unavailable, please try to submit your record later. If the issue persists, please contact doecode@osti.gov.")
                        .build();
            }
        }

        // store the snapshot copy of Metadata
        MetadataSnapshot snapshot = new MetadataSnapshot();
        snapshot.getSnapshotKey().setCodeId(md.getCodeId());
        snapshot.getSnapshotKey().setSnapshotStatus(md.getWorkflowStatus());
        snapshot.setDoi(md.getDoi());
        snapshot.setDoiIsMinted(md.getReleaseDate() != null);
        snapshot.setJson(md.toJson().toString());

        em.merge(snapshot);

        // commit it
        em.getTransaction().commit();

        // send NOTIFICATION if configured to do so
        sendStatusNotification(md);

        // we are done here
        return Response.ok().entity(mapper.createObjectNode().putPOJO("metadata", md.toJson()).toString())
                .build();
    } catch (BadRequestException e) {
        return e.getResponse();
    } catch (NotFoundException e) {
        return ErrorResponse.notFound(e.getMessage()).build();
    } catch (IllegalAccessException e) {
        log.warn("Persistence Error: Unable to update record, invalid owner: " + user.getEmail());
        log.warn("Message: " + e.getMessage());
        return ErrorResponse.forbidden("Logged in User is not allowed to modify this record.").build();
    } catch (ValidationException e) {
        log.warn("Validation Error: " + e.getMessage());
        return ErrorResponse.badRequest(e.getMessage()).build();
    } catch (IOException | InvocationTargetException e) {
        if (em.getTransaction().isActive())
            em.getTransaction().rollback();

        log.warn("Persistence Error Submitting: " + e.getMessage());
        return ErrorResponse.internalServerError("Persistence error submitting record.").build();
    } finally {
        em.close();
    }
}

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

public List<Users> searchUserProfile(String searchTxt, String userOffers, String userSearchs, String orderBy,
        int start, int max, boolean asc) {
    try {//  w  w  w.  j a  v a  2  s .  co  m

        String hql = "select c from Users c " + "where c.deleted = 'false' ";

        if (searchTxt.length() != 0 && userOffers.length() != 0 && userSearchs.length() != 0) {

            hql += "AND " + "(" + "(" + "lower(c.login) LIKE :search " + "OR lower(c.firstname) LIKE :search "
                    + "OR lower(c.lastname) LIKE :search " + "OR lower(c.adresses.email) LIKE :search "
                    + "OR lower(c.adresses.town) LIKE :search " + ")" + "AND" + "("
                    + "lower(c.userOffers) LIKE :userOffers " + ")" + "AND" + "("
                    + "lower(c.userSearchs) LIKE :userSearchs " + ")" + ")";

        } else if (searchTxt.length() != 0 && userOffers.length() != 0) {

            hql += "AND " + "(" + "(" + "lower(c.login) LIKE :search " + "OR lower(c.firstname) LIKE :search "
                    + "OR lower(c.lastname) LIKE :search " + "OR lower(c.adresses.email) LIKE :search "
                    + "OR lower(c.adresses.town) LIKE :search " + ")" + "AND" + "("
                    + "lower(c.userOffers) LIKE :userOffers " + ")" + ")";

        } else if (searchTxt.length() != 0 && userSearchs.length() != 0) {

            hql += "AND " + "(" + "(" + "lower(c.login) LIKE :search " + "OR lower(c.firstname) LIKE :search "
                    + "OR lower(c.lastname) LIKE :search " + "OR lower(c.adresses.email) LIKE :search "
                    + "OR lower(c.adresses.town) LIKE :search " + ")" + "AND" + "("
                    + "lower(c.userSearchs) LIKE :userSearchs " + ")" + ")";

        } else if (userOffers.length() != 0 && userSearchs.length() != 0) {

            hql += "AND " + "(" + "(" + "lower(c.userOffers) LIKE :userOffers " + ")" + "AND" + "("
                    + "lower(c.userSearchs) LIKE :userSearchs " + ")" + ")";

        } else if (searchTxt.length() != 0) {

            hql += "AND " + "(" + "(" + "lower(c.login) LIKE :search " + "OR lower(c.firstname) LIKE :search "
                    + "OR lower(c.lastname) LIKE :search " + "OR lower(c.adresses.email) LIKE :search "
                    + "OR lower(c.adresses.town) LIKE :search " + ")" + ")";

        } else if (userOffers.length() != 0) {

            hql += "AND " + "(" + "(" + "lower(c.userOffers) LIKE :userOffers " + ")" + ")";

        } else if (userSearchs.length() != 0) {

            hql += "AND " + "(" + "(" + "lower(c.userSearchs) LIKE :userSearchs " + ")" + ")";

        }

        hql += " ORDER BY " + orderBy;

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

        if (searchTxt.length() != 0) {
            searchTxt = "%" + searchTxt + "%";
        }

        if (userOffers.length() != 0) {
            userOffers = "%" + userOffers + "%";
        }

        if (userSearchs.length() != 0) {
            userSearchs = "%" + userSearchs + "%";
        }

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

        // get all users
        TypedQuery<Users> query = em.createQuery(hql, Users.class);

        if (searchTxt.length() != 0 && userOffers.length() != 0 && userSearchs.length() != 0) {

            query.setParameter("search", StringUtils.lowerCase(searchTxt));
            query.setParameter("userOffers", StringUtils.lowerCase(userOffers));
            query.setParameter("userSearchs", StringUtils.lowerCase(userSearchs));

        } else if (searchTxt.length() != 0 && userOffers.length() != 0) {

            query.setParameter("search", StringUtils.lowerCase(searchTxt));
            query.setParameter("userOffers", StringUtils.lowerCase(userOffers));

        } else if (searchTxt.length() != 0 && userSearchs.length() != 0) {

            query.setParameter("search", StringUtils.lowerCase(searchTxt));
            query.setParameter("userSearchs", StringUtils.lowerCase(userSearchs));

        } else if (userOffers.length() != 0 && userSearchs.length() != 0) {

            query.setParameter("userOffers", StringUtils.lowerCase(userOffers));
            query.setParameter("userSearchs", StringUtils.lowerCase(userSearchs));

        } else if (searchTxt.length() != 0) {

            query.setParameter("search", StringUtils.lowerCase(searchTxt));

        } else if (userOffers.length() != 0) {

            query.setParameter("userOffers", StringUtils.lowerCase(userOffers));

        } else if (userSearchs.length() != 0) {

            query.setParameter("userSearchs", StringUtils.lowerCase(userSearchs));

        }

        query.setMaxResults(max);
        query.setFirstResult(start);

        List<Users> userList = query.getResultList();

        return userList;

    } catch (Exception ex2) {
        log.error("[getUsersList] ", ex2);
    }

    return null;
}

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

/**
 * Acquire a listing of all records by OWNER.
 *
 * @param rows the number of rows desired (if present)
 * @param start the starting row number (from 0)
 * @return the Metadata information in the desired format
 * @throws JsonProcessingException/*from  w  w  w.j a  va 2s  . c om*/
 */
@GET
@Path("/projects")
@Produces(MediaType.APPLICATION_JSON)
@RequiresAuthentication
public Response listProjects(@QueryParam("rows") int rows, @QueryParam("start") int start)
        throws JsonProcessingException {
    EntityManager em = DoeServletContextListener.createEntityManager();

    // get the security user in context
    Subject subject = SecurityUtils.getSubject();
    User user = (User) subject.getPrincipal();

    try {
        Set<String> roles = user.getRoles();
        String rolecode = (null == roles) ? "" : (roles.isEmpty()) ? "" : roles.iterator().next();

        TypedQuery<DOECodeMetadata> query;
        // admins see ALL PROJECTS
        if ("OSTI".equals(rolecode)) {
            query = em.createQuery("SELECT md FROM DOECodeMetadata md", DOECodeMetadata.class);
        } else if (StringUtils.isNotEmpty(rolecode)) {
            // if you have another ROLE, it is assumed to be a SITE ADMIN; see all those records
            query = em.createQuery("SELECT md FROM DOECodeMetadata md WHERE md.siteOwnershipCode = :site",
                    DOECodeMetadata.class).setParameter("site", rolecode);
        } else {
            // no roles, you see only YOUR OWN projects
            query = em.createQuery("SELECT md FROM DOECodeMetadata md WHERE md.owner = lower(:owner)",
                    DOECodeMetadata.class).setParameter("owner", user.getEmail());
        }

        // if rows specified, and greater than 100, cap it there
        rows = (rows > 100) ? 100 : rows;

        // if pagination elements are present, set them on the query
        if (0 != rows)
            query.setMaxResults(rows);
        if (0 != start)
            query.setFirstResult(start);

        // get a List of records
        RecordsList records = new RecordsList(query.getResultList());
        records.setStart(start);
        ObjectNode recordsObject = mapper.valueToTree(records);

        // lookup previous Snapshot status info for each item
        TypedQuery<MetadataSnapshot> querySnapshot = em
                .createNamedQuery("MetadataSnapshot.findByCodeIdLastNotStatus", MetadataSnapshot.class)
                .setParameter("status", DOECodeMetadata.Status.Approved);

        // lookup system Snapshot status info for each item
        TypedQuery<MetadataSnapshot> querySystemSnapshot = em
                .createNamedQuery("MetadataSnapshot.findByCodeIdAsSystemStatus", MetadataSnapshot.class)
                .setParameter("status", DOECodeMetadata.Status.Approved);

        JsonNode recordNode = recordsObject.get("records");
        if (recordNode.isArray()) {
            int rowCount = 0;
            for (JsonNode objNode : recordNode) {
                rowCount++;

                // skip non-approved records
                String currentStatus = objNode.get("workflow_status").asText();
                if (!currentStatus.equalsIgnoreCase("Approved"))
                    continue;

                // get code_id to find Snapshot
                long codeId = objNode.get("code_id").asLong();
                querySnapshot.setParameter("codeId", codeId);
                querySystemSnapshot.setParameter("codeId", codeId);

                String lastApprovalFor = "";
                List<MetadataSnapshot> results = querySnapshot.setMaxResults(1).getResultList();
                for (MetadataSnapshot ms : results) {
                    lastApprovalFor = ms.getSnapshotKey().getSnapshotStatus().toString();
                }

                // add "approve as" status indicator to response record, if not blank
                if (!StringUtils.isBlank(lastApprovalFor))
                    ((ObjectNode) objNode).put("approved_as", lastApprovalFor);

                String systemStatus = "";
                List<MetadataSnapshot> resultsSystem = querySystemSnapshot.setMaxResults(1).getResultList();
                for (MetadataSnapshot ms : resultsSystem) {
                    systemStatus = ms.getSnapshotKey().getSnapshotStatus().toString();
                }

                // add "system status" indicator to response record, if not blank
                if (!StringUtils.isBlank(lastApprovalFor))
                    ((ObjectNode) objNode).put("system_status", systemStatus);
            }

            recordsObject.put("total", rowCount);
        }

        return Response.status(Response.Status.OK).entity(recordsObject.toString()).build();
    } finally {
        em.close();
    }
}

From source file:com.clustercontrol.notify.monitor.util.QueryUtil.java

public static List<EventLogEntity> getEventLogByFilter(String[] facilityIds, Integer[] priorityList,
        Long outputFromDate, Long outputToDate, Long generationFromDate, Long generationToDate,
        String monitorId, String monitorDetailId, String application, String message, Integer confirmFlg,
        String confirmUser, String comment, String commentUser, Boolean collectGraphFlg, String ownerRoleId,
        Boolean orderByFlg, Integer limit) {

    HinemosEntityManager em = new JpaTransactionManager().getEntityManager();

    // ??????????
    String notInclude = "NOT:";

    StringBuffer sbJpql = new StringBuffer();
    sbJpql.append("SELECT a FROM EventLogEntity a WHERE true = true");
    // ID/*from ww  w  .j  ava2s .c  o m*/
    if (facilityIds != null && facilityIds.length > 0) {
        sbJpql.append(" AND a.id.facilityId IN ("
                + HinemosEntityManager.getParamNameString("facilityId", facilityIds) + ")");
    }
    // ??
    if (priorityList != null && priorityList.length > 0
            && priorityList.length != PriorityConstant.PRIORITY_LIST.length) {
        sbJpql.append(" AND a.priority IN ("
                + HinemosEntityManager.getParamNameString("priority", new String[priorityList.length]) + ")");
    }
    // ?
    if (outputFromDate != null) {
        sbJpql.append(" AND a.id.outputDate >= :outputFromDate");
    }
    // ?
    if (outputToDate != null) {
        sbJpql.append(" AND a.id.outputDate <= :outputToDate");
    }
    // 
    if (generationFromDate != null) {
        sbJpql.append(" AND a.generationDate >= :generationFromDate");
    }
    // 
    if (generationToDate != null) {
        sbJpql.append(" AND a.generationDate <= :generationToDate");
    }
    // ID
    if (monitorId != null && !"".equals(monitorId)) {
        if (!monitorId.startsWith(notInclude)) {
            sbJpql.append(" AND a.id.monitorId like :monitorId");
        } else {
            sbJpql.append(" AND a.id.monitorId not like :monitorId");
        }
    }
    // 
    if (monitorDetailId != null && !"".equals(monitorDetailId)) {
        if (!monitorDetailId.startsWith(notInclude)) {
            sbJpql.append(" AND a.id.monitorDetailId like :monitorDetailId");
        } else {
            sbJpql.append(" AND a.id.monitorDetailId not like :monitorDetailId");
        }
    }
    // 
    if (application != null && !"".equals(application)) {
        if (!application.startsWith(notInclude)) {
            sbJpql.append(" AND a.application like :application");
        } else {
            sbJpql.append(" AND a.application not like :application");
        }
    }
    // 
    if (message != null && !"".equals(message)) {
        if (!message.startsWith(notInclude)) {
            sbJpql.append(" AND a.message like :message");
        } else {
            sbJpql.append(" AND a.message not like :message");
        }
    }
    // ?
    if (confirmFlg != null) {
        sbJpql.append(" AND a.confirmFlg = :confirmFlg");
    }
    // ?
    if (confirmUser != null && !"".equals(confirmUser)) {
        if (!confirmUser.startsWith(notInclude)) {
            sbJpql.append(" AND a.confirmUser like :confirmUser");
        } else {
            sbJpql.append(" AND a.confirmUser not like :confirmUser");
        }
    }
    //
    if (comment != null && !"".equals(comment)) {
        if (!comment.startsWith(notInclude)) {
            sbJpql.append(" AND a.comment like :comment");
        } else {
            sbJpql.append(" AND a.comment not like :comment");
        }
    }
    //
    if (commentUser != null && !"".equals(commentUser)) {
        if (!commentUser.startsWith(notInclude)) {
            sbJpql.append(" AND a.commentUser like :commentUser");
        } else {
            sbJpql.append(" AND a.commentUser not like :commentUser");
        }
    }
    //
    if (collectGraphFlg != null) {
        sbJpql.append(" AND a.collectGraphFlg = :collectGraphFlg");
    }
    //ID
    if (ownerRoleId != null && !"".equals(ownerRoleId)) {
        if (!ownerRoleId.startsWith(notInclude)) {
            sbJpql.append(" AND a.ownerRoleId like :ownerRoleId");
        } else {
            sbJpql.append(" AND a.ownerRoleId not like :ownerRoleId");
        }
    }
    // 
    if (orderByFlg) {
        sbJpql.append(" ORDER BY a.id.outputDate");
    } else {
        sbJpql.append(" ORDER BY a.id.outputDate DESC");
    }
    TypedQuery<EventLogEntity> typedQuery = em.createQuery(sbJpql.toString(), EventLogEntity.class);
    // ID
    if (facilityIds != null && facilityIds.length > 0) {
        typedQuery = HinemosEntityManager.appendParam(typedQuery, "facilityId", facilityIds);
    }
    // ??
    if (priorityList != null && priorityList.length > 0
            && priorityList.length != PriorityConstant.PRIORITY_LIST.length) {
        int count = priorityList.length;
        if (count > 0) {
            for (int i = 0; i < count; i++) {
                typedQuery = typedQuery.setParameter("priority" + i, priorityList[i]);
            }
        }
    }
    // ?
    if (outputFromDate != null) {
        typedQuery = typedQuery.setParameter("outputFromDate", outputFromDate);
    }
    // ?
    if (outputToDate != null) {
        typedQuery = typedQuery.setParameter("outputToDate", outputToDate);
    }
    // 
    if (generationFromDate != null) {
        typedQuery = typedQuery.setParameter("generationFromDate", generationFromDate);
    }
    // 
    if (generationToDate != null) {
        typedQuery = typedQuery.setParameter("generationToDate", generationToDate);
    }
    // ID
    if (monitorId != null && !"".equals(monitorId)) {
        if (!monitorId.startsWith(notInclude)) {
            typedQuery = typedQuery.setParameter("monitorId", monitorId);
        } else {
            typedQuery = typedQuery.setParameter("monitorId", monitorId.substring(notInclude.length()));
        }
    }
    // 
    if (monitorDetailId != null && !"".equals(monitorDetailId)) {
        if (!monitorDetailId.startsWith(notInclude)) {
            typedQuery = typedQuery.setParameter("monitorDetailId", monitorDetailId);
        } else {
            typedQuery = typedQuery.setParameter("monitorDetailId",
                    monitorDetailId.substring(notInclude.length()));
        }
    }
    // 
    if (application != null && !"".equals(application)) {
        if (!application.startsWith(notInclude)) {
            typedQuery = typedQuery.setParameter("application", application);
        } else {
            typedQuery = typedQuery.setParameter("application", application.substring(notInclude.length()));
        }
    }
    // 
    if (message != null && !"".equals(message)) {
        if (!message.startsWith(notInclude)) {
            typedQuery = typedQuery.setParameter("message", message);
        } else {
            typedQuery = typedQuery.setParameter("message", message.substring(notInclude.length()));
        }
    }
    // ?
    if (confirmFlg != null) {
        typedQuery = typedQuery.setParameter("confirmFlg", confirmFlg);
    }
    // ?
    if (confirmUser != null && !"".equals(confirmUser)) {
        if (!confirmUser.startsWith(notInclude)) {
            typedQuery = typedQuery.setParameter("confirmUser", confirmUser);
        } else {
            typedQuery = typedQuery.setParameter("confirmUser", confirmUser.substring(notInclude.length()));
        }
    }
    //
    if (comment != null && !"".equals(comment)) {
        if (!comment.startsWith(notInclude)) {
            typedQuery = typedQuery.setParameter("comment", comment);
        } else {
            typedQuery = typedQuery.setParameter("comment", comment.substring(notInclude.length()));
        }
    }
    //
    if (commentUser != null && !"".equals(commentUser)) {
        if (!commentUser.startsWith(notInclude)) {
            typedQuery = typedQuery.setParameter("commentUser", commentUser);
        } else {
            typedQuery = typedQuery.setParameter("commentUser", commentUser.substring(notInclude.length()));
        }
    }
    //
    if (collectGraphFlg != null) {
        typedQuery = typedQuery.setParameter("collectGraphFlg", collectGraphFlg);
    }
    //ID
    if (ownerRoleId != null && !"".equals(ownerRoleId)) {
        if (!ownerRoleId.startsWith(notInclude)) {
            typedQuery = typedQuery.setParameter("ownerRoleId", ownerRoleId);
        } else {
            typedQuery = typedQuery.setParameter("ownerRoleId", ownerRoleId.substring(notInclude.length()));
        }
    }
    if (limit != null) {
        typedQuery = typedQuery.setMaxResults(limit);
    }

    return typedQuery.getResultList();
}

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

/**
 * Add/Remove backfill RI information./*  w  w w  .ja v a2  s. co  m*/
 * To modify source items, you must be an OSTI admin, project owner, or site admin.
 *
 * @param em the EntityManager to control commits.
 * @param md the Metadata to evaluate for RI updating.
 * @param previousList the RelatedIdentifiers from previous Approval.
 */
private void backfillProjects(EntityManager em, DOECodeMetadata md, List<RelatedIdentifier> previousList)
        throws IllegalAccessException, IOException {
    // if current project has no DOI, there is nothing to process
    if (StringUtils.isBlank(md.getDoi()))
        return;

    // get current list of RI info, for backfill additions
    List<RelatedIdentifier> additionList = md.getRelatedIdentifiers();

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

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

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

    // previous relations no longer defined must be removed
    previousList.removeAll(additionList);

    // store details about what will need sent to OSTI and re-indexed
    Map<Long, DOECodeMetadata> backfillSendToIndex = new HashMap<>();
    Map<Long, DOECodeMetadata> backfillSendToOsti = new HashMap<>();

    // define needed queries
    TypedQuery<DOECodeMetadata> deleteQuery = em.createNamedQuery("DOECodeMetadata.findByDoiAndRi",
            DOECodeMetadata.class);
    TypedQuery<DOECodeMetadata> addQuery = em.createNamedQuery("DOECodeMetadata.findByDoi",
            DOECodeMetadata.class);
    TypedQuery<MetadataSnapshot> snapshotQuery = em.createNamedQuery("MetadataSnapshot.findByCodeIdAndStatus",
            MetadataSnapshot.class);
    TypedQuery<MetadataSnapshot> querySnapshot = em
            .createNamedQuery("MetadataSnapshot.findByCodeIdLastNotStatus", MetadataSnapshot.class)
            .setParameter("status", DOECodeMetadata.Status.Approved);

    List<RelatedIdentifier> backfillSourceList;

    // for each BackfillType, perform actions:  delete obsolete previous info / add new info
    for (RelatedIdentifier.BackfillType backfillType : RelatedIdentifier.BackfillType.values()) {
        // previous relations no longer defined must be removed, current relations need to be added
        backfillSourceList = backfillType == RelatedIdentifier.BackfillType.Deletion ? previousList
                : additionList;

        // if there is no list to process, skip
        if (backfillSourceList == null || backfillSourceList.isEmpty())
            continue;

        for (RelatedIdentifier ri : backfillSourceList) {
            // get inverse relation
            RelatedIdentifier inverseRelation = new RelatedIdentifier(ri);
            inverseRelation.setRelationType(ri.getRelationType().inverse());
            inverseRelation.setIdentifierValue(md.getDoi());
            inverseRelation.setSource(RelatedIdentifier.Source.AutoBackfill);

            List<RelatedIdentifier> targetedList = Arrays.asList(inverseRelation);

            List<DOECodeMetadata> results = new ArrayList<>();
            List<MetadataSnapshot> snapshotResults;

            if (backfillType == RelatedIdentifier.BackfillType.Deletion) {
                // check for the existance of the inverse relation
                deleteQuery.setParameter("doi", ri.getIdentifierValue())
                        .setParameter("type", inverseRelation.getIdentifierType())
                        .setParameter("value", inverseRelation.getIdentifierValue())
                        .setParameter("relType", inverseRelation.getRelationType());

                results = deleteQuery.getResultList();
            } else if (backfillType == RelatedIdentifier.BackfillType.Addition) {
                // lookup target DOI
                addQuery.setParameter("doi", ri.getIdentifierValue());

                results = addQuery.getResultList();
            }

            // update RI where needed
            for (DOECodeMetadata bmd : results) {
                // target CODE ID and Workflow Status
                Long codeId = bmd.getCodeId();
                DOECodeMetadata.Status status = bmd.getWorkflowStatus();

                List<RelatedIdentifier> updateList = bmd.getRelatedIdentifiers();

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

                // get User data
                List<RelatedIdentifier> userRIList = getSourceRi(updateList, RelatedIdentifier.Source.User);

                // update metadata RI info
                updateList.removeAll(targetedList); // always remove match
                if (backfillType == RelatedIdentifier.BackfillType.Addition)
                    updateList.addAll(targetedList); // add back, if needed

                // restore any modified User data
                updateList.removeAll(userRIList); // always remove match
                updateList.addAll(userRIList); // add back, if needed

                // save changes
                bmd.setRelatedIdentifiers(updateList);

                // update snapshot metadata
                snapshotQuery.setParameter("codeId", codeId).setParameter("status", status);

                snapshotResults = snapshotQuery.getResultList();

                // update snapshot RI, for same status, where needed
                for (MetadataSnapshot ms : snapshotResults) {
                    try {
                        DOECodeMetadata smd = DOECodeMetadata.parseJson(new StringReader(ms.getJson()));

                        List<RelatedIdentifier> snapshotList = smd.getRelatedIdentifiers();

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

                        // get User data
                        userRIList = getSourceRi(snapshotList, RelatedIdentifier.Source.User);

                        // update snapshot RI info, if needed
                        snapshotList.removeAll(targetedList); // always remove match
                        if (backfillType == RelatedIdentifier.BackfillType.Addition)
                            snapshotList.addAll(targetedList); // add back, if needed

                        // restore any modified User data
                        snapshotList.removeAll(userRIList); // always remove match
                        snapshotList.addAll(userRIList); // add back, if needed

                        // save changes to Snapshot
                        smd.setRelatedIdentifiers(snapshotList);
                        ms.setJson(smd.toJson().toString());

                        // log updated, Approved snapshot info for post-backfill actions
                        if (status == DOECodeMetadata.Status.Approved) {
                            // log for re-indexing
                            backfillSendToIndex.put(codeId, smd);

                            // lookup snapshot status info, prior to Approval
                            querySnapshot.setParameter("codeId", codeId);

                            List<MetadataSnapshot> previousResults = querySnapshot.setMaxResults(1)
                                    .getResultList();
                            for (MetadataSnapshot pms : previousResults) {
                                DOECodeMetadata.Status lastApprovalFor = pms.getSnapshotKey()
                                        .getSnapshotStatus();

                                // if Approved for Announcement, log for OSTI
                                if (lastApprovalFor == DOECodeMetadata.Status.Announced)
                                    backfillSendToOsti.put(codeId, smd);

                                break; // failsafe, but should only be at most one item returned
                            }
                        }
                    } catch (IOException ex) {
                        // unable to parse JSON, but for this process
                        String msg = "Unable to parse '" + ms.getSnapshotKey().getSnapshotStatus()
                                + "' Snapshot JSON for " + ms.getSnapshotKey().getCodeId() + ": "
                                + ex.getMessage();
                        throw new IOException(msg);
                    }
                }
            }
        }
    }

    // update OSTI, as needed
    for (Map.Entry<Long, DOECodeMetadata> entry : backfillSendToOsti.entrySet()) {
        sendToOsti(em, entry.getValue());
    }

    // update Index, as needed
    for (Map.Entry<Long, DOECodeMetadata> entry : backfillSendToIndex.entrySet()) {
        sendToIndex(em, entry.getValue());
    }
}

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

/**
 * TypedQuery?/*from  w  ww.j  a v a2 s . co m*/
 *f
 * @param property 
 * @param statuslist ?(?)
 * @param isPending null:???, true:"?"??(???), false:"?"??(???)
 * @param roleIdList 
 * @param loginUser ID
 * @param limit ?
 * 
 * @return typedQuery
 */
private TypedQuery<?> getApprovalFilterQuery(JobApprovalFilter property, List<Integer> statuslist,
        Boolean isPending, List<String> roleIdList, String loginUser, Integer limit) {

    m_log.debug("getApprovalFilterQuery()");

    HinemosEntityManager em = new JpaTransactionManager().getEntityManager();

    // ??????????
    String notInclude = "NOT:";

    String[] userlist = { "*", loginUser };

    StringBuffer sbJpql = new StringBuffer();
    sbJpql.append("SELECT b");
    sbJpql.append(" FROM JobSessionJobEntity a, JobInfoEntity b, JobSessionNodeEntity c");
    sbJpql.append(" WHERE a.id.sessionId = b.id.sessionId");
    sbJpql.append(" AND a.id.jobunitId = b.id.jobunitId");
    sbJpql.append(" AND a.id.jobId = b.id.jobId");
    sbJpql.append(" AND a.id.sessionId = c.id.sessionId");
    sbJpql.append(" AND a.id.jobunitId = c.id.jobunitId");
    sbJpql.append(" AND a.id.jobId = c.id.jobId");
    sbJpql.append(" AND b.jobType = :jobType");

    // ???????()?????
    sbJpql.append(" AND c.approvalStatus IS NOT NULL");

    if (property.getStartFromDate() != null) {
        sbJpql.append(" AND c.startDate >= :startFromDate");
    }
    if (property.getStartToDate() != null) {
        sbJpql.append(" AND c.startDate <= :startToDate");
    }
    if (property.getEndFromDate() != null) {
        sbJpql.append(" AND c.endDate >= :endFromDate");
    }
    if (property.getEndToDate() != null) {
        sbJpql.append(" AND c.endDate <= :endToDate");
    }

    //?/SQL??????????
    // ????(statuslist)?
    if (isPending != null) {
        //??/?????"?"???????"?"
        if (isPending) {
            //"?"?"?"
            if (statuslist != null && statuslist.size() > 0) {
                //?
                sbJpql.append(" AND ((c.approvalStatus = :approvalPendingStatus");
                sbJpql.append(" AND b.approvalReqRoleId IN (" + HinemosEntityManager
                        .getParamNameString("approvalReqRoleId", new String[roleIdList.size()]) + ")");
                sbJpql.append(" AND b.approvalReqUserId IN ("
                        + HinemosEntityManager.getParamNameString("approvalReqUserId", userlist) + "))");
                sbJpql.append(" OR c.approvalStatus IN (" + HinemosEntityManager
                        .getParamNameString("approvalStatus", new String[statuslist.size()]) + "))");
            } else {
                //"?"??
                sbJpql.append(" AND c.approvalStatus = :approvalPendingStatus");
                sbJpql.append(" AND b.approvalReqRoleId IN (" + HinemosEntityManager
                        .getParamNameString("approvalReqRoleId", new String[roleIdList.size()]) + ")");
                sbJpql.append(" AND b.approvalReqUserId IN ("
                        + HinemosEntityManager.getParamNameString("approvalReqUserId", userlist) + ")");
            }
        } else {
            //"?"?"?"
            if (statuslist != null && statuslist.size() > 0) {
                //?
                sbJpql.append(" AND ((c.approvalStatus = :approvalPendingStatus");
                sbJpql.append(" AND (b.approvalReqRoleId NOT IN (" + HinemosEntityManager
                        .getParamNameString("approvalReqRoleId", new String[roleIdList.size()]) + ")");
                sbJpql.append(" OR b.approvalReqUserId NOT IN ("
                        + HinemosEntityManager.getParamNameString("approvalReqUserId", userlist) + ")))");
                sbJpql.append(" OR c.approvalStatus IN (" + HinemosEntityManager
                        .getParamNameString("approvalStatus", new String[statuslist.size()]) + "))");
            } else {
                //"?"??
                sbJpql.append(" AND c.approvalStatus = :approvalPendingStatus");
                sbJpql.append(" AND (b.approvalReqRoleId NOT IN (" + HinemosEntityManager
                        .getParamNameString("approvalReqRoleId", new String[roleIdList.size()]) + ")");
                sbJpql.append(" OR b.approvalReqUserId NOT IN ("
                        + HinemosEntityManager.getParamNameString("approvalReqUserId", userlist) + "))");
            }
        }
    } else {
        //?/????("?"/"?"???)???????
        //"?"?DB???(?//??/?)????????????
        if (statuslist != null && statuslist.size() > 0 && statuslist.size() != 4) {
            sbJpql.append(" AND c.approvalStatus IN ("
                    + HinemosEntityManager.getParamNameString("approvalStatus", new String[statuslist.size()])
                    + ")");
        }
    }

    if (property.getResult() != null && property.getResult() != -1) {
        sbJpql.append(" AND c.approvalResult = :approvalResult");
    }
    if (property.getSessionId() != null && property.getSessionId().length() > 0) {
        if (!property.getSessionId().startsWith(notInclude)) {
            sbJpql.append(" AND a.id.sessionId like :sessionId");
        } else {
            sbJpql.append(" AND a.id.sessionId not like :sessionId");
        }
    }
    if (property.getJobunitId() != null && property.getJobunitId().length() > 0) {
        if (!property.getJobunitId().startsWith(notInclude)) {
            sbJpql.append(" AND a.id.jobunitId like :jobunitId");
        } else {
            sbJpql.append(" AND a.id.jobunitId not like :jobunitId");
        }
    }
    if (property.getJobId() != null && property.getJobId().length() > 0) {
        if (!property.getJobId().startsWith(notInclude)) {
            sbJpql.append(" AND a.id.jobId like :jobId");
        } else {
            sbJpql.append(" AND a.id.jobId not like :jobId");
        }
    }
    if (property.getJobName() != null && property.getJobName().length() > 0) {
        if (!property.getJobName().startsWith(notInclude)) {
            sbJpql.append(" AND b.jobName like :jobName");
        } else {
            sbJpql.append(" AND b.jobName not like :jobName");
        }
    }
    if (property.getRequestUser() != null && property.getRequestUser().length() > 0) {
        if (!property.getRequestUser().startsWith(notInclude)) {
            sbJpql.append(" AND c.approvalRequestUser like :approvalRequestUser");
        } else {
            sbJpql.append(" AND c.approvalRequestUser not like :approvalRequestUser");
        }
    }
    if (property.getApprovalUser() != null && property.getApprovalUser().length() > 0) {
        if (!property.getApprovalUser().startsWith(notInclude)) {
            sbJpql.append(" AND c.approvalUser like :approvalUser");
        } else {
            sbJpql.append(" AND c.approvalUser not like :approvalUser");
        }
    }
    if (property.getRequestSentence() != null && property.getRequestSentence().length() > 0) {
        if (!property.getRequestSentence().startsWith(notInclude)) {
            sbJpql.append(" AND b.approvalReqSentence like :approvalReqSentence");
        } else {
            sbJpql.append(" AND b.approvalReqSentence not like :approvalReqSentence");
        }
    }
    if (property.getComment() != null && property.getComment().length() > 0) {
        if (!property.getComment().startsWith(notInclude)) {
            sbJpql.append(" AND c.approvalComment like :approvalComment");
        } else {
            sbJpql.append(" AND c.approvalComment not like :approvalComment");
        }
    }

    // TODO:??????????
    // ??
    sbJpql = getJpql(sbJpql);

    sbJpql.append(" ORDER BY c.approvalStatus DESC, a.id.sessionId DESC");
    m_log.debug("getApprovalFilterQuery() jpql = " + sbJpql.toString());

    TypedQuery<?> typedQuery = null;
    typedQuery = em.createQuery(sbJpql.toString(), JobInfoEntity.class);

    typedQuery = typedQuery.setParameter("jobType", JobConstant.TYPE_APPROVALJOB);

    if (property.getStartFromDate() != null) {
        typedQuery = typedQuery.setParameter("startFromDate", property.getStartFromDate());
    }
    if (property.getStartToDate() != null) {
        typedQuery = typedQuery.setParameter("startToDate", property.getStartToDate());
    }
    if (property.getEndFromDate() != null) {
        typedQuery = typedQuery.setParameter("endFromDate", property.getEndFromDate());
    }
    if (property.getEndToDate() != null) {
        typedQuery = typedQuery.setParameter("endToDate", property.getEndToDate());
    }

    //?/SQL??????????
    if (isPending != null) {
        //??/?????"?"???????"?"
        typedQuery = typedQuery.setParameter("approvalPendingStatus", JobApprovalStatusConstant.TYPE_PENDING);
        int count = roleIdList.size();
        if (count > 0) {
            for (int i = 0; i < count; i++) {
                typedQuery = typedQuery.setParameter("approvalReqRoleId" + i, roleIdList.toArray()[i]);
            }
        }
        count = userlist.length;
        if (count > 0) {
            for (int i = 0; i < count; i++) {
                typedQuery = typedQuery.setParameter("approvalReqUserId" + i, userlist[i]);
            }
        }
        if (statuslist != null && statuslist.size() > 0) {
            count = statuslist.size();
            if (count > 0) {
                for (int i = 0; i < count; i++) {
                    typedQuery = typedQuery.setParameter("approvalStatus" + i, statuslist.toArray()[i]);
                }
            }
        }
    } else {
        //?/????("?"/"?"???)???????
        //"?"?DB???(?//??/?)????????????
        if (statuslist != null && statuslist.size() > 0 && statuslist.size() != 4) {
            int count = statuslist.size();
            if (count > 0) {
                for (int i = 0; i < count; i++) {
                    typedQuery = typedQuery.setParameter("approvalStatus" + i, statuslist.toArray()[i]);
                }
            }
        }
    }

    if (property.getResult() != null && property.getResult() != -1) {
        typedQuery = typedQuery.setParameter("approvalResult", property.getResult());
    }
    if (property.getSessionId() != null && property.getSessionId().length() > 0) {
        if (!property.getSessionId().startsWith(notInclude)) {
            typedQuery = typedQuery.setParameter("sessionId", property.getSessionId());
        } else {
            typedQuery = typedQuery.setParameter("sessionId",
                    property.getSessionId().substring(notInclude.length()));
        }
    }
    if (property.getJobunitId() != null && property.getJobunitId().length() > 0) {
        if (!property.getJobunitId().startsWith(notInclude)) {
            typedQuery = typedQuery.setParameter("jobunitId", property.getJobunitId());
        } else {
            typedQuery = typedQuery.setParameter("jobunitId",
                    property.getJobunitId().substring(notInclude.length()));
        }
    }
    if (property.getJobId() != null && property.getJobId().length() > 0) {
        if (!property.getJobId().startsWith(notInclude)) {
            typedQuery = typedQuery.setParameter("jobId", property.getJobId());
        } else {
            typedQuery = typedQuery.setParameter("jobId", property.getJobId().substring(notInclude.length()));
        }
    }
    if (property.getJobName() != null && property.getJobName().length() > 0) {
        if (!property.getJobName().startsWith(notInclude)) {
            typedQuery = typedQuery.setParameter("jobName", property.getJobName());
        } else {
            typedQuery = typedQuery.setParameter("jobName",
                    property.getJobName().substring(notInclude.length()));
        }
    }
    if (property.getRequestUser() != null && property.getRequestUser().length() > 0) {
        if (!property.getRequestUser().startsWith(notInclude)) {
            typedQuery = typedQuery.setParameter("approvalRequestUser", property.getRequestUser());
        } else {
            typedQuery = typedQuery.setParameter("approvalRequestUser",
                    property.getRequestUser().substring(notInclude.length()));
        }
    }
    if (property.getApprovalUser() != null && property.getApprovalUser().length() > 0) {
        if (!property.getApprovalUser().startsWith(notInclude)) {
            typedQuery = typedQuery.setParameter("approvalUser", property.getApprovalUser());
        } else {
            typedQuery = typedQuery.setParameter("approvalUser",
                    property.getApprovalUser().substring(notInclude.length()));
        }
    }
    if (property.getRequestSentence() != null && property.getRequestSentence().length() > 0) {
        if (!property.getRequestSentence().startsWith(notInclude)) {
            typedQuery = typedQuery.setParameter("approvalReqSentence", property.getRequestSentence());
        } else {
            typedQuery = typedQuery.setParameter("approvalReqSentence",
                    property.getRequestSentence().substring(notInclude.length()));
        }
    }
    if (property.getComment() != null && property.getComment().length() > 0) {
        if (!property.getComment().startsWith(notInclude)) {
            typedQuery = typedQuery.setParameter("approvalComment", property.getComment());
        } else {
            typedQuery = typedQuery.setParameter("approvalComment",
                    property.getComment().substring(notInclude.length()));
        }
    }

    // TODO:??????????
    // ??
    typedQuery = setObjectPrivilegeParameter(typedQuery);

    if (limit != null) {
        typedQuery = typedQuery.setMaxResults(limit);
    }

    return typedQuery;
}

From source file:org.apache.ambari.server.orm.dao.AlertsDAO.java

/**
 * Finds all {@link AlertHistoryEntity} that match the provided
 * {@link AlertHistoryRequest}. This method will make JPA do the heavy lifting
 * of providing a slice of the result set.
 *
 * @param request//from w w  w .ja  v  a 2  s.  c o  m
 * @return
 */
@RequiresSession
public List<AlertHistoryEntity> findAll(AlertHistoryRequest request) {
    EntityManager entityManager = m_entityManagerProvider.get();

    // convert the Ambari predicate into a JPA predicate
    HistoryPredicateVisitor visitor = new HistoryPredicateVisitor();
    PredicateHelper.visit(request.Predicate, visitor);

    CriteriaQuery<AlertHistoryEntity> query = visitor.getCriteriaQuery();
    javax.persistence.criteria.Predicate jpaPredicate = visitor.getJpaPredicate();

    if (null != jpaPredicate) {
        query.where(jpaPredicate);
    }

    // sorting
    JpaSortBuilder<AlertHistoryEntity> sortBuilder = new JpaSortBuilder<AlertHistoryEntity>();
    List<Order> sortOrders = sortBuilder.buildSortOrders(request.Sort, visitor);
    query.orderBy(sortOrders);

    // pagination
    TypedQuery<AlertHistoryEntity> typedQuery = entityManager.createQuery(query);
    if (null != request.Pagination) {
        typedQuery.setFirstResult(request.Pagination.getOffset());
        typedQuery.setMaxResults(request.Pagination.getPageSize());
    }

    return m_daoUtils.selectList(typedQuery);
}

From source file:org.apache.ambari.server.orm.dao.AlertsDAO.java

/**
 * Finds all {@link AlertCurrentEntity} that match the provided
 * {@link AlertCurrentRequest}. This method will make JPA do the heavy lifting
 * of providing a slice of the result set.
 *
 * @param request// ww w  .  j a v  a  2 s.  c  om
 * @return
 */
@Transactional
public List<AlertCurrentEntity> findAll(AlertCurrentRequest request) {
    EntityManager entityManager = m_entityManagerProvider.get();

    // convert the Ambari predicate into a JPA predicate
    CurrentPredicateVisitor visitor = new CurrentPredicateVisitor();
    PredicateHelper.visit(request.Predicate, visitor);

    CriteriaQuery<AlertCurrentEntity> query = visitor.getCriteriaQuery();
    javax.persistence.criteria.Predicate jpaPredicate = visitor.getJpaPredicate();

    if (null != jpaPredicate) {
        query.where(jpaPredicate);
    }

    // sorting
    JpaSortBuilder<AlertCurrentEntity> sortBuilder = new JpaSortBuilder<AlertCurrentEntity>();
    List<Order> sortOrders = sortBuilder.buildSortOrders(request.Sort, visitor);
    query.orderBy(sortOrders);

    // pagination
    TypedQuery<AlertCurrentEntity> typedQuery = entityManager.createQuery(query);
    if (null != request.Pagination) {
        // prevent JPA errors when -1 is passed in by accident
        int offset = request.Pagination.getOffset();
        if (offset < 0) {
            offset = 0;
        }

        typedQuery.setFirstResult(offset);
        typedQuery.setMaxResults(request.Pagination.getPageSize());
    }

    List<AlertCurrentEntity> alerts = m_daoUtils.selectList(typedQuery);

    // if caching is enabled, replace results with cached values when present
    if (m_configuration.isAlertCacheEnabled()) {
        alerts = supplementWithCachedAlerts(alerts);
    }

    return alerts;
}

From source file:org.apache.openejb.util.proxy.QueryProxy.java

private <T> Query createFinderQuery(final EntityManager entityManager, final String methodName,
        final Class<T> entityType, final Object[] args) {
    final List<String> conditions = parseMethodName(methodName);

    final EntityType<T> et = entityManager.getMetamodel().entity(entityType);
    final CriteriaBuilder cb = entityManager.getCriteriaBuilder();

    CriteriaQuery<Object> query = cb.createQuery();
    final Root<T> from = query.from(entityType);
    query = query.select(from);/*from  w  ww  .ja  va 2s  . co m*/

    int i = 0;
    Predicate where = null;
    for (final String condition : conditions) {
        final SingularAttribute<? super T, ?> attribute = et.getSingularAttribute(condition);
        final Path<?> path = from.get(attribute);
        final Class<?> javaType = attribute.getType().getJavaType();

        final Predicate currentClause;
        if (javaType.equals(String.class)) {
            currentClause = cb.like((Expression<String>) path, (String) args[i++]);
        } else if (Number.class.isAssignableFrom(javaType) || javaType.isPrimitive()) {
            currentClause = cb.equal(path, args[i++]);
        } else {
            LOGGER.warning("field " + condition + " not found, ignoring");
            continue;
        }

        if (where == null) {
            where = currentClause;
        } else {
            where = cb.and(where, currentClause);
        }
    }

    if (where != null) {
        query = query.where(where);
    }

    // pagination
    final TypedQuery<?> emQuery = entityManager.createQuery(query);
    if (args != null && args.length == conditions.size() + 2 && isInt(args[args.length - 2].getClass())
            && isInt(args[args.length - 1].getClass())) {
        final int first = (Integer) args[args.length - 2];
        final int max = (Integer) args[args.length - 1];

        emQuery.setFirstResult(first);
        emQuery.setMaxResults(max);
    }

    return emQuery;
}