001package ca.uhn.fhir.jpa.term.custom;
002
003/*-
004 * #%L
005 * HAPI FHIR JPA Server
006 * %%
007 * Copyright (C) 2014 - 2021 Smile CDR, Inc.
008 * %%
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 *
013 *      http://www.apache.org/licenses/LICENSE-2.0
014 *
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 * #L%
021 */
022
023import ca.uhn.fhir.jpa.entity.TermConcept;
024import ca.uhn.fhir.jpa.entity.TermConceptParentChildLink;
025import ca.uhn.fhir.jpa.term.IZipContentsHandlerCsv;
026import ca.uhn.fhir.util.ValidateUtil;
027import org.apache.commons.csv.CSVRecord;
028
029import java.util.Map;
030
031import static org.apache.commons.lang3.StringUtils.isNotBlank;
032import static org.apache.commons.lang3.StringUtils.trim;
033
034public class HierarchyHandler implements IZipContentsHandlerCsv {
035
036        public static final String PARENT = "PARENT";
037        public static final String CHILD = "CHILD";
038        private final Map<String, TermConcept> myCode2Concept;
039
040        public HierarchyHandler(Map<String, TermConcept> theCode2concept) {
041                myCode2Concept = theCode2concept;
042        }
043
044        @Override
045        public void accept(CSVRecord theRecord) {
046                String parent = trim(theRecord.get(PARENT));
047                String child = trim(theRecord.get(CHILD));
048                if (isNotBlank(parent) && isNotBlank(child)) {
049
050                        TermConcept childConcept = myCode2Concept.get(child);
051                        ValidateUtil.isNotNullOrThrowUnprocessableEntity(childConcept, "Child code %s not found in file", child);
052
053                        TermConcept parentConcept = myCode2Concept.get(parent);
054                        ValidateUtil.isNotNullOrThrowUnprocessableEntity(parentConcept, "Parent code %s not found in file", child);
055
056                        parentConcept.addChild(childConcept, TermConceptParentChildLink.RelationshipTypeEnum.ISA);
057                }
058        }
059}