001/*-
002 * #%L
003 * HAPI FHIR JPA Server
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.term.custom;
021
022import ca.uhn.fhir.jpa.entity.TermConcept;
023import ca.uhn.fhir.jpa.entity.TermConceptParentChildLink;
024import ca.uhn.fhir.jpa.term.IZipContentsHandlerCsv;
025import ca.uhn.fhir.util.ValidateUtil;
026import org.apache.commons.csv.CSVRecord;
027
028import java.util.Map;
029
030import static org.apache.commons.lang3.StringUtils.isNotBlank;
031import static org.apache.commons.lang3.StringUtils.trim;
032
033public class HierarchyHandler implements IZipContentsHandlerCsv {
034
035        public static final String PARENT = "PARENT";
036        public static final String CHILD = "CHILD";
037        private final Map<String, TermConcept> myCode2Concept;
038
039        public HierarchyHandler(Map<String, TermConcept> theCode2concept) {
040                myCode2Concept = theCode2concept;
041        }
042
043        @Override
044        public void accept(CSVRecord theRecord) {
045                String parent = trim(theRecord.get(PARENT));
046                String child = trim(theRecord.get(CHILD));
047                if (isNotBlank(parent) && isNotBlank(child)) {
048
049                        TermConcept childConcept = myCode2Concept.get(child);
050                        ValidateUtil.isNotNullOrThrowUnprocessableEntity(childConcept, "Child code %s not found in file", child);
051
052                        TermConcept parentConcept = myCode2Concept.get(parent);
053                        ValidateUtil.isNotNullOrThrowUnprocessableEntity(parentConcept, "Parent code %s not found in file", child);
054
055                        parentConcept.addChild(childConcept, TermConceptParentChildLink.RelationshipTypeEnum.ISA);
056                }
057        }
058}