/*
(non-Javadoc)

@see ca.uhn.fhir.jpa.dao.ISearchParamExtractor#extractSearchParamQuantity(ca.uhn.fhir.jpa.entity.ResourceTable,
ca.uhn.fhir.model.api.IResource)
172563
@Override
	public Set<ResourceIndexedSearchParamQuantity> extractSearchParamQuantity(ResourceTable theEntity, IBaseResource theResource) {
		HashSet<ResourceIndexedSearchParamQuantity> retVal = new HashSet<ResourceIndexedSearchParamQuantity>();

		Collection<RuntimeSearchParam> searchParams = getSearchParams(theResource);
		for (RuntimeSearchParam nextSpDef : searchParams) {
			if (nextSpDef.getParamType() != RestSearchParameterTypeEnum.QUANTITY) {
				continue;
			}

			String nextPath = nextSpDef.getPath();
			if (isBlank(nextPath)) {
				continue;
			}

			for (Object nextObject : extractValues(nextPath, theResource)) {
				if (nextObject == null || ((IDatatype) nextObject).isEmpty()) {
					continue;
				}

				String resourceName = nextSpDef.getName();
				boolean multiType = false;
				if (nextPath.endsWith("[x]")) {
					multiType = true;
				}

				if (nextObject instanceof QuantityDt) {
					QuantityDt nextValue = (QuantityDt) nextObject;
					if (nextValue.getValueElement().isEmpty()) {
						continue;
					}

					ResourceIndexedSearchParamQuantity nextEntity = new ResourceIndexedSearchParamQuantity(resourceName, nextValue.getValueElement().getValue(), nextValue.getSystemElement().getValueAsString(), nextValue.getCode());
					nextEntity.setResource(theEntity);
					retVal.add(nextEntity);
				} else {
					if (!multiType) {
						throw new ConfigurationException("Search param " + resourceName + " is of unexpected datatype: " + nextObject.getClass());
					} else {
						continue;
					}
				}
			}
		}

		return retVal;
	}
53883
@Operation(name = JpaConstants.OPERATION_GET_RESOURCE_COUNTS, idempotent = true, returnParameters = {
		@OperationParam(name = "AllergyIntolerance", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Appointment", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "AppointmentResponse", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "AuditEvent", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Basic", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Binary", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "BodySite", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Bundle", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "CarePlan", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "CarePlan2", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Claim", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "ClaimResponse", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "ClinicalImpression", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Communication", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "CommunicationRequest", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Composition", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "ConceptMap", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Condition", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Conformance", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Contract", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Contraindication", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Coverage", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "DataElement", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Device", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "DeviceComponent", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "DeviceMetric", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "DeviceUseRequest", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "DeviceUseStatement", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "DiagnosticOrder", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "DiagnosticReport", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "DocumentManifest", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "DocumentReference", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "EligibilityRequest", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "EligibilityResponse", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Encounter", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "EnrollmentRequest", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "EnrollmentResponse", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "EpisodeOfCare", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "ExplanationOfBenefit", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "FamilyMemberHistory", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Flag", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Goal", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Group", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "HealthcareService", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "ImagingObjectSelection", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "ImagingStudy", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Immunization", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "ImmunizationRecommendation", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "ListResource", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Location", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Media", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Medication", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "MedicationAdministration", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "MedicationDispense", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "MedicationPrescription", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "MedicationStatement", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "MessageHeader", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "NamingSystem", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "NutritionOrder", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Observation", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "OperationDefinition", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "OperationOutcome", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Order", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "OrderResponse", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Organization", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Parameters", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Patient", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "PaymentNotice", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "PaymentReconciliation", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Person", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Practitioner", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Procedure", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "ProcedureRequest", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "ProcessRequest", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "ProcessResponse", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Provenance", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Questionnaire", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "QuestionnaireAnswers", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "ReferralRequest", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "RelatedPerson", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "RiskAssessment", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Schedule", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "SearchParameter", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Slot", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Specimen", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "StructureDefinition", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Subscription", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Substance", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "Supply", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "ValueSet", type = IntegerDt.class, min = 0, max = 1),
		@OperationParam(name = "VisionPrescription", type = IntegerDt.class, min = 0, max = 1)
	})
	@Description(shortDefinition = "Provides the number of resources currently stored on the server, broken down by resource type")
	//@formatter:on
	public Parameters getResourceCounts() {
		Parameters retVal = new Parameters();

		Map<String, Long> counts = mySystemDao.getResourceCountsFromCache();
		counts = defaultIfNull(counts, Collections.emptyMap());
		counts = new TreeMap<>(counts);
		for (Entry<String, Long> nextEntry : counts.entrySet()) {
			retVal.addParameter().setName(new StringDt(nextEntry.getKey())).setValue(new IntegerDt(nextEntry.getValue().intValue()));
		}

		return retVal;
	}
7881
@Override
	public Set<ResourceIndexedSearchParamString> extractSearchParamStrings(ResourceTable theEntity, IBaseResource theResource) {
		HashSet<ResourceIndexedSearchParamString> retVal = new HashSet<ResourceIndexedSearchParamString>();

		String resourceName = getContext().getResourceDefinition(theResource).getName();

		Collection<RuntimeSearchParam> searchParams = getSearchParams(theResource);
		for (RuntimeSearchParam nextSpDef : searchParams) {
			if (nextSpDef.getParamType() != RestSearchParameterTypeEnum.STRING) {
				continue;
			}

			String nextPath = nextSpDef.getPath();
			String nextSpName = nextSpDef.getName();

			if (isBlank(nextPath)) {

				// TODO: implement phonetic, and any others that have no path

				if ("Questionnaire".equals(resourceName) && nextSpDef.getName().equals("title")) {
					Questionnaire q = (Questionnaire) theResource;
					String title = q.getGroup().getTitle();
					addSearchTerm(theEntity, retVal, nextSpName, title);
				}
				continue;
			}

			for (Object nextObject : extractValues(nextPath, theResource)) {
				if (nextObject == null || ((IDatatype) nextObject).isEmpty()) {
					continue;
				}

				boolean multiType = false;
				if (nextPath.endsWith("[x]")) {
					multiType = true;
				}

				if (nextObject instanceof IPrimitiveDatatype<?>) {
					IPrimitiveDatatype<?> nextValue = (IPrimitiveDatatype<?>) nextObject;
					String searchTerm = nextValue.getValueAsString();
					addSearchTerm(theEntity, retVal, nextSpName, searchTerm);
				} else {
					if (nextObject instanceof BaseHumanNameDt) {
						ArrayList<StringDt> allNames = new ArrayList<StringDt>();
						HumanNameDt nextHumanName = (HumanNameDt) nextObject;
						allNames.addAll(nextHumanName.getFamily());
						allNames.addAll(nextHumanName.getGiven());
						for (StringDt nextName : allNames) {
							addSearchTerm(theEntity, retVal, nextSpName, nextName.getValue());
						}
					} else if (nextObject instanceof AddressDt) {
						ArrayList<StringDt> allNames = new ArrayList<StringDt>();
						AddressDt nextAddress = (AddressDt) nextObject;
						allNames.addAll(nextAddress.getLine());
						allNames.add(nextAddress.getCityElement());
						allNames.add(nextAddress.getStateElement());
						allNames.add(nextAddress.getCountryElement());
						allNames.add(nextAddress.getPostalCodeElement());
						for (StringDt nextName : allNames) {
							addSearchTerm(theEntity, retVal, nextSpName, nextName.getValue());
						}
					} else if (nextObject instanceof ContactPointDt) {
						ContactPointDt nextContact = (ContactPointDt) nextObject;
						if (nextContact.getValueElement().isEmpty() == false) {
							addSearchTerm(theEntity, retVal, nextSpName, nextContact.getValue());
						}
					} else {
						if (!multiType) {
							throw new ConfigurationException("Search param " + nextSpName + " is of unexpected datatype: " + nextObject.getClass());
						}
					}
				}
			}
		}

		return retVal;
	}
247391
@Override
  public final void retrievePage(final Map<String, Object> pAddParam,
    final IRequestData pRequestData) throws Exception {
    this.isDbgSh = this.logger.getDbgSh(this.getClass())
        && this.logger.getDbgFl() < 7001 && this.logger.getDbgCl() > 7003;
    this.hlpEntitiesPage.retrievePage(pAddParam, pRequestData, this.entitiesMap,
      this.isDbgSh, this.filterFiMaker);
  }
1323819
protected <R> Predicate byMandatoryPredicate(CriteriaQuery<?> criteriaQuery, Root<E> root, CriteriaBuilder builder, E entity, SearchParameters sp) {
        return null;
    }
1189102
@SuppressWarnings("unchecked")
    @Override
    public Set<JsonEntityBean> search(String entityType, String searchTerm) {

        Set<JsonEntityBean> results = new HashSet<>();

        EntityEnum entityEnum = EntityEnum.getEntityEnum(entityType);
        if (entityEnum == null) {
            throw new IllegalArgumentException(
                    String.format("Parameter entityType has an unknown value of [%s]", entityType));
        }

        EntityIdentifier[] identifiers;

        Class identifierType;

        // if the entity type is a group, use the group service's findGroup method
        // to locate it
        if (entityEnum.isGroup()) {
            identifiers =
                    GroupService.searchForGroups(
                            searchTerm,
                            GroupService.SearchMethod.CONTAINS_CI,
                            entityEnum.getClazz());
            identifierType = IEntityGroup.class;
        }

        // otherwise use the getGroupMember method
        else {
            identifiers =
                    GroupService.searchForEntities(
                            searchTerm,
                            GroupService.SearchMethod.CONTAINS_CI,
                            entityEnum.getClazz());
            identifierType = entityEnum.getClazz();
        }

        for (int i = 0; i < identifiers.length; i++) {
            if (identifiers[i].getType().equals(identifierType)) {
                IGroupMember entity = GroupService.getGroupMember(identifiers[i]);
                if (entity != null) {
                    JsonEntityBean jsonBean = getEntity(entity);
                    results.add(jsonBean);
                } else {
                    log.warn("Grouper member entity of " + identifiers[i].getKey() + " is null.");
                }
            }
        }

        return results;
    }
399225
def get(self, *args, **kwargs):
        
        clone = self.filter(*args, **kwargs)

        if self.query.can_filter():
            clone = clone.order_by()

        num = len(clone)

        if num == 1:
            return clone._result_cache[0]
        if not num:
            raise self.resource.DoesNotExist(
                "%s matching query does not exist. "
                "Lookup parameters were %s" %
                (self.resource._meta.resource_name, kwargs))

        raise self.resource.MultipleObjectsReturned(
            "get() returned more than one %s -- it returned %s! "
            "Lookup parameters were %s" %
            (self.resource._meta.resource_name, num, kwargs))
485319
private <T> SearchResultsBean<T> find(SearchCriteriaBean criteria, String type,
            IUnmarshaller<T> unmarshaller) throws StorageException {
        try {
            SearchResultsBean<T> rval = new SearchResultsBean<>();

            // Set some default in the case that paging information was not included in the request.
            PagingBean paging = criteria.getPaging();
            if (paging == null) {
                paging = new PagingBean();
                paging.setPage(1);
                paging.setPageSize(20);
            }
            int page = paging.getPage();
            int pageSize = paging.getPageSize();
            int start = (page - 1) * pageSize;

            SearchSourceBuilder builder = new SearchSourceBuilder().size(pageSize).from(start).fetchSource(true);

            // Sort order
            OrderByBean orderBy = criteria.getOrderBy();
            if (orderBy != null) {
                String name = orderBy.getName();
                if (name.equals("name") || name.equals("fullName")) { //$NON-NLS-1$ //$NON-NLS-2$
                    name += ".raw"; //$NON-NLS-1$
                }
                if (orderBy.isAscending()) {
                    builder.sort(name, SortOrder.ASC);
                } else {
                    builder.sort(name, SortOrder.DESC);
                }
            }

            // Now process the filter criteria
            List<SearchCriteriaFilterBean> filters = criteria.getFilters();

            QueryBuilder q = null;

            if (filters != null && !filters.isEmpty()) {
                FilterBuilder andFilter = FilterBuilders.filter();
                int filterCount = 0;
                for (SearchCriteriaFilterBean filter : filters) {
                    String propertyName = filter.getName();
                    if (filter.getOperator() == SearchCriteriaFilterOperator.eq) {
                        andFilter.add(FilterBuilders.termFilter(propertyName, filter.getValue()));
                        filterCount++;
                    } else if (filter.getOperator() == SearchCriteriaFilterOperator.like) {
                        q = QueryBuilders.wildcardQuery(propertyName, filter.getValue().toLowerCase().replace('%', '*'));
                    } else if (filter.getOperator() == SearchCriteriaFilterOperator.bool_eq) {
                        andFilter.add(FilterBuilders.termFilter(propertyName, "true".equals(filter.getValue()))); //$NON-NLS-1$
                        filterCount++;
                    }
                    // TODO implement the other filter operators here!
                }

                if (filterCount > 0) {
                    q = FilterBuilders.boolFilter(andFilter);
                }
            }
            builder.query(q);

            String query = builder.string();
            Search search = new Search.Builder(query)
                    .addIndex(getIndexName())
                    .addType(type)
                    .build();
            SearchResult response = esClient.execute(search);
            @SuppressWarnings({ "unchecked", "rawtypes" })
            List<Hit<Map<String, Object>, Void>> thehits = (List) response.getHits(Map.class);

            rval.setTotalSize((int)(long)response.getTotal());
            for (Hit<Map<String,Object>,Void> hit : thehits) {
                Map<String, Object> sourceAsMap = hit.source;
                T bean = unmarshaller.unmarshal(sourceAsMap);
                rval.getBeans().add(bean);
            }
            return rval;
        } catch (Exception e) {
            throw new StorageException(e);
        }
    }
941642
@SuppressWarnings({ "unchecked", "rawtypes" })
	@Deprecated
	public <T, I extends Serializable> ResourceRepositoryStub<T, I> getQueryParamsRepository(Class<T> resourceClass) {
		init();

		RegistryEntry entry = resourceRegistry.findEntry(resourceClass);

		// TODO fix this in katharsis, should be able to get original resource
		ResourceRepositoryAdapter repositoryAdapter = entry.getResourceRepository(null);
		return (ResourceRepositoryStub<T, I>) repositoryAdapter.getResourceRepository();
	}
1221035
static <P extends ParaObject> Map<String, Object> buildQueryAndSearch(App app, String querytype,
			MultivaluedMap<String, String> params, String typeOverride) {
		String query = paramOrDefault(params, "q", "*");
		String appid = app.getAppIdentifier();
		Pager pager = getPagerFromParams(params);
		List<P> items = Collections.emptyList();
		String queryType = paramOrDefault(params, "querytype", querytype);
		String type = paramOrDefault(params, Config._TYPE, null);
		if (!StringUtils.isBlank(typeOverride) && !"search".equals(typeOverride)) {
			type = typeOverride;
		}
		try (final Metrics.Context context = Metrics.time(appid, RestUtils.class, "search", queryType)) {
			if (params == null) {
				return buildPageResponse(Para.getSearch().findQuery(appid, type, query, pager), pager);
			}

			if ("id".equals(queryType)) {
				items = findByIdQuery(params, appid, pager);
			} else if ("ids".equals(queryType)) {
				items = Para.getSearch().findByIds(appid, params.get("ids"));
				pager.setCount(items.size());
			} else if ("nested".equals(queryType)) {
				items = Para.getSearch().findNestedQuery(appid, type, params.getFirst("field"), query, pager);
			} else if ("nearby".equals(queryType)) {
				items = findNearbyQuery(params, appid, type, query, pager);
			} else if ("prefix".equals(queryType)) {
				items = Para.getSearch().findPrefix(appid, type, params.getFirst("field"), params.getFirst("prefix"), pager);
			} else if ("similar".equals(queryType)) {
				items = findSimilarQuery(params, appid, type, pager);
			} else if ("tagged".equals(queryType)) {
				items = findTaggedQuery(params, appid, type, pager);
			} else if ("in".equals(queryType)) {
				items = Para.getSearch().findTermInList(appid, type, params.getFirst("field"), params.get("terms"), pager);
			} else if ("terms".equals(queryType)) {
				items = findTermsQuery(params, pager, appid, type);
			} else if ("wildcard".equals(queryType)) {
				items = Para.getSearch().findWildcard(appid, type, params.getFirst("field"), query, pager);
			} else if ("count".equals(queryType)) {
				pager.setCount(Para.getSearch().getCount(appid, type));
			} else {
				items = Para.getSearch().findQuery(appid, type, query, pager);
			}
			return buildPageResponse(items, pager);
		}
	}
486627
@Override
	public Set<ResourceIndexedSearchParamDate> extractSearchParamDates(ResourceTable theEntity, IBaseResource theResource) {
		HashSet<ResourceIndexedSearchParamDate> retVal = new HashSet<>();

		Collection<RuntimeSearchParam> searchParams = getSearchParams(theResource);
		for (RuntimeSearchParam nextSpDef : searchParams) {
			if (nextSpDef.getParamType() != RestSearchParameterTypeEnum.DATE) {
				continue;
			}

			String nextPath = nextSpDef.getPath();
			if (isBlank(nextPath)) {
				continue;
			}

			boolean multiType = false;
			if (nextPath.endsWith("[x]")) {
				multiType = true;
			}

			for (Object nextObject : extractValues(nextPath, theResource)) {
				if (nextObject == null) {
					continue;
				}

				ResourceIndexedSearchParamDate nextEntity;
				if (nextObject instanceof BaseDateTimeType) {
					BaseDateTimeType nextValue = (BaseDateTimeType) nextObject;
					if (nextValue.isEmpty()) {
						continue;
					}
					nextEntity = new ResourceIndexedSearchParamDate(nextSpDef.getName(), nextValue.getValue(), nextValue.getValue(), nextValue.getValueAsString());
				} else if (nextObject instanceof Period) {
					Period nextValue = (Period) nextObject;
					if (nextValue.isEmpty()) {
						continue;
					}
					nextEntity = new ResourceIndexedSearchParamDate(nextSpDef.getName(), nextValue.getStart(), nextValue.getEnd(), nextValue.getStartElement().getValueAsString());
				} else if (nextObject instanceof Timing) {
					Timing nextValue = (Timing) nextObject;
					if (nextValue.isEmpty()) {
						continue;
					}
					TreeSet<Date> dates = new TreeSet<>();
					String firstValue = null;
					for (DateTimeType nextEvent : nextValue.getEvent()) {
						if (nextEvent.getValue() != null) {
							dates.add(nextEvent.getValue());
							if (firstValue == null) {
								firstValue = nextEvent.getValueAsString();
							}
						}
					}
					if (dates.isEmpty()) {
						continue;
					}

					nextEntity = new ResourceIndexedSearchParamDate(nextSpDef.getName(), dates.first(), dates.last(), firstValue);
				} else if (nextObject instanceof StringType) {
					// CarePlan.activitydate can be a string
					continue;
				} else {
					if (!multiType) {
						throw new ConfigurationException("Search param " + nextSpDef.getName() + " is of unexpected datatype: " + nextObject.getClass());
					} else {
						continue;
					}
				}
				if (nextEntity != null) {
					nextEntity.setResource(theEntity);
					retVal.add(nextEntity);
				}
			}
		}

		return retVal;
	}
1316768
private <L extends Collection<JQLPlaceHolder>> L extractPlaceHolders(final JQLContext jqlContext, String jql, final L result) {
		final One<Boolean> valid = new One<>();
		valid.value0 = false;

		analyzeInternal(jqlContext, jql, new JqlBaseListener() {

			@Override
			public void enterBind_parameter(Bind_parameterContext ctx) {
				String value;
				if (ctx.bind_parameter_name() != null) {
					value = ctx.bind_parameter_name().getText();
				} else {
					value = ctx.getText();
				}
				result.add(new JQLPlaceHolder(JQLPlaceHolderType.PARAMETER, value));
			}

			@Override
			public void enterBind_dynamic_sql(Bind_dynamic_sqlContext ctx) {
				result.add(new JQLPlaceHolder(JQLPlaceHolderType.DYNAMIC_SQL, ctx.bind_parameter_name().getText()));
			}

		});
		return result;
	}
1116162
@Transactional
    public E findUniqueOrNone(E entity, SearchParameters sp) {
        // this code is an optimization to prevent using a count
        sp.setFirst(0);
        sp.setMaxResults(2);
        List<E> results = find(entity, sp);

        if (results == null || results.isEmpty()) {
            return null;
        } else if (results.size() > 1) {
            throw new NonUniqueResultException("Developper: You expected 1 result but we found more ! sample: " + entity);
        } else {
            return results.iterator().next();
        }
    }
1012729
@Override
	public IResourceFactory getResourceFactory(Mutable<URI> uriRef) {
		final String sourceMethod = "getResourceFactory"; //$NON-NLS-1$
		boolean isTraceLogging = log.isLoggable(Level.FINER);
		if (isTraceLogging) {
			log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[]{uriRef});
		}
		IResourceFactory factory = null;
		URI uri = uriRef.getValue();
		if (!uri.isAbsolute()) {
			if (uri.getPath().startsWith("/")) { //$NON-NLS-1$
				// server relative URI not supported for server resources.  Probably meant
				// to refer to a web resource.
				if (isTraceLogging) {
					log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod, null);
				}
				return null;
			}
			// URI is not absolute, so make it absolute.
			try {
				uri = getPlatformServices().getAppContextURI().resolve(uri.getPath());
				if (isTraceLogging) {
					log.logp(Level.FINER, AbstractAggregatorImpl.class.getName(), sourceMethod,
							"URI " + uriRef.getValue().toString() + " transformed to " + uri.toString()); //$NON-NLS-1$ //$NON-NLS-2$
				}
			} catch (URISyntaxException e) {
				throw new IllegalArgumentException(e);
			}
		}

		Iterable<IAggregatorExtension> extensions = getExtensions(IResourceFactoryExtensionPoint.ID);
		if (extensions != null) {	// may be null when unit testing
			for (IAggregatorExtension extension : getExtensions(IResourceFactoryExtensionPoint.ID)) {
				if (uri.getScheme().equals(extension.getAttribute(IResourceFactoryExtensionPoint.SCHEME_ATTRIBUTE))) {
					IResourceFactory test = (IResourceFactory)extension.getInstance();
					if (test.handles(uri)) {
						factory = test;
						break;
					}
				}
			}
		}
		if (factory != null) {
			uriRef.setValue(uri);
		}
		if (isTraceLogging) {
			log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod, factory);
		}
		return factory;
	}
751466
func validateResourceQuantityValue(resource string, value resource.Quantity, fldPath *validation.FieldPath) validation.ErrorList {
	allErrs := validation.ErrorList{}
	allErrs = append(allErrs, ValidatePositiveQuantity(value, fldPath)...)
	if api.IsIntegerResourceName(resource) {
		if value.MilliValue()%int64(1000) != int64(0) {
			allErrs = append(allErrs, validation.NewInvalidError(fldPath, value, isNotIntegerErrorMsg))
		}
	}
	return allErrs
}
182213
@SuppressWarnings("unchecked")
    public <T> List<Serializable> findId(Class<T> clazz, SearchParameters sp, List<SingularAttribute<?, ?>> availableProperties) {
        //log.info("Searching {} with terms : {} with available Properties: {}", new Object[]{clazz.getSimpleName(), sp.getTerms(), availableProperties});
        FullTextEntityManager fullTextEntityManager = getFullTextEntityManager(entityManager);
        Query query = sp.getLuceneQueryBuilder().build(fullTextEntityManager, sp, availableProperties);

        if (query == null) {
            return null;
        }

        FullTextQuery ftq = fullTextEntityManager.createFullTextQuery( //
                query, clazz);
        ftq.setProjection("id");
        if (sp.getMaxResults() > 0) {
            ftq.setMaxResults(sp.getMaxResults());
        }
        List<Serializable> ids = newArrayList();
        List<Object[]> resultList = ftq.getResultList();
        for (Object[] result : resultList) {
            ids.add((Serializable) result[0]);
        }
        return ids;
    }
507338
public String extractResource(XEvent event) {
		XAttribute attribute = event.getAttributes().get(KEY_RESOURCE);
		if (attribute == null) {
			return null;
		} else {
			return ((XAttributeLiteral) attribute).getValue();
		}
	}