001/*- 002 * #%L 003 * HAPI FHIR JPA - Search Parameters 004 * %% 005 * Copyright (C) 2014 - 2024 Smile CDR, Inc. 006 * %% 007 * Licensed under the Apache License, Version 2.0 (the "License"); 008 * you may not use this file except in compliance with the License. 009 * You may obtain a copy of the License at 010 * 011 * http://www.apache.org/licenses/LICENSE-2.0 012 * 013 * Unless required by applicable law or agreed to in writing, software 014 * distributed under the License is distributed on an "AS IS" BASIS, 015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 016 * See the License for the specific language governing permissions and 017 * limitations under the License. 018 * #L% 019 */ 020package ca.uhn.fhir.jpa.searchparam.util; 021 022import ca.uhn.fhir.context.RuntimeSearchParam; 023import ca.uhn.fhir.jpa.searchparam.SearchParameterMap; 024import ca.uhn.fhir.jpa.searchparam.registry.SearchParameterCanonicalizer; 025import ca.uhn.fhir.rest.param.TokenAndListParam; 026import ca.uhn.fhir.rest.param.TokenOrListParam; 027import ca.uhn.fhir.rest.param.TokenParam; 028import org.hl7.fhir.instance.model.api.IBaseResource; 029 030import java.util.List; 031import java.util.Optional; 032 033import static org.apache.commons.lang3.StringUtils.isNotBlank; 034 035public class SearchParameterHelper { 036 private final SearchParameterCanonicalizer mySearchParameterCanonicalizer; 037 038 public SearchParameterHelper(SearchParameterCanonicalizer theSearchParameterCanonicalizer) { 039 mySearchParameterCanonicalizer = theSearchParameterCanonicalizer; 040 } 041 042 public Optional<SearchParameterMap> buildSearchParameterMapFromCanonical(IBaseResource theRuntimeSearchParam) { 043 RuntimeSearchParam canonicalSearchParam = 044 mySearchParameterCanonicalizer.canonicalizeSearchParameter(theRuntimeSearchParam); 045 if (canonicalSearchParam == null) { 046 return Optional.empty(); 047 } 048 049 SearchParameterMap retVal = SearchParameterMap.newSynchronous(); 050 051 String theCode = canonicalSearchParam.getName(); 052 List<String> theBases = List.copyOf(canonicalSearchParam.getBase()); 053 054 TokenAndListParam codeParam = new TokenAndListParam().addAnd(new TokenParam(theCode)); 055 TokenAndListParam basesParam = toTokenAndList(theBases); 056 057 retVal.add("code", codeParam); 058 retVal.add("base", basesParam); 059 060 return Optional.of(retVal); 061 } 062 063 private TokenAndListParam toTokenAndList(List<String> theBases) { 064 TokenAndListParam retVal = new TokenAndListParam(); 065 066 if (theBases != null) { 067 068 TokenOrListParam tokenOrListParam = new TokenOrListParam(); 069 retVal.addAnd(tokenOrListParam); 070 071 for (String next : theBases) { 072 if (isNotBlank(next)) { 073 tokenOrListParam.addOr(new TokenParam(next)); 074 } 075 } 076 } 077 078 return retVal.getValuesAsQueryTokens().isEmpty() ? null : retVal; 079 } 080}