View Javadoc
1   package ca.uhn.fhir.jpa.dao.r4;
2   
3   /*
4    * #%L
5    * HAPI FHIR JPA Server
6    * %%
7    * Copyright (C) 2014 - 2019 University Health Network
8    * %%
9    * Licensed under the Apache License, Version 2.0 (the "License");
10   * you may not use this file except in compliance with the License.
11   * You may obtain a copy of the License at
12   * 
13   *      http://www.apache.org/licenses/LICENSE-2.0
14   * 
15   * Unless required by applicable law or agreed to in writing, software
16   * distributed under the License is distributed on an "AS IS" BASIS,
17   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18   * See the License for the specific language governing permissions and
19   * limitations under the License.
20   * #L%
21   */
22  
23  import ca.uhn.fhir.jpa.dao.IFhirResourceDaoCodeSystem;
24  import ca.uhn.fhir.jpa.searchparam.SearchParameterMap;
25  import ca.uhn.fhir.jpa.dao.data.ITermCodeSystemDao;
26  import ca.uhn.fhir.jpa.dao.data.ITermCodeSystemVersionDao;
27  import ca.uhn.fhir.jpa.model.entity.ResourceTable;
28  import ca.uhn.fhir.jpa.entity.TermCodeSystem;
29  import ca.uhn.fhir.jpa.entity.TermCodeSystemVersion;
30  import ca.uhn.fhir.jpa.entity.TermConcept;
31  import ca.uhn.fhir.jpa.entity.TermConceptParentChildLink.RelationshipTypeEnum;
32  import ca.uhn.fhir.jpa.util.LogicUtil;
33  import ca.uhn.fhir.rest.api.server.RequestDetails;
34  import ca.uhn.fhir.rest.param.TokenParam;
35  import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
36  import org.hl7.fhir.instance.model.api.IBaseResource;
37  import org.hl7.fhir.instance.model.api.IIdType;
38  import org.hl7.fhir.instance.model.api.IPrimitiveType;
39  import org.hl7.fhir.r4.hapi.ctx.IValidationSupport.CodeValidationResult;
40  import org.hl7.fhir.r4.hapi.validation.ValidationSupportChain;
41  import org.hl7.fhir.r4.model.CodeSystem;
42  import org.hl7.fhir.r4.model.CodeSystem.CodeSystemContentMode;
43  import org.hl7.fhir.r4.model.CodeSystem.ConceptDefinitionComponent;
44  import org.hl7.fhir.r4.model.CodeableConcept;
45  import org.hl7.fhir.r4.model.Coding;
46  import org.hl7.fhir.r4.model.IdType;
47  import org.springframework.beans.factory.annotation.Autowired;
48  
49  import java.util.ArrayList;
50  import java.util.Date;
51  import java.util.List;
52  import java.util.Set;
53  
54  import static org.apache.commons.lang3.StringUtils.isBlank;
55  import static org.apache.commons.lang3.StringUtils.isNotBlank;
56  
57  public class FhirResourceDaoCodeSystemR4 extends FhirResourceDaoR4<CodeSystem> implements IFhirResourceDaoCodeSystem<CodeSystem, Coding, CodeableConcept> {
58  
59  	private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(FhirResourceDaoCodeSystemR4.class);
60  
61  	@Autowired
62  	private ITermCodeSystemVersionDao myCsvDao;
63  	@Autowired
64  	private ITermCodeSystemDao myCsDao;
65  	@Autowired
66  	private ValidationSupportChain myValidationSupport;
67  
68  	@Override
69  	public List<IIdType> findCodeSystemIdsContainingSystemAndCode(String theCode, String theSystem) {
70  		List<IIdType> valueSetIds;
71  		Set<Long> ids = searchForIds(new SearchParameterMap(CodeSystem.SP_CODE, new TokenParam(theSystem, theCode)));
72  		valueSetIds = new ArrayList<>();
73  		for (Long next : ids) {
74  			valueSetIds.add(new IdType("CodeSystem", next));
75  		}
76  		return valueSetIds;
77  	}
78  
79  	@Override
80  	public LookupCodeResult lookupCode(IPrimitiveType<String> theCode, IPrimitiveType<String> theSystem, Coding theCoding, RequestDetails theRequestDetails) {
81  		boolean haveCoding = theCoding != null && isNotBlank(theCoding.getSystem()) && isNotBlank(theCoding.getCode());
82  		boolean haveCode = theCode != null && theCode.isEmpty() == false;
83  		boolean haveSystem = theSystem != null && theSystem.isEmpty() == false;
84  
85  		if (!haveCoding && !(haveSystem && haveCode)) {
86  			throw new InvalidRequestException("No code, coding, or codeableConcept provided to validate");
87  		}
88  		if (!LogicUtil.multiXor(haveCoding, (haveSystem && haveCode)) || (haveSystem != haveCode)) {
89  			throw new InvalidRequestException("$lookup can only validate (system AND code) OR (coding.system AND coding.code)");
90  		}
91  
92  		String code;
93  		String system;
94  		if (haveCoding) {
95  			code = theCoding.getCode();
96  			system = theCoding.getSystem();
97  		} else {
98  			code = theCode.getValue();
99  			system = theSystem.getValue();
100 		}
101 
102 		ourLog.info("Looking up {} / {}", system, code);
103 
104 		if (myValidationSupport.isCodeSystemSupported(getContext(), system)) {
105 
106 			ourLog.info("Code system {} is supported", system);
107 
108 			CodeValidationResult result = myValidationSupport.validateCode(getContext(), system, code, null);
109 			if (result != null) {
110 				if (result.isOk()) {
111 					LookupCodeResult retVal = new LookupCodeResult();
112 					retVal.setFound(true);
113 					retVal.setSearchedForCode(code);
114 					retVal.setSearchedForSystem(system);
115 					retVal.setCodeDisplay(result.asConceptDefinition().getDisplay());
116 
117 					String codeSystemDisplayName = result.getCodeSystemName();
118 					if (isBlank(codeSystemDisplayName)) {
119 						codeSystemDisplayName = "Unknown";
120 					}
121 
122 					retVal.setCodeSystemDisplayName(codeSystemDisplayName);
123 					retVal.setCodeSystemVersion(result.getCodeSystemVersion());
124 					retVal.setProperties(result.getProperties());
125 
126 					return retVal;
127 				}
128 			}
129 
130 		}
131 
132 		// We didn't find it..
133 		LookupCodeResult retVal = new LookupCodeResult();
134 		retVal.setFound(false);
135 		retVal.setSearchedForCode(code);
136 		retVal.setSearchedForSystem(system);
137 		return retVal;
138 
139 	}
140 
141 	@Override
142 	protected void preDelete(CodeSystem theResourceToDelete, ResourceTable theEntityToDelete) {
143 		super.preDelete(theResourceToDelete, theEntityToDelete);
144 
145 		String codeSystemUrl = theResourceToDelete.getUrl();
146 		if (isNotBlank(codeSystemUrl)) {
147 			TermCodeSystem persCs = myCsDao.findByCodeSystemUri(codeSystemUrl);
148 			if (persCs != null) {
149 				myTerminologySvc.deleteCodeSystem(persCs);
150 			}
151 		}
152 	}
153 
154 	private List<TermConcept> toPersistedConcepts(List<ConceptDefinitionComponent> theConcept, TermCodeSystemVersion theCodeSystemVersion) {
155 		ArrayList<TermConcept> retVal = new ArrayList<>();
156 
157 		for (ConceptDefinitionComponent next : theConcept) {
158 			if (isNotBlank(next.getCode())) {
159 				TermConcept termConcept = new TermConcept();
160 				termConcept.setCode(next.getCode());
161 				termConcept.setCodeSystemVersion(theCodeSystemVersion);
162 				termConcept.setDisplay(next.getDisplay());
163 				termConcept.addChildren(toPersistedConcepts(next.getConcept(), theCodeSystemVersion), RelationshipTypeEnum.ISA);
164 				retVal.add(termConcept);
165 			}
166 		}
167 
168 		return retVal;
169 	}
170 
171 	@Override
172 	protected ResourceTable updateEntity(RequestDetails theRequest, IBaseResource theResource, ResourceTable theEntity, Date theDeletedTimestampOrNull, boolean thePerformIndexing,
173 													 boolean theUpdateVersion, Date theUpdateTime, boolean theForceUpdate, boolean theCreateNewHistoryEntry) {
174 		ResourceTable retVal = super.updateEntity(theRequest, theResource, theEntity, theDeletedTimestampOrNull, thePerformIndexing, theUpdateVersion, theUpdateTime, theForceUpdate, theCreateNewHistoryEntry);
175 
176 		CodeSystem cs = (CodeSystem) theResource;
177 
178 		if (cs != null && isNotBlank(cs.getUrl())) {
179 			String codeSystemUrl = cs.getUrl();
180 			if (cs.getContent() == CodeSystemContentMode.COMPLETE || cs.getContent() == null) {
181 				ourLog.info("CodeSystem {} has a status of {}, going to store concepts in terminology tables", retVal.getIdDt().getValue(), cs.getContentElement().getValueAsString());
182 
183 				Long codeSystemResourcePid = retVal.getId();
184 				TermCodeSystemVersion persCs = myCsvDao.findCurrentVersionForCodeSystemResourcePid(codeSystemResourcePid);
185 				if (persCs != null) {
186 					ourLog.info("Code system version already exists in database");
187 				} else {
188 
189 					persCs = new TermCodeSystemVersion();
190 					persCs.setResource(retVal);
191 					persCs.getConcepts().addAll(toPersistedConcepts(cs.getConcept(), persCs));
192 					ourLog.info("Code system has {} concepts", persCs.getConcepts().size());
193 					myTerminologySvc.storeNewCodeSystemVersion(codeSystemResourcePid, codeSystemUrl, cs.getName(), persCs);
194 
195 				}
196 
197 			}
198 		}
199 
200 		return retVal;
201 	}
202 
203 }