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