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