コード例 #1
2
  @Override
  public Predicate toPredicate(Root<Role> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
    Predicate predicate = cb.conjunction();
    List<Expression<Boolean>> expressions = predicate.getExpressions();

    if (isNotBlank(criteria.getFilter())) {
      expressions.add(
          cb.or(
              cb.like(
                  cb.lower(root.<String>get(Role_.roleName)),
                  wildcardsAndLower(criteria.getFilter())),
              cb.like(
                  cb.lower(root.<String>get(Role_.roleDesc)),
                  wildcardsAndLower(criteria.getFilter()))));
    }

    if (isNotBlank(criteria.getRoleName())) {
      expressions.add(
          cb.like(
              cb.lower(root.<String>get(Role_.roleName)),
              wildcardsAndLower(criteria.getRoleName())));
    }
    if (isNotBlank(criteria.getRoleDesc())) {
      expressions.add(
          cb.like(
              cb.lower(root.<String>get(Role_.roleDesc)),
              wildcardsAndLower(criteria.getRoleDesc())));
    }
    if (null != criteria.getIsSys()) {
      expressions.add(cb.equal(root.<Boolean>get(Role_.isSys), criteria.getIsSys()));
    }
    return predicate;
  }
  public static CriteriaQuery<Organization> buildSearchQuery(
      String name,
      String email,
      String phone,
      String type,
      String region,
      String district,
      String locality,
      String streetToSearch,
      String sortCriteria,
      String sortOrder,
      EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Organization> criteriaQuery = cb.createQuery(Organization.class);
    Root<Organization> root = criteriaQuery.from(Organization.class);

    Predicate predicate =
        ArchivalOrganizationsQueryConstructorAdmin.buildPredicate(
            name, email, type, phone, region, district, locality, streetToSearch, root, cb);
    if ((sortCriteria != null) && (sortOrder != null)) {
      criteriaQuery.orderBy(
          SortCriteriaOrganization.valueOf(sortCriteria.toUpperCase())
              .getSortOrder(root, cb, sortOrder));
    } else {
      criteriaQuery.orderBy(cb.desc(root.get("id")));
    }
    criteriaQuery.select(root);
    criteriaQuery.where(predicate);
    return criteriaQuery;
  }
コード例 #3
0
  @SuppressWarnings("unchecked")
  public static Predicate[] deviceListPredicates(
      CriteriaBuilder cb,
      Root<Device> from,
      Optional<String> name,
      Optional<String> namePattern,
      Optional<String> status,
      Optional<Long> networkId,
      Optional<String> networkName,
      Optional<Long> deviceClassId,
      Optional<String> deviceClassName,
      Optional<String> deviceClassVersion,
      Optional<HivePrincipal> principal) {
    final List<Predicate> predicates = new LinkedList<>();

    name.ifPresent(n -> predicates.add(cb.equal(from.<String>get("name"), n)));
    namePattern.ifPresent(np -> predicates.add(cb.like(from.<String>get("name"), np)));
    status.ifPresent(s -> predicates.add(cb.equal(from.<String>get("status"), s)));

    final Join<Device, Network> networkJoin = (Join) from.fetch("network", JoinType.LEFT);
    networkId.ifPresent(nId -> predicates.add(cb.equal(networkJoin.<Long>get("id"), nId)));
    networkName.ifPresent(
        nName -> predicates.add(cb.equal(networkJoin.<String>get("name"), nName)));

    final Join<Device, DeviceClass> dcJoin = (Join) from.fetch("deviceClass", JoinType.LEFT);
    deviceClassId.ifPresent(dcId -> predicates.add(cb.equal(dcJoin.<Long>get("id"), dcId)));
    deviceClassName.ifPresent(
        dcName -> predicates.add(cb.equal(dcJoin.<String>get("name"), dcName)));
    deviceClassVersion.ifPresent(
        dcVersion -> predicates.add(cb.equal(dcJoin.<String>get("version"), dcVersion)));

    predicates.addAll(deviceSpecificPrincipalPredicates(cb, from, principal));

    return predicates.toArray(new Predicate[predicates.size()]);
  }
  private <C, X> Subquery<?> createCountSubQuery(
      Root<T> root,
      CriteriaQuery<Long> countQuery,
      Selections<T, C, X> selection,
      CriteriaBuilder builder,
      Specification<T> spec,
      List<Expression<?>> groupBy,
      Predicate having) {

    Subquery<?> subquery = countQuery.subquery(entityInformation.getIdType());
    Root subRoot = subquery.from(entityInformation.getJavaType());
    Expression[] select = selection.select(subRoot, (AbstractQuery<C>) subquery, builder);
    subquery.select(select[0]);
    selection.join(subRoot, builder);
    Predicate predicate =
        builder.equal(
            subRoot.get(entityInformation.getIdAttribute()),
            root.get(entityInformation.getIdAttribute()));
    if (predicate != null) {
      subquery.where(predicate);
    }
    if (groupBy != null) {
      subquery.groupBy(groupBy);
    }
    if (having != null) {
      subquery.having(having);
    }
    return subquery;
  }
コード例 #5
0
 /**
  * Adds ORDER BY ... ASC/DESC to query Mutates provided criteria query
  *
  * @param sortFieldOpt - field to sort by (field name in JPA Entity class)
  * @param asc - true if order should be ASC, false otherwise
  */
 public static void order(
     CriteriaBuilder cb,
     CriteriaQuery<?> cq,
     Root<?> from,
     Optional<String> sortFieldOpt,
     boolean asc) {
   sortFieldOpt.ifPresent(
       sortField -> {
         Order order = asc ? cb.asc(from.get(sortField)) : cb.desc(from.get(sortField));
         cq.orderBy(order);
       });
 }
コード例 #6
0
  @Override
  public List<Product> getProductsByConditions(
      String categoryContain, String nameContain, Float priceFrom, Float priceBefore) {
    openConnection();
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Product> cq = cb.createQuery(Product.class);
    Root<Product> productRoot = cq.from(Product.class);
    List<Predicate> predicates = new ArrayList<Predicate>();

    if (categoryContain != null) {
      if (!categoryContain.equals("")) {
        Expression<String> catName = productRoot.get("cat").get("name");
        Predicate catNameContainPredicate = cb.like(cb.lower(catName), "%" + categoryContain + "%");
        predicates.add(catNameContainPredicate);
      }
    }

    if (nameContain != null) {
      if (!nameContain.equals("")) {
        Expression<String> productName = productRoot.get("name");
        Predicate nameContainPredicate = cb.like(cb.lower(productName), "%" + nameContain + "%");
        predicates.add(nameContainPredicate);
      }
    }

    Expression<Float> price = productRoot.get("price");
    if (priceBefore != null) {
      Predicate pricePredicate = cb.between(price, priceFrom, priceBefore);
      predicates.add(pricePredicate);
    }

    if (priceBefore == null) {
      Predicate pricePredicate = cb.gt(price, priceFrom);
      predicates.add(pricePredicate);
    }

    cq.select(productRoot);

    if (predicates.size() != 0) {
      Predicate[] predicatesArray = new Predicate[predicates.size()];
      cq.where(predicates.toArray(predicatesArray));
    }

    TypedQuery<Product> productTypedQuery = entityManager.createQuery(cq);
    List<Product> productList = productTypedQuery.getResultList();
    closeConnection();

    return DbManagerPersistence.filterProducts(productList, nameContain, categoryContain);
  }
コード例 #7
0
  public static Predicate[] deviceClassListPredicates(
      CriteriaBuilder cb,
      Root<DeviceClass> from,
      Optional<String> name,
      Optional<String> namePattern,
      Optional<String> version) {
    final List<Predicate> predicates = new LinkedList<>();
    if (namePattern.isPresent()) {
      namePattern.ifPresent(np -> predicates.add(cb.like(from.get("name"), np)));
    } else {
      name.ifPresent(n -> predicates.add(cb.equal(from.get("name"), n)));
    }

    version.ifPresent(v -> predicates.add(cb.equal(from.get(DeviceClass.VERSION_COLUMN), v)));
    return predicates.toArray(new Predicate[predicates.size()]);
  }
コード例 #8
0
ファイル: UserEJB.java プロジェクト: gauravjn/ezrent
  /** @author Romain Wurtz <*****@*****.**> */
  public List<User> load(
      int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {

    CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
    CriteriaQuery<User> dataQuery = criteriaBuilder.createQuery(User.class);
    Root<User> from = dataQuery.from(User.class);
    if (sortField != null) {
      if (sortOrder == SortOrder.ASCENDING) {
        dataQuery.orderBy(criteriaBuilder.asc(from.get(sortField)));
      } else {
        dataQuery.orderBy(criteriaBuilder.desc(from.get(sortField)));
      }
    }
    List<Predicate> predicates = createPredicates(from, criteriaBuilder, filters);
    dataQuery.where(predicates.toArray(new Predicate[predicates.size()]));
    return em.createQuery(dataQuery).setFirstResult(first).setMaxResults(pageSize).getResultList();
  }
コード例 #9
0
 static Application findApplication(String name, String version) {
   EntityManager em = Stripersist.getEntityManager();
   if (name != null) {
     CriteriaBuilder cb = em.getCriteriaBuilder();
     CriteriaQuery q = cb.createQuery(Application.class);
     Root<Application> root = q.from(Application.class);
     Predicate namePredicate = cb.equal(root.get("name"), name);
     Predicate versionPredicate =
         version != null ? cb.equal(root.get("version"), version) : cb.isNull(root.get("version"));
     q.where(cb.and(namePredicate, versionPredicate));
     try {
       return (Application) em.createQuery(q).getSingleResult();
     } catch (NoResultException nre) {
     }
   }
   return null;
 }
コード例 #10
0
 @Override
 public List<? extends Image> getImages(
     int firstResult, int maxResults, Map<String, String> sorts) {
   // From Query
   CriteriaQuery<ImageImpl> fromQuery = this.builder.createQuery(ImageImpl.class);
   Root<ImageImpl> images = fromQuery.from(ImageImpl.class);
   // Select Query
   CriteriaQuery<ImageImpl> selectQuery = fromQuery.select(images);
   // Order
   if (sorts != null) {
     List<Order> orders = new ArrayList<>();
     for (Map.Entry<String, String> entry : sorts.entrySet()) {
       String field = entry.getKey();
       String sortType = entry.getValue();
       if (field != null && sortType != null) {
         if (field.startsWith("file.")) {
           if (sortType.equalsIgnoreCase("asc")) {
             orders.add(this.builder.asc(images.join("originalFile").get(field.substring(5))));
           } else if (sortType.equalsIgnoreCase("desc")) {
             orders.add(this.builder.desc(images.join("originalFile").get(field.substring(5))));
           }
         } else {
           if (sortType.equalsIgnoreCase("asc")) {
             orders.add(this.builder.asc(images.get(field)));
           } else if (sortType.equalsIgnoreCase("desc")) {
             orders.add(this.builder.asc(images.get(field)));
           }
         }
       }
     }
     selectQuery.orderBy(orders);
   }
   // Final Query
   TypedQuery<ImageImpl> typedQuery = this.entityManager.createQuery(selectQuery);
   // First Result
   if (firstResult >= 0) {
     typedQuery = typedQuery.setFirstResult(firstResult);
   }
   // Max Results
   if (maxResults >= 0) {
     typedQuery = typedQuery.setMaxResults(maxResults);
   }
   return typedQuery.getResultList();
 }
コード例 #11
0
  public static Predicate[] oAuthClientListPredicates(
      CriteriaBuilder cb,
      Root<OAuthClient> from,
      Optional<String> nameOpt,
      Optional<String> namePattern,
      Optional<String> domainOpt,
      Optional<String> oauthIdOpt) {
    List<Predicate> predicates = new LinkedList<>();

    if (namePattern.isPresent()) {
      namePattern.ifPresent(pattern -> predicates.add(cb.like(from.get("name"), pattern)));
    } else {
      nameOpt.ifPresent(name -> predicates.add(cb.equal(from.get("name"), name)));
    }
    domainOpt.ifPresent(domain -> predicates.add(cb.equal(from.get("domain"), domain)));
    oauthIdOpt.ifPresent(id -> predicates.add(cb.equal(from.get("oauthId"), id)));

    return predicates.toArray(new Predicate[predicates.size()]);
  }
コード例 #12
0
  public static Predicate[] userListPredicates(
      CriteriaBuilder cb,
      Root<User> from,
      Optional<String> loginOpt,
      Optional<String> loginPattern,
      Optional<Integer> roleOpt,
      Optional<Integer> statusOpt) {
    List<Predicate> predicates = new LinkedList<>();

    if (loginPattern.isPresent()) {
      loginPattern.ifPresent(pattern -> predicates.add(cb.like(from.get("login"), pattern)));
    } else {
      loginOpt.ifPresent(login -> predicates.add(cb.equal(from.get("login"), login)));
    }

    roleOpt.ifPresent(role -> predicates.add(cb.equal(from.get("role"), role)));
    statusOpt.ifPresent(status -> predicates.add(cb.equal(from.get("status"), status)));

    return predicates.toArray(new Predicate[predicates.size()]);
  }
  private static Predicate buildPredicate(
      String name,
      String email,
      String phone,
      String type,
      String region,
      String district,
      String locality,
      String streetToSearch,
      Root<Organization> root,
      CriteriaBuilder cb) {
    Predicate queryPredicate = cb.conjunction();

    if (StringUtils.isNotEmpty(name)) {
      queryPredicate = cb.and(cb.like(root.get("name"), "%" + name + "%"), queryPredicate);
    }

    if (StringUtils.isNotEmpty(email)) {
      queryPredicate = cb.and(cb.like(root.get("email"), "%" + email + "%"), queryPredicate);
    }
    if (StringUtils.isNotEmpty(phone)) {
      queryPredicate = cb.and(cb.like(root.get("phone"), "%" + phone + "%"), queryPredicate);
    }
    if (StringUtils.isNotEmpty(type)) {
      OrganizationType organizationType = OrganizationType.valueOf(type.trim());
      queryPredicate =
          cb.and(cb.isMember(organizationType, root.get("organizationTypes")), queryPredicate);
    }
    if (StringUtils.isNotEmpty(region)) {
      queryPredicate =
          cb.and(cb.like(root.get("address").get("region"), "%" + region + "%"), queryPredicate);
    }
    if (StringUtils.isNotEmpty(district)) {
      queryPredicate =
          cb.and(
              cb.like(root.get("address").get("district"), "%" + district + "%"), queryPredicate);
    }
    if (StringUtils.isNotEmpty(locality)) {
      queryPredicate =
          cb.and(
              cb.like(root.get("address").get("locality"), "%" + locality + "%"), queryPredicate);
    }
    if (StringUtils.isNotEmpty(streetToSearch)) {
      queryPredicate =
          cb.and(
              cb.like(root.get("address").get("street"), "%" + streetToSearch + "%"),
              queryPredicate);
    }

    return queryPredicate;
  }
コード例 #14
0
ファイル: UserEJB.java プロジェクト: gauravjn/ezrent
  /** @author Romain Wurtz <*****@*****.**> */
  public List<Predicate> createPredicates(
      Root<User> from, CriteriaBuilder criteriaBuilder, Map<String, String> filters) {
    List<Predicate> predicates = new ArrayList<Predicate>();
    for (Iterator<String> it = filters.keySet().iterator(); it.hasNext(); ) {
      String filterProperty = it.next();
      String filterValue = filters.get(filterProperty);

      Expression<String> literal = criteriaBuilder.literal("%" + (String) filterValue + "%");
      predicates.add(criteriaBuilder.like(from.<String>get(filterProperty), literal));
    }
    return predicates;
  }
コード例 #15
0
  public static Predicate[] deviceListPredicates(
      CriteriaBuilder cb,
      Root<Device> from,
      List<String> guids,
      Optional<HivePrincipal> principal) {
    final List<Predicate> predicates = deviceSpecificPrincipalPredicates(cb, from, principal);
    if (guids != null && !guids.isEmpty()) {
      predicates.add(from.get(GUID).in(guids));
    }

    return predicates.toArray(new Predicate[predicates.size()]);
  }
コード例 #16
0
 public static Predicate[] networkPermissionsPredicates(
     CriteriaBuilder cb, Root<?> from, Set<AccessKeyPermission> permissions) {
   List<Predicate> predicates = new ArrayList<>();
   for (AccessKeyBasedFilterForDevices extraFilter :
       AccessKeyBasedFilterForDevices.createExtraFilters(permissions)) {
     List<Predicate> filter = new ArrayList<>();
     if (extraFilter.getNetworkIds() != null) {
       filter.add(from.get("id").in(extraFilter.getNetworkIds()));
     }
     predicates.add(cb.and(filter.toArray(new Predicate[filter.size()])));
   }
   return predicates.toArray(new Predicate[predicates.size()]);
 }
コード例 #17
0
  public static Predicate[] accessKeyListPredicates(
      CriteriaBuilder cb,
      Root<AccessKey> from,
      Long userId,
      Optional<String> labelOpt,
      Optional<String> labelPatten,
      Optional<Integer> typeOpt) {
    List<Predicate> predicates = new LinkedList<>();

    Join user = (Join) from.fetch("user", JoinType.LEFT);
    predicates.add(cb.equal(user.get("id"), userId));

    if (labelPatten.isPresent()) {
      labelPatten.ifPresent(pattern -> predicates.add(cb.like(from.get("label"), pattern)));
    } else {
      labelOpt.ifPresent(label -> predicates.add(cb.equal(from.get("label"), label)));
    }

    typeOpt.ifPresent(type -> predicates.add(cb.equal(from.get("type"), type)));

    return predicates.toArray(new Predicate[predicates.size()]);
  }
コード例 #18
0
 @Override
 public List<String> getImageAlbums(int firstResult, int maxResults, Map<String, String> sorts) {
   // From Query
   CriteriaQuery<String> fromQuery = this.builder.createQuery(String.class);
   Root<ImageImpl> images = fromQuery.from(ImageImpl.class);
   // Select Query
   CriteriaQuery<String> selectQuery = fromQuery.multiselect(images.get("album"));
   selectQuery.distinct(true);
   if (sorts != null) {
     List<Order> orders = new ArrayList<>();
     for (Map.Entry<String, String> entry : sorts.entrySet()) {
       String field = entry.getKey();
       String sortType = entry.getValue();
       if (field != null && sortType != null) {
         if (field.equals("album")) {
           if (sortType.equalsIgnoreCase("asc")) {
             orders.add(this.builder.asc(images.get(field)));
           } else if (sortType.equalsIgnoreCase("desc")) {
             orders.add(this.builder.asc(images.get(field)));
           }
         }
       }
     }
     selectQuery.orderBy(orders);
   }
   // Final Query
   TypedQuery<String> typedQuery = this.entityManager.createQuery(selectQuery);
   // First Result
   if (firstResult >= 0) {
     typedQuery = typedQuery.setFirstResult(firstResult);
   }
   // Max Results
   if (maxResults >= 0) {
     typedQuery = typedQuery.setMaxResults(maxResults);
   }
   return typedQuery.getResultList();
 }
コード例 #19
0
  /**
   * Creates an array of JPA predicates for networks list query. Add filter predicates for name and
   * principal if required. 1) if name is specified adds 'name = ?' predicate 2) if name pattern is
   * specified adds 'name like ?' predicate 3) if principal is user of key without ADMIN role adds
   * predicate for filtering not assigned networks 4) if principal is key which has permissions only
   * to specific networks adds 'network.id in (allowed_networks)' predicates
   *
   * @return array of above predicates
   * @see {@link com.devicehive.service.NetworkService#list(String, String, String, boolean,
   *     Integer, Integer, HivePrincipal)}
   */
  public static Predicate[] networkListPredicates(
      CriteriaBuilder cb,
      Root<Network> from,
      Optional<String> nameOpt,
      Optional<String> namePatternOpt,
      Optional<HivePrincipal> principalOpt) {
    List<Predicate> predicates = new LinkedList<>();

    nameOpt.ifPresent(name -> predicates.add(cb.equal(from.get("name"), name)));

    namePatternOpt.ifPresent(pattern -> predicates.add(cb.like(from.get("name"), pattern)));

    principalOpt
        .flatMap(
            principal -> {
              User user = principal.getUser();
              if (user == null && principal.getKey() != null) {
                user = principal.getKey().getUser();
              }
              return ofNullable(user);
            })
        .ifPresent(
            user -> {
              if (!user.isAdmin()) {
                predicates.add(from.join("users").in(user));
              }
            });

    principalOpt
        .map(HivePrincipal::getKey)
        .ifPresent(
            key ->
                predicates.add(
                    cb.or(networkPermissionsPredicates(cb, from, key.getPermissions()))));

    return predicates.toArray(new Predicate[predicates.size()]);
  }
  private <C, X> TypedQuery<Long> getCountQuery(
      Specification<T> spec,
      Selections<T, C, X> selection,
      List<Expression<?>> groupBy,
      Predicate having) {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Long> countQuery = builder.createQuery(Long.class);
    Root<T> root = countQuery.from(getDomainClass());

    Subquery<?> subquery =
        createCountSubQuery(root, countQuery, selection, builder, spec, groupBy, having);
    Path<?> path = root.get(entityInformation.getIdAttribute());
    countQuery.select(builder.countDistinct(path)).where(builder.exists(subquery));
    return em.createQuery(countQuery);
  }
コード例 #21
0
  @SuppressWarnings("unchecked")
  private static List<Predicate> deviceSpecificPrincipalPredicates(
      CriteriaBuilder cb, Root<Device> from, Optional<HivePrincipal> principal) {
    final List<Predicate> predicates = new LinkedList<>();
    final Join<Device, Network> networkJoin = (Join) from.fetch("network", JoinType.LEFT);
    final Join<Device, Network> usersJoin = (Join) networkJoin.fetch("users", JoinType.LEFT);
    from.fetch("deviceClass", JoinType.LEFT); // need this fetch to populate deviceClass
    principal.ifPresent(
        p -> {
          User user = p.getUser();
          if (user == null && p.getKey() != null) {
            user = p.getKey().getUser();
          }
          if (user != null && !user.isAdmin()) {
            predicates.add(cb.equal(usersJoin.<Long>get("id"), user.getId()));
          }

          if (p.getDevice() != null) {
            predicates.add(cb.equal(from.<Long>get("id"), p.getDevice().getId()));
          }

          if (p.getKey() != null) {
            for (AccessKeyBasedFilterForDevices extraFilter :
                AccessKeyBasedFilterForDevices.createExtraFilters(p.getKey().getPermissions())) {
              if (extraFilter.getDeviceGuids() != null) {
                predicates.add(from.<String>get("guid").in(extraFilter.getDeviceGuids()));
              }
              if (extraFilter.getNetworkIds() != null) {
                predicates.add(networkJoin.<Long>get("id").in(extraFilter.getNetworkIds()));
              }
            }
          }
        });

    return predicates;
  }
  @Override
  public SearchResult<VeteranAssessment> searchVeteranAssessment(
      Integer veteranAssessmentId,
      Integer veteranId,
      Integer programId,
      Integer clinicanId,
      Integer createdByUserId,
      Date fromAssessmentDate,
      Date toAssessmentDate,
      List<Integer> programIdList,
      SearchAttributes searchAttributes) {

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<VeteranAssessment> criteriaQuery =
        criteriaBuilder.createQuery(VeteranAssessment.class);

    Root<VeteranAssessment> veteranAssessmentRoot = criteriaQuery.from(VeteranAssessment.class);
    Join<VeteranAssessment, AssessmentStatus> assessmentStatusJoin =
        veteranAssessmentRoot.join("assessmentStatus");
    Join<VeteranAssessment, Veteran> veteranJoin = veteranAssessmentRoot.join("veteran");
    Join<VeteranAssessment, Program> programJoin = veteranAssessmentRoot.join("program");
    Join<VeteranAssessment, User> clinicianJoin = veteranAssessmentRoot.join("clinician");
    Join<VeteranAssessment, User> createdByUserJoin = veteranAssessmentRoot.join("createdByUser");

    List<Predicate> criteriaList = new ArrayList<Predicate>();

    if (veteranAssessmentId != null) {
      criteriaList.add(
          criteriaBuilder.equal(
              veteranAssessmentRoot.get("veteranAssessmentId"), veteranAssessmentId));
    }

    if (veteranId != null) {
      criteriaList.add(criteriaBuilder.equal(veteranJoin.get("veteranId"), veteranId));
    }

    if (programId != null) {
      criteriaList.add(criteriaBuilder.equal(programJoin.get("programId"), programId));
    }

    if (clinicanId != null) {
      criteriaList.add(criteriaBuilder.equal(clinicianJoin.get("userId"), clinicanId));
    }

    if (createdByUserId != null) {
      criteriaList.add(criteriaBuilder.equal(createdByUserJoin.get("userId"), createdByUserId));
    }

    if (fromAssessmentDate != null) {
      criteriaList.add(
          criteriaBuilder.greaterThanOrEqualTo(
              veteranAssessmentRoot.<Date>get("dateUpdated"), fromAssessmentDate));
    }

    if (toAssessmentDate != null) {
      criteriaList.add(
          criteriaBuilder.lessThanOrEqualTo(
              veteranAssessmentRoot.<Date>get("dateUpdated"), toAssessmentDate));
    }

    if (programIdList != null && programIdList.size() > 0) {
      Expression<Integer> exp = programJoin.get("programId");
      Predicate programIdPredicate = exp.in(programIdList);
      criteriaList.add(programIdPredicate);
    }

    criteriaQuery.select(veteranAssessmentRoot);
    criteriaQuery.where(criteriaBuilder.and(criteriaList.toArray(new Predicate[0])));

    // Set default order by field and then check if one was passed to us.
    @SuppressWarnings("rawtypes")
    Expression orderByPath = veteranAssessmentRoot.get("veteranAssessmentId");

    if (StringUtils.isNotBlank(searchAttributes.getSortColumn())) {
      if (searchAttributes.getSortColumn().equalsIgnoreCase("programName")) {
        orderByPath = programJoin.get("name");
      } else if (searchAttributes.getSortColumn().equalsIgnoreCase("clinicianName")) {
        orderByPath = clinicianJoin.get("lastName");
      } else if (searchAttributes.getSortColumn().equalsIgnoreCase("createdBy")) {
        orderByPath = createdByUserJoin.get("lastName");
      } else if (searchAttributes.getSortColumn().equalsIgnoreCase("createDate")) {
        orderByPath = veteranAssessmentRoot.get("dateCreated");
      } else if (searchAttributes.getSortColumn().equalsIgnoreCase("assessmentDate")) {
        orderByPath = veteranAssessmentRoot.get("dateUpdated");
      } else if (searchAttributes.getSortColumn().equalsIgnoreCase("completeDate")) {
        orderByPath = veteranAssessmentRoot.get("dateCompleted");
      } else if (searchAttributes.getSortColumn().equalsIgnoreCase("veteranId")) {
        orderByPath = veteranJoin.get("veteranId");
      } else if (searchAttributes.getSortColumn().equalsIgnoreCase("veteranName")) {
        orderByPath = veteranJoin.get("lastName");
      } else if (searchAttributes.getSortColumn().equalsIgnoreCase("assessmentStatusName")) {
        orderByPath = assessmentStatusJoin.get("name");
      } else if (searchAttributes.getSortColumn().equalsIgnoreCase("ssnLastFour")) {
        orderByPath = veteranJoin.get("ssnLastFour");
      } else if (searchAttributes.getSortColumn().equalsIgnoreCase("duration")) {
        orderByPath = veteranAssessmentRoot.get("duration");
      } else if (searchAttributes.getSortColumn().equalsIgnoreCase("percentComplete")) {
        orderByPath = veteranAssessmentRoot.get("percentComplete");
      }
    }

    if (searchAttributes.getSortDirection() == SortDirection.SORT_DESCENDING) {

      criteriaQuery.orderBy(criteriaBuilder.desc(orderByPath));
    } else {
      criteriaQuery.orderBy(criteriaBuilder.asc(orderByPath));
    }

    // Generate the query based on the criteria.
    TypedQuery<VeteranAssessment> query = entityManager.createQuery(criteriaQuery);

    SearchResult<VeteranAssessment> searchResult = new SearchResult<VeteranAssessment>();

    // Get the total count. Not a very efficient way....
    Integer totalCount = query.getResultList().size();
    searchResult.setTotalNumRowsFound(totalCount);

    // Now get only the page.
    query.setFirstResult(searchAttributes.getRowStartIndex());
    query.setMaxResults(searchAttributes.getPageSize());

    List<VeteranAssessment> veteranAssessments = query.getResultList();
    searchResult.setResultList(veteranAssessments);

    return searchResult;
  }
  @Override
  public List<VeteranAssessment> searchVeteranAssessmentForExport(
      Integer clinicanId,
      Integer createdByUserId,
      Integer programId,
      Date fromAssessmentDate,
      Date toAssessmentDate,
      Integer veteranId,
      List<Integer> programIdList) {

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<VeteranAssessment> criteriaQuery =
        criteriaBuilder.createQuery(VeteranAssessment.class);

    Root<VeteranAssessment> veteranAssessmentRoot = criteriaQuery.from(VeteranAssessment.class);
    Join<VeteranAssessment, AssessmentStatus> assessmentStatusJoin =
        veteranAssessmentRoot.join("assessmentStatus");

    List<Predicate> criteriaList = new ArrayList<Predicate>();

    // only include assessments in the appropriate state
    Expression<Integer> statusExp = assessmentStatusJoin.get("assessmentStatusId");
    Predicate statusPredicate = statusExp.in(getExportAssessmentStates());
    criteriaList.add(statusPredicate);

    if (clinicanId != null) {
      Join<VeteranAssessment, User> clinicianJoin = veteranAssessmentRoot.join("clinician");
      criteriaList.add(criteriaBuilder.equal(clinicianJoin.get("userId"), clinicanId));
    }

    if (createdByUserId != null) {
      Join<VeteranAssessment, User> createdByUserJoin = veteranAssessmentRoot.join("createdByUser");
      criteriaList.add(criteriaBuilder.equal(createdByUserJoin.get("userId"), createdByUserId));
    }

    if (fromAssessmentDate != null) {
      criteriaList.add(
          criteriaBuilder.greaterThan(
              veteranAssessmentRoot.<Date>get("dateCreated"), fromAssessmentDate));
    }

    if (toAssessmentDate != null) {
      criteriaList.add(
          criteriaBuilder.lessThanOrEqualTo(
              veteranAssessmentRoot.<Date>get("dateCreated"), toAssessmentDate));
    }

    if (veteranId != null) {
      Join<VeteranAssessment, Veteran> veteranJoin = veteranAssessmentRoot.join("veteran");
      criteriaList.add(criteriaBuilder.equal(veteranJoin.get("veteranId"), veteranId));
    }

    if (programId != null) {
      // criteriaList.add(criteriaBuilder.equal(programJoin.get("programId"), programId));
      if (programIdList == null) {
        programIdList = new ArrayList<Integer>();
      }

      programIdList.add(programId);
    }

    if (programIdList != null && programIdList.size() > 0) {
      Join<VeteranAssessment, Program> programJoin = veteranAssessmentRoot.join("program");
      Expression<Integer> exp = programJoin.get("programId");
      Predicate programIdPredicate = exp.in(programIdList);
      criteriaList.add(programIdPredicate);
    }

    criteriaQuery.select(veteranAssessmentRoot);
    criteriaQuery.where(criteriaBuilder.and(criteriaList.toArray(new Predicate[0])));

    @SuppressWarnings("rawtypes")
    Expression orderByPath = veteranAssessmentRoot.get("veteranAssessmentId");

    criteriaQuery.orderBy(criteriaBuilder.desc(orderByPath));

    // Generate the query based on the criteria.
    TypedQuery<VeteranAssessment> query = entityManager.createQuery(criteriaQuery);
    List<VeteranAssessment> veteranAssessments = query.getResultList();

    return veteranAssessments;
  }
コード例 #24
-1
  public static Predicate[] oAuthGrantsListPredicates(
      CriteriaBuilder cb,
      Root<OAuthGrant> from,
      User user,
      Optional<Date> startOpt,
      Optional<Date> endOpt,
      Optional<String> oAuthIdOpt,
      Optional<Integer> typeOpt,
      Optional<String> scopeOpt,
      Optional<String> redirectUri,
      Optional<Integer> accessType) {
    List<Predicate> predicates = new LinkedList<>();

    if (!user.isAdmin()) {
      predicates.add(from.join("user").in(user));
    }

    startOpt.ifPresent(start -> predicates.add(cb.greaterThan(from.get("timestamp"), start)));
    endOpt.ifPresent(end -> predicates.add(cb.lessThan(from.get("timestamp"), end)));
    oAuthIdOpt.ifPresent(id -> predicates.add(cb.equal(from.join("client").get("oauthId"), id)));
    typeOpt.ifPresent(type -> predicates.add(cb.equal(from.get("type"), type)));
    scopeOpt.ifPresent(scope -> predicates.add(cb.equal(from.get("scope"), scope)));
    redirectUri.ifPresent(uri -> predicates.add(cb.equal(from.get("redirectUri"), uri)));
    accessType.ifPresent(at -> predicates.add(cb.equal(from.get("accessType"), at)));

    return predicates.toArray(new Predicate[predicates.size()]);
  }