001/******************************************************************************* 002 * Crown Copyright (c) 2006 - 2014, Copyright (c) 2006 - 2014 Kestral Computing P/L. 003 * All rights reserved. This program and the accompanying materials 004 * are made available under the terms of the Eclipse Public License v1.0 005 * which accompanies this distribution, and is available at 006 * http://www.eclipse.org/legal/epl-v10.html 007 * 008 * Contributors: 009 * Kestral Computing P/L - initial implementation 010 *******************************************************************************/ 011 012package org.hl7.fhir.utilities.ucum; 013 014import java.util.ArrayList; 015import java.util.List; 016 017public class Search { 018 019 public List<Concept> doSearch(UcumModel model, ConceptKind kind, String text, boolean isRegex) { 020 List<Concept> concepts = new ArrayList<Concept>(); 021 if (kind == null || kind == ConceptKind.PREFIX) 022 searchPrefixes(concepts, model.getPrefixes(), text, isRegex); 023 if (kind == null || kind == ConceptKind.BASEUNIT) 024 searchUnits(concepts, model.getBaseUnits(), text, isRegex); 025 if (kind == null || kind == ConceptKind.UNIT) 026 searchUnits(concepts, model.getDefinedUnits(), text, isRegex); 027 return concepts; 028 } 029 030 private void searchUnits(List<Concept> concepts, List<? extends Unit> units, String text, boolean isRegex) { 031 for (Unit unit : units) { 032 if (matchesUnit(unit, text, isRegex)) 033 concepts.add(unit); 034 } 035 } 036 037 private boolean matchesUnit(Unit unit, String text, boolean isRegex) { 038 return matches(unit.getProperty(), text, isRegex) || matchesConcept(unit, text, isRegex); 039 } 040 041 private void searchPrefixes(List<Concept> concepts, List<? extends Prefix> prefixes, String text, boolean isRegex) { 042 for (Concept concept : prefixes) { 043 if (matchesConcept(concept, text, isRegex)) 044 concepts.add(concept); 045 } 046 } 047 048 private boolean matchesConcept(Concept concept, String text, boolean isRegex) { 049 for (String name : concept.getNames()) { 050 if (matches(name, text, isRegex)) 051 return true; 052 } 053 if (matches(concept.getCode(), text, isRegex)) 054 return true; 055 if (matches(concept.getCodeUC(), text, isRegex)) 056 return true; 057 if (matches(concept.getPrintSymbol(), text, isRegex)) 058 return true; 059 return false; 060 } 061 062 private boolean matches(String value, String text, boolean isRegex) { 063 return (value != null) && ((isRegex && value.matches(text)) || (!isRegex && value.toLowerCase().contains(text.toLowerCase()))); 064 } 065 066 067} 068