001package org.gbif.dwc.terms;
002
003import java.util.Map;
004import java.util.regex.Pattern;
005
006/**
007 * Utility methods for {@link Term}
008 *
009 */
010public class Terms {
011
012  private static final Pattern NULL_PATTERN = Pattern.compile("^\\s*(\\\\N|\\\\?NULL)\\s*$");
013
014  /**
015   * static utility class
016   */
017  private Terms() {
018  }
019
020  /**
021   * Tries various terms in given order until it finds a non empty value.
022   *
023   * @param record
024   * @param terms
025   * @return value or null
026   */
027  public static String getValueOfFirst(Map<Term, String> record, Term... terms) {
028    for (Term t : terms) {
029      if (record.containsKey(t)) {
030        String val = clean(record.get(t));
031        if (val != null) {
032          return val;
033        }
034      }
035    }
036    return null;
037  }
038
039  private static String clean(String str) {
040    if (isTermValueBlank(str)) {
041      return null;
042    }
043    str = str.trim();
044    if(str.isEmpty()){
045      return null;
046    }
047    return str;
048  }
049
050  /**
051   * Check if the value provided should be considered "blank" in the context of a {@link Term} value.
052   *
053   * @param termValue
054   * @return
055   */
056  public static boolean isTermValueBlank(String termValue){
057    return termValue == null || termValue.isEmpty() || NULL_PATTERN.matcher(termValue).find();
058  }
059}