001package org.hl7.fhir.utilities; 002 003import org.apache.commons.lang3.StringUtils; 004 005/** 006 * Abstraction that splits a canonical in form of {@code <url>|<version>} into a URL and a version part. 007 */ 008public class CanonicalPair { 009 010 private final String url; 011 private final String version; 012 013 /** 014 * Static factory method, that invokes the {@link CanonicalPair#CanonicalPair(String) CanonicalPair constructor} 015 * with the given argument. 016 * @param target the canonical to be split. May be {@code null}. 017 * @return new instance of CanonicalPair 018 */ 019 public static CanonicalPair of(String target) { 020 return new CanonicalPair(target); 021 } 022 023 /** 024 * Wraps the given canonical and if needed splits off the version part.<p> 025 * The given parameter {@code target} is expected to be a canonical. 026 * @param target canonical to create a url, version pair from. May be {@code null}. 027 */ 028 public CanonicalPair(String target) { 029 int pipeIndex = target != null ? target.indexOf('|') : -1; 030 if (pipeIndex >= 0) { 031 this.url = target.substring(0, pipeIndex); 032 this.version = target.substring(pipeIndex+1); 033 } else { 034 this.url = target; 035 this.version = null; 036 } 037 } 038 039 /** 040 * Returns the URL part of the canonical (everything before the {@code "|"} character, or the complete 041 * canonical if the character is not present). If the source 042 * @return URL part of the source canonical. May be {@code null}, if source canonical was {@code null} 043 */ 044 public String getUrl() { 045 return url; 046 } 047 048 /** 049 * Returns the version part of the source canonical (everything after the {@code "|"} character. 050 * @return version part of the canonical, may be {@code null}, if canonical was {@code null}, or canonical contains no 051 * {@code "|"} character. 052 */ 053 public String getVersion() { 054 return version; 055 } 056 057 /** 058 * Determines if the version part of the canonical is not {@code null} 059 * @return {@code true} if version is not {@code null}, otherwise {@code false} 060 */ 061 public boolean hasVersion() { 062 return version != null; 063 } 064 065 /** 066 * Returns the version of this pair, or the parameter {@code alternative}, 067 * if the version of this pair is {@code null}. 068 * @param alternative to be returned from this method if the encapsulated version is {@code null}. 069 * @return either the held version, or {@code alternative}, if version is {@code null} 070 */ 071 public String getVersionOr(String alternative) { 072 return hasVersion() ? version : alternative; 073 } 074 075 /** 076 * Determines if the encapsulated version of this pair is not {@code null} and not an empty string. 077 * @return {@code true} if the version of this pair is not {@code null} and not an empty string, {@code false} otherwise 078 */ 079 public boolean hasNonEmptyVersion() { 080 return StringUtils.isNotEmpty(version); 081 } 082}