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()]);
 }
  @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;
  }