001package org.hl7.fhir.utilities; 002 003import static org.apache.commons.lang3.StringUtils.isBlank; 004 005import java.io.BufferedInputStream; 006import java.io.File; 007import java.io.IOException; 008import java.io.InputStream; 009import java.io.UnsupportedEncodingException; 010import java.math.BigDecimal; 011import java.math.RoundingMode; 012import java.net.URI; 013import java.net.URLDecoder; 014import java.net.URLEncoder; 015import java.nio.charset.StandardCharsets; 016import java.time.Duration; 017import java.util.*; 018import java.util.regex.Matcher; 019import java.util.regex.Pattern; 020 021import javax.annotation.Nullable; 022 023import org.hl7.fhir.exceptions.FHIRException; 024import org.hl7.fhir.utilities.filesystem.ManagedFileAccess; 025import org.hl7.fhir.utilities.settings.FhirSettings; 026 027public class Utilities { 028 029 static final String C_TEMP_DIR = "c:\\temp"; 030 031 /** 032 * Returns the plural form of the word in the string. 033 * <p> 034 * Examples: 035 * 036 * <pre> 037 * inflector.pluralize("post") #=> "posts" 038 * inflector.pluralize("octopus") #=> "octopi" 039 * inflector.pluralize("sheep") #=> "sheep" 040 * inflector.pluralize("words") #=> "words" 041 * inflector.pluralize("the blue mailman") #=> "the blue mailmen" 042 * inflector.pluralize("CamelOctopus") #=> "CamelOctopi" 043 * </pre> 044 * <p> 045 * <p> 046 * <p> 047 * Note that if the {@link Object#toString()} is called on the supplied object, so this method works for non-strings, too. 048 * 049 * @param word the word that is to be pluralized. 050 * @return the pluralized form of the word, or the word itself if it could not be pluralized 051 * @see Inflector#singularize(Object) 052 */ 053 public static String pluralizeMe(String word) { 054 Inflector inf = new Inflector(); 055 return inf.pluralize(word); 056 } 057 058 public static String pluralize(String word, int count) { 059 if (count == 1) 060 return word; 061 Inflector inf = new Inflector(); 062 return inf.pluralize(word); 063 } 064 065 public static String singularise(String word) { 066 Inflector inf = new Inflector(); 067 return inf.singularize(word); 068 } 069 070 071 public static boolean isInteger(String string) { 072 if (isBlank(string)) { 073 return false; 074 } 075 String value = string.startsWith("-") ? string.substring(1) : string; 076 if (Utilities.noString(value)) { 077 return false; 078 } 079 for (char next : value.toCharArray()) { 080 if (!Character.isDigit(next)) { 081 return false; 082 } 083 } 084 // check bounds -2,147,483,648..2,147,483,647 085 if (value.length() > 10) 086 return false; 087 if (string.startsWith("-")) { 088 if (value.length() == 10 && string.compareTo("2147483648") > 0) 089 return false; 090 } else { 091 if (value.length() == 10 && string.compareTo("2147483647") > 0) 092 return false; 093 } 094 return true; 095 } 096 097 public static boolean isLong(String string) { 098 if (isBlank(string)) { 099 return false; 100 } 101 String value = string.startsWith("-") ? string.substring(1) : string; 102 for (char next : value.toCharArray()) { 103 if (!Character.isDigit(next)) { 104 return false; 105 } 106 } 107 // check bounds -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 108 if (value.length() > 20) 109 return false; 110 if (string.startsWith("-")) { 111 if (value.length() == 20 && string.compareTo("9223372036854775808") > 0) 112 return false; 113 } else { 114 if (value.length() == 20 && string.compareTo("9223372036854775807") > 0) 115 return false; 116 } 117 return true; 118 } 119 120 public static boolean isHex(String string) { 121 try { 122 int i = Integer.parseInt(string, 16); 123 return i != i + 1; 124 } catch (Exception e) { 125 return false; 126 } 127 } 128 129 public static boolean isValidId(String id) { 130 return id.matches("[A-Za-z0-9\\-\\.]{1,64}"); 131 } 132 133 public enum DecimalStatus { 134 BLANK, SYNTAX, RANGE, OK 135 } 136 137 public static boolean isDecimal(String value, boolean allowExponent, boolean allowLeadingZero) { 138 DecimalStatus ds = checkDecimal(value, allowExponent, true); 139 return ds == DecimalStatus.OK || ds == DecimalStatus.RANGE; 140 } 141 142 public static boolean isDecimal(String value, boolean allowExponent) { 143 DecimalStatus ds = checkDecimal(value, allowExponent, false); 144 return ds == DecimalStatus.OK || ds == DecimalStatus.RANGE; 145 } 146 147 public static DecimalStatus checkDecimal(String value, boolean allowExponent, boolean allowLeadingZero) { 148 if (isBlank(value)) { 149 return DecimalStatus.BLANK; 150 } 151 152 // check for leading zeros 153 if (!allowLeadingZero) { 154 if (value.startsWith("0") && !"0".equals(value) && !value.startsWith("0.")) 155 return DecimalStatus.SYNTAX; 156 if (value.startsWith("-0") && !"-0".equals(value) && !value.startsWith("-0.")) 157 return DecimalStatus.SYNTAX; 158 if (value.startsWith("+0") && !"+0".equals(value) && !value.startsWith("+0.")) 159 return DecimalStatus.SYNTAX; 160 } 161 162 // check for trailing dot 163 if (value.endsWith(".")) { 164 return DecimalStatus.SYNTAX; 165 } 166 167 boolean havePeriod = false; 168 boolean haveExponent = false; 169 boolean haveSign = false; 170 boolean haveDigits = false; 171 int preDecLength = 0; 172 int postDecLength = 0; 173 int exponentLength = 0; 174 int length = 0; 175 for (char next : value.toCharArray()) { 176 if (next == '.') { 177 if (!haveDigits || havePeriod || haveExponent) 178 return DecimalStatus.SYNTAX; 179 havePeriod = true; 180 preDecLength = length; 181 length = 0; 182 } else if (next == '-' || next == '+') { 183 if (haveDigits || haveSign) 184 return DecimalStatus.SYNTAX; 185 haveSign = true; 186 } else if (next == 'e' || next == 'E') { 187 if (!haveDigits || haveExponent || !allowExponent) 188 return DecimalStatus.SYNTAX; 189 haveExponent = true; 190 haveSign = false; 191 haveDigits = false; 192 if (havePeriod) 193 postDecLength = length; 194 else 195 preDecLength = length; 196 length = 0; 197 } else if (!Character.isDigit(next)) { 198 return DecimalStatus.SYNTAX; 199 } else { 200 haveDigits = true; 201 length++; 202 } 203 } 204 if (haveExponent && !haveDigits) 205 return DecimalStatus.SYNTAX; 206 if (haveExponent) 207 exponentLength = length; 208 else if (havePeriod) 209 postDecLength = length; 210 else 211 preDecLength = length; 212 213 // now, bounds checking - these are arbitrary 214 if (exponentLength > 4) 215 return DecimalStatus.RANGE; 216 if (preDecLength + postDecLength > 18) 217 return DecimalStatus.RANGE; 218 219 return DecimalStatus.OK; 220 } 221 222 public static String camelCase(String value) { 223 return new Inflector().camelCase(value.trim().replace(" ", "_"), false); 224 } 225 226 public static String upperCamelCase(String value) { 227 return new Inflector().upperCamelCase(value.trim().replace(" ", "_")); 228 } 229 230 public static String escapeXml(String doco) { 231 if (doco == null) 232 return ""; 233 234 StringBuilder b = new StringBuilder(); 235 for (char c : doco.toCharArray()) { 236 if (c == '<') 237 b.append("<"); 238 else if (c == '>') 239 b.append(">"); 240 else if (c == '&') 241 b.append("&"); 242 else if (c == '"') 243 b.append("""); 244 else 245 b.append(c); 246 } 247 return b.toString(); 248 } 249 250 public static String titleize(String s) { 251 StringBuilder b = new StringBuilder(); 252 boolean up = true; 253 for (char c : s.toCharArray()) { 254 if (up) 255 b.append(Character.toUpperCase(c)); 256 else 257 b.append(c); 258 up = c == ' '; 259 } 260 return b.toString(); 261 } 262 263 public static String capitalize(String s) { 264 if (s == null) return null; 265 if (s.length() == 0) return s; 266 if (s.length() == 1) return s.toUpperCase(); 267 268 return s.substring(0, 1).toUpperCase() + s.substring(1); 269 } 270 271 272 public static String asCSV(List<String> strings) { 273 StringBuilder s = new StringBuilder(); 274 boolean first = true; 275 for (String n : strings) { 276 if (!first) 277 s.append(","); 278 s.append(n); 279 first = false; 280 } 281 return s.toString(); 282 } 283 284 public static String asHtmlBr(String prefix, List<String> strings) { 285 StringBuilder s = new StringBuilder(); 286 boolean first = true; 287 for (String n : strings) { 288 if (!first) 289 s.append("<br/>"); 290 s.append(prefix); 291 s.append(n); 292 first = false; 293 } 294 return s.toString(); 295 } 296 297 public static String generateUniqueRandomUUIDPath(String path) throws IOException { 298 String randomUUIDPath = null; 299 300 while (randomUUIDPath == null) { 301 final String uuid = UUID.randomUUID().toString().toLowerCase(); 302 final String pathCandidate = Utilities.path(path, uuid); 303 304 if (!ManagedFileAccess.file(pathCandidate).exists()) { 305 randomUUIDPath = pathCandidate; 306 } 307 } 308 309 return randomUUIDPath; 310 } 311 312 public static String cleanupTextString(String contents) { 313 if (contents == null || contents.trim().equals("")) 314 return null; 315 else 316 return contents.trim(); 317 } 318 319 public static boolean noString(String v) { 320 return v == null || v.equals(""); 321 } 322 323 public static String appendSlash(String definitions) { 324 return definitions.endsWith(File.separator) ? definitions : definitions + File.separator; 325 } 326 327 public static String appendForwardSlash(String definitions) { 328 if (definitions == null) { 329 return "/"; 330 } 331 return definitions.endsWith("/") ? definitions : definitions + "/"; 332 } 333 334 public static String systemEol() { 335 return System.getProperty("line.separator"); 336 } 337 338 public static String normaliseEolns(String value) { 339 return value.replace("\r\n", "\r").replace("\n", "\r").replace("\r", "\r\n"); 340 } 341 342 public static String unescapeXml(String xml) throws FHIRException { 343 if (xml == null) 344 return null; 345 346 StringBuilder b = new StringBuilder(); 347 int i = 0; 348 while (i < xml.length()) { 349 if (xml.charAt(i) == '&') { 350 StringBuilder e = new StringBuilder(); 351 i++; 352 while (xml.charAt(i) != ';') { 353 e.append(xml.charAt(i)); 354 i++; 355 } 356 if (e.toString().equals("lt")) 357 b.append("<"); 358 else if (e.toString().equals("gt")) 359 b.append(">"); 360 else if (e.toString().equals("amp")) 361 b.append("&"); 362 else if (e.toString().equals("quot")) 363 b.append("\""); 364 else if (e.toString().equals("mu")) 365 b.append((char) 956); 366 else 367 throw new FHIRException("unknown XML entity \"" + e.toString() + "\""); 368 } else 369 b.append(xml.charAt(i)); 370 i++; 371 } 372 return b.toString(); 373 } 374 375 376 377 public static String unescapeJson(String json) throws FHIRException { 378 if (json == null) 379 return null; 380 381 StringBuilder b = new StringBuilder(); 382 int i = 0; 383 while (i < json.length()) { 384 if (json.charAt(i) == '\\') { 385 i++; 386 char ch = json.charAt(i); 387 switch (ch) { 388 case '"': 389 b.append('b'); 390 break; 391 case '\\': 392 b.append('\\'); 393 break; 394 case '/': 395 b.append('/'); 396 break; 397 case 'b': 398 b.append('\b'); 399 break; 400 case 'f': 401 b.append('\f'); 402 break; 403 case 'n': 404 b.append('\n'); 405 break; 406 case 'r': 407 b.append('\r'); 408 break; 409 case 't': 410 b.append('\t'); 411 break; 412 case 'u': 413 String hex = json.substring(i + 1, i + 5); 414 b.append(Character.toString(Integer.parseInt(hex, 16))); 415 break; 416 default: 417 throw new FHIRException("Unknown JSON escape \\" + ch); 418 } 419 } else 420 b.append(json.charAt(i)); 421 i++; 422 } 423 return b.toString(); 424 } 425 426 427 public static boolean isPlural(String word) { 428 word = word.toLowerCase(); 429 if ("restricts".equals(word) || "contains".equals(word) || "data".equals(word) || "specimen".equals(word) || "replaces".equals(word) || "addresses".equals(word) 430 || "supplementalData".equals(word) || "instantiates".equals(word) || "imports".equals(word) || "covers".equals(word)) 431 return false; 432 Inflector inf = new Inflector(); 433 return !inf.singularize(word).equals(word); 434 } 435 436 437 public static String padRight(String src, char c, int len) { 438 StringBuilder s = new StringBuilder(); 439 if (src != null) { 440 s.append(src); 441 for (int i = 0; i < len - src.length(); i++) 442 s.append(c); 443 } 444 return s.toString(); 445 } 446 447 public static String padRight(int num, char c, int len) { 448 return padRight(Integer.toString(num), c, len); 449 } 450 451 452 public static String padLeft(String src, char c, int len) { 453 StringBuilder s = new StringBuilder(); 454 for (int i = 0; i < len - src.length(); i++) 455 s.append(c); 456 s.append(src); 457 return s.toString(); 458 } 459 460 /** 461 * Composes a path string using by concatenating the passed arguments. 462 * 463 * This method enables all checks for unintended path locations. 464 * 465 * @param args 466 * @return 467 * @throws IOException 468 * @see PathBuilder#buildPath(String...) 469 */ 470 public static String path(String... args) throws IOException { 471 return PathBuilder.getPathBuilder().buildPath(args); 472 } 473 474 public static File pathFile(String... args) throws IOException { 475 return ManagedFileAccess.file(PathBuilder.getPathBuilder().buildPath(args)); 476 } 477 478 public static String path(File f, String... args) throws IOException { 479 String[] a = new String[args.length+1]; 480 a[0] = f.getAbsolutePath(); 481 for (int i = 0; i < args.length; i++) { 482 a[i+1] = args[i]; 483 } 484 return PathBuilder.getPathBuilder().buildPath(a); 485 } 486 487 public static String forcePath(String... args) throws IOException { 488 String path = path(args); 489 String folder = FileUtilities.getDirectoryForFile(path); 490 FileUtilities.createDirectory(folder); 491 return path; 492 } 493 494 /** 495 * Composes a path string using by concatenating the passed arguments. 496 * 497 * This method does not check for unintentional access to areas of the file 498 * system outside of the first entry. ONLY USE THIS METHOD IN CASES WHERE YOU 499 * ARE CERTAIN THE COMPOSED PATH IS NOT MALICIOUS. 500 * 501 * @param args 502 * @return 503 * @throws IOException 504 * 505 * @see PathBuilder#buildPath(String...) 506 */ 507 @Deprecated 508 public static String uncheckedPath(String... args) throws IOException { 509 return PathBuilder.getPathBuilder() 510 .withRequireNonRootFirstEntry(false) 511 .withRequireNonNullNonEmptyFirstEntry(false) 512 .withRequirePathIsChildOfTarget(false) 513 .buildPath(args); 514 } 515 516 517 public static String pathURL(String... args) { 518 StringBuilder s = new StringBuilder(); 519 boolean d = false; 520 for (String arg : args) { 521 if (arg != null) { 522 if (!d) 523 d = !noString(arg); 524 else if (s.toString() != null && !s.toString().endsWith("/") && !arg.startsWith("/") && !arg.startsWith("?") && !arg.startsWith("&")) 525 s.append("/"); 526 s.append(arg); 527 } 528 } 529 return s.toString(); 530 } 531 532 public static String nmtokenize(String cs) { 533 if (cs == null) 534 return ""; 535 StringBuilder s = new StringBuilder(); 536 for (int i = 0; i < cs.length(); i++) { 537 char c = cs.charAt(i); 538 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_') 539 s.append(c); 540 else if (c != ' ') 541 s.append("." + Integer.toString(c)); 542 } 543 return s.toString(); 544 } 545 546 public static String javaTokenize(String cs, boolean capFirst) { 547 if (cs == null) 548 return ""; 549 StringBuilder s = new StringBuilder(); 550 boolean upcase = capFirst; 551 for (int i = 0; i < cs.length(); i++) { 552 char c = cs.charAt(i); 553 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_') { 554 if (upcase) { 555 s.append(Character.toUpperCase(c)); 556 upcase = false; 557 } else { 558 s.append(c); 559 } 560 } else { 561 upcase = true; 562 } 563 } 564 String res = s.toString(); 565 if (isJavaReservedWord(res)) { 566 return "_"+res; 567 } else { 568 return res; 569 } 570 } 571 572 public static boolean isJavaReservedWord(String word) { 573 if (word.equals("abstract")) return true; 574 if (word.equals("assert")) return true; 575 if (word.equals("boolean")) return true; 576 if (word.equals("break")) return true; 577 if (word.equals("byte")) return true; 578 if (word.equals("case")) return true; 579 if (word.equals("catch")) return true; 580 if (word.equals("char")) return true; 581 if (word.equals("class")) return true; 582 if (word.equals("const")) return true; 583 if (word.equals("continue")) return true; 584 if (word.equals("default")) return true; 585 if (word.equals("double")) return true; 586 if (word.equals("do")) return true; 587 if (word.equals("else")) return true; 588 if (word.equals("enum")) return true; 589 if (word.equals("extends")) return true; 590 if (word.equals("false")) return true; 591 if (word.equals("final")) return true; 592 if (word.equals("finally")) return true; 593 if (word.equals("float")) return true; 594 if (word.equals("for")) return true; 595 if (word.equals("goto")) return true; 596 if (word.equals("if")) return true; 597 if (word.equals("implements")) return true; 598 if (word.equals("import")) return true; 599 if (word.equals("instanceof")) return true; 600 if (word.equals("int")) return true; 601 if (word.equals("interface")) return true; 602 if (word.equals("long")) return true; 603 if (word.equals("native")) return true; 604 if (word.equals("new")) return true; 605 if (word.equals("null")) return true; 606 if (word.equals("package")) return true; 607 if (word.equals("private")) return true; 608 if (word.equals("protected")) return true; 609 if (word.equals("public")) return true; 610 if (word.equals("return")) return true; 611 if (word.equals("short")) return true; 612 if (word.equals("static")) return true; 613 if (word.equals("strictfp")) return true; 614 if (word.equals("super")) return true; 615 if (word.equals("switch")) return true; 616 if (word.equals("synchronized")) return true; 617 if (word.equals("this")) return true; 618 if (word.equals("throw")) return true; 619 if (word.equals("throws")) return true; 620 if (word.equals("transient")) return true; 621 if (word.equals("true")) return true; 622 if (word.equals("try")) return true; 623 if (word.equals("void")) return true; 624 if (word.equals("volatile")) return true; 625 if (word.equals("while")) return true; 626 if (word.equals("Exception")) return true; 627 return false; 628 } 629 public static boolean isToken(String tail) { 630 if (tail == null || tail.length() == 0) 631 return false; 632 boolean result = isAlphabetic(tail.charAt(0)); 633 for (int i = 1; i < tail.length(); i++) { 634 result = result && (isAlphabetic(tail.charAt(i)) || isDigit(tail.charAt(i)) || (tail.charAt(i) == '_') || (tail.charAt(i) == '[') || (tail.charAt(i) == ']')); 635 } 636 return result; 637 } 638 639 public static boolean isTokenChar(char ch) { 640 return isAlphabetic(ch) || (ch == '_'); 641 } 642 643 public static boolean isDigit(char c) { 644 return (c >= '0') && (c <= '9'); 645 } 646 647 648 public static boolean isAlphabetic(char c) { 649 return ((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')); 650 } 651 652 public static String appendPeriod(String s) { 653 if (Utilities.noString(s)) 654 return s; 655 s = s.trim(); 656 if (s.endsWith(".") || s.endsWith("?")) 657 return s; 658 return s + "."; 659 } 660 661 662 public static String removePeriod(String s) { 663 if (Utilities.noString(s)) 664 return s; 665 if (s.endsWith(".")) 666 return s.substring(0, s.length() - 1); 667 return s; 668 } 669 670 671 public static String stripBOM(String string) { 672 return string == null ? null : string.replace("\uFEFF", ""); 673 } 674 675 676 public static String escapeJava(String doco) { 677 if (doco == null) 678 return ""; 679 680 StringBuilder b = new StringBuilder(); 681 for (char c : doco.toCharArray()) { 682 if (c == '\r') 683 b.append("\\r"); 684 else if (c == '\n') 685 b.append("\\n"); 686 else if (c == '"') 687 b.append("\\\""); 688 else if (c == '\\') 689 b.append("\\\\"); 690 else 691 b.append(c); 692 } 693 return b.toString(); 694 } 695 696 697 public static String[] splitByCamelCase(String name) { 698 List<String> parts = new ArrayList<String>(); 699 StringBuilder b = new StringBuilder(); 700 for (int i = 0; i < name.length(); i++) { 701 if (i > 0 && Character.isUpperCase(name.charAt(i))) { 702 parts.add(b.toString()); 703 b = new StringBuilder(); 704 } 705 b.append(Character.toLowerCase(name.charAt(i))); 706 } 707 parts.add(b.toString()); 708 return parts.toArray(new String[]{}); 709 } 710 711 @Deprecated 712 public static String encodeUri(String string) { 713 return encodeUriParam(string); 714 } 715 716 public static String encodeUriParam(String param) { 717 return URLEncoder.encode(param, StandardCharsets.UTF_8); 718 } 719 720 public static String normalize(String s) { 721 return normalize(s, true); 722 } 723 public static String normalize(String s, boolean lower) { 724 if (noString(s)) 725 return null; 726 StringBuilder b = new StringBuilder(); 727 boolean isWhitespace = false; 728 for (int i = 0; i < s.length(); i++) { 729 char c = s.charAt(i); 730 if (!isWhitespace(c)) { 731 b.append(lower ? Character.toLowerCase(c) : c); 732 isWhitespace = false; 733 } else if (!isWhitespace) { 734 if (c == '\r' || c == '\n') { 735 b.append('\n'); 736 } else { 737 b.append(' '); 738 } 739 isWhitespace = true; 740 } 741 } 742 return b.toString().trim(); 743 } 744 745 public static String normalizeSameCase(String s) { 746 if (noString(s)) 747 return null; 748 StringBuilder b = new StringBuilder(); 749 boolean isWhitespace = false; 750 for (int i = 0; i < s.length(); i++) { 751 char c = s.charAt(i); 752 if (!Character.isWhitespace(c)) { 753 b.append(c); 754 isWhitespace = false; 755 } else if (!isWhitespace) { 756 b.append(' '); 757 isWhitespace = true; 758 } 759 } 760 return b.toString().trim(); 761 } 762 763 public static String URLEncode(String string) { 764 try { 765 return URLEncoder.encode(string, "UTF-8"); 766 } catch (UnsupportedEncodingException e) { 767 throw new Error(e.getMessage()); 768 } 769 } 770 771 772 public static String URLDecode(String ref) { 773 try { 774 return URLDecoder.decode(ref, "UTF-8"); 775 } catch (UnsupportedEncodingException e) { 776 throw new Error(e.getMessage()); 777 } 778 } 779 780 public static boolean charInSet(char value, char... array) { 781 for (int i : array) 782 if (value == i) 783 return true; 784 return false; 785 } 786 787 788 public static boolean charInRange(char ch, char a, char z) { 789 return ch >= a && ch <= z; 790 } 791 792 public static boolean existsInList(String value, List<String> array) { 793 if (value == null) 794 return false; 795 for (String s : array) 796 if (value.equals(s)) 797 return true; 798 return false; 799 } 800 801 public static boolean containsInList(String value, String... array) { 802 if (value == null) 803 return false; 804 for (String s : array) 805 if (value.contains(s)) 806 return true; 807 return false; 808 } 809 810 public static boolean existsInList(String value, String... array) { 811 if (value == null) 812 return false; 813 for (String s : array) 814 if (value.equals(s)) 815 return true; 816 return false; 817 } 818 819 public static boolean existsInListTrimmed(String value, String... array) { 820 if (value == null) 821 return false; 822 for (String s : array) 823 if (value.equals(s.trim())) 824 return true; 825 return false; 826 } 827 828 public static boolean existsInList(int value, int... array) { 829 for (int i : array) 830 if (value == i) 831 return true; 832 return false; 833 } 834 835 public static boolean existsInListNC(String value, String... array) { 836 for (String s : array) 837 if (value.equalsIgnoreCase(s)) 838 return true; 839 return false; 840 } 841 842 public static String stringJoin(String sep, String... array) { 843 CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder(sep); 844 for (String s : array) 845 if (!noString(s)) 846 b.append(s); 847 return b.toString(); 848 } 849 850 851 public static String getFileNameForName(String name) { 852 return name.toLowerCase(); 853 } 854 855 public static boolean isAsciiChar(char ch) { 856 return ch >= ' ' && ch <= '~'; 857 } 858 859 860 public static boolean isURL(String s) { 861 boolean ok = s.matches("^http(s{0,1})://[a-zA-Z0-9_/\\-\\.]+\\.([A-Za-z/]{2,5})[a-zA-Z0-9_/\\&\\?\\=\\-\\.\\~\\%]*"); 862 return ok; 863 } 864 865 866 public static String escapeCSV(String value) { 867 if (value == null) 868 return ""; 869 870 StringBuilder b = new StringBuilder(); 871 for (char c : value.toCharArray()) { 872 if (c == '"') 873 b.append("\"\""); 874 else if (isWhitespace(c)) 875 b.append(" "); 876 else 877 b.append(c); 878 } 879 return b.toString(); 880 } 881 882 883 public static String escapeJson(String value) { 884 return escapeJson(value, true); 885 } 886 887 public static String escapeJson(String value, boolean escapeUnicodeWhitespace) { 888 if (value == null) 889 return ""; 890 891 StringBuilder b = new StringBuilder(); 892 for (char c : value.toCharArray()) { 893 if (c == '\r') 894 b.append("\\r"); 895 else if (c == '\n') 896 b.append("\\n"); 897 else if (c == '\t') 898 b.append("\\t"); 899 else if (c == '"') 900 b.append("\\\""); 901 else if (c == '\\') 902 b.append("\\\\"); 903 else if (c == ' ') 904 b.append(" "); 905 else if ((c == '\r' || c == '\n') || (isWhitespace(c) && escapeUnicodeWhitespace)) { 906 b.append("\\u"+Utilities.padLeft(Integer.toHexString(c), '0', 4)); 907 } else if (((int) c) < 32) 908 b.append("\\u" + Utilities.padLeft(Integer.toHexString(c), '0', 4)); 909 else 910 b.append(c); 911 } 912 return b.toString(); 913 } 914 915 public static String humanize(String code) { 916 StringBuilder b = new StringBuilder(); 917 boolean lastBreak = true; 918 for (char c : code.toCharArray()) { 919 if (Character.isLetter(c)) { 920 if (lastBreak) 921 b.append(Character.toUpperCase(c)); 922 else { 923 if (Character.isUpperCase(c)) 924 b.append(" "); 925 b.append(c); 926 } 927 lastBreak = false; 928 } else { 929 b.append(" "); 930 lastBreak = true; 931 } 932 } 933 if (b.length() == 0) 934 return code; 935 else 936 return b.toString(); 937 } 938 939 940 public static String uncapitalize(String s) { 941 if (s == null) return null; 942 if (s.length() == 0) return s; 943 if (s.length() == 1) return s.toLowerCase(); 944 945 return s.substring(0, 1).toLowerCase() + s.substring(1); 946 } 947 948 public static int charCount(String s, char c) { 949 int res = 0; 950 for (char ch : s.toCharArray()) 951 if (ch == c) 952 res++; 953 return res; 954 } 955 956 public static boolean equals(String one, String two) { 957 if (one == null && two == null) 958 return true; 959 if (one == null || two == null) 960 return false; 961 return one.equals(two); 962 } 963 964 965 public static boolean compareIgnoreWhitespace(File f1, File f2) throws IOException { 966 InputStream in1 = null; 967 InputStream in2 = null; 968 try { 969 in1 = new BufferedInputStream(ManagedFileAccess.inStream(f1)); 970 in2 = new BufferedInputStream(ManagedFileAccess.inStream(f2)); 971 972 int expectedByte = in1.read(); 973 while (expectedByte != -1) { 974 boolean w1 = Character.isWhitespace(expectedByte); 975 if (w1) 976 while (Character.isWhitespace(expectedByte)) 977 expectedByte = in1.read(); 978 int foundByte = in2.read(); 979 if (w1) { 980 if (!Character.isWhitespace(foundByte)) 981 return false; 982 while (Character.isWhitespace(foundByte)) 983 foundByte = in2.read(); 984 } 985 if (expectedByte != foundByte) 986 return false; 987 expectedByte = in1.read(); 988 } 989 if (in2.read() != -1) { 990 return false; 991 } 992 return true; 993 } finally { 994 if (in1 != null) { 995 try { 996 in1.close(); 997 } catch (IOException e) { 998 } 999 } 1000 if (in2 != null) { 1001 try { 1002 in2.close(); 1003 } catch (IOException e) { 1004 } 1005 } 1006 } 1007 } 1008 1009 1010 public static boolean compareIgnoreWhitespace(String fn1, String fn2) throws IOException { 1011 return compareIgnoreWhitespace(ManagedFileAccess.file(fn1), ManagedFileAccess.file(fn2)); 1012 } 1013 1014 1015 public static boolean isAbsoluteUrl(String ref) { 1016 if (ref != null && ref.contains(":")) { 1017 String scheme = ref.substring(0, ref.indexOf(":")); 1018 String details = ref.substring(ref.indexOf(":")+1); 1019 return (existsInList(scheme, "http", "https", "urn", "file:") || (isToken(scheme) && scheme.equals(scheme.toLowerCase())) || Utilities.startsWithInList(ref, "urn:iso:", "urn:iso-iec:", "urn:iso-cie:", "urn:iso-astm:", "urn:iso-ieee:", "urn:iec:")) 1020 && details != null && details.length() > 0 && !details.contains(" "); // rfc5141 1021 } 1022 return false; 1023 } 1024 1025 public static boolean isAbsoluteUrlLinkable(String ref) { 1026 if (ref != null && ref.contains(":")) { 1027 String scheme = ref.substring(0, ref.indexOf(":")); 1028 String details = ref.substring(ref.indexOf(":")+1); 1029 return (existsInList(scheme, "http", "https", "ftp")) 1030 && details != null && details.length() > 0 && !details.contains(" "); // rfc5141 1031 } 1032 return false; 1033 } 1034 1035 public static boolean equivalent(String l, String r) { 1036 if (Utilities.noString(l) && Utilities.noString(r)) 1037 return true; 1038 if (Utilities.noString(l) || Utilities.noString(r)) 1039 return false; 1040 return l.toLowerCase().equals(r.toLowerCase()); 1041 } 1042 1043 1044 public static boolean equivalentNumber(String l, String r) { 1045 if (Utilities.noString(l) && Utilities.noString(r)) 1046 return true; 1047 if (Utilities.noString(l) || Utilities.noString(r)) 1048 return false; 1049 if (!Utilities.isDecimal(l, true) || !Utilities.isDecimal(r, true)) 1050 return false; 1051 BigDecimal dl = new BigDecimal(l); 1052 BigDecimal dr = new BigDecimal(r); 1053 if (dl.scale() < dr.scale()) { 1054 dr = dr.setScale(dl.scale(), RoundingMode.HALF_UP); 1055 } else if (dl.scale() > dr.scale()) { 1056 dl = dl.setScale(dr.scale(), RoundingMode.HALF_UP); 1057 } 1058 return dl.equals(dr); 1059 } 1060 1061 public static String getFileExtension(String fn) { 1062 return fn.contains(".") ? fn.substring(fn.lastIndexOf(".") + 1) : ""; 1063 } 1064 1065 public static String unCamelCaseKeepCapitals(String name) { 1066 StringBuilder b = new StringBuilder(); 1067 boolean first = true; 1068 for (char c : name.toCharArray()) { 1069 if (Character.isUpperCase(c)) { 1070 if (!first) 1071 b.append(" "); 1072 b.append(c); 1073 } else 1074 b.append(c); 1075 first = false; 1076 } 1077 return b.toString(); 1078 } 1079 1080 public static String unCamelCase(String name) { 1081 StringBuilder b = new StringBuilder(); 1082 boolean first = true; 1083 for (char c : name.toCharArray()) { 1084 if (Character.isUpperCase(c)) { 1085 if (!first) 1086 b.append(" "); 1087 b.append(Character.toLowerCase(c)); 1088 } else 1089 b.append(c); 1090 first = false; 1091 } 1092 return b.toString(); 1093 } 1094 1095 1096 public static boolean isAbsoluteFileName(String source) { 1097 if (isWindows()) 1098 return (source.length() > 2 && source.charAt(1) == ':') || source.startsWith("\\\\"); 1099 else 1100 return source.startsWith("//"); 1101 } 1102 1103 1104 public static boolean isWindows() { 1105 return System.getProperty("os.name").startsWith("Windows"); 1106 } 1107 1108 1109 public static String splitLineForLength(String line, int prefixLength, int indent, int allowedLength) { 1110 List<String> list = new ArrayList<String>(); 1111 while (prefixLength + line.length() > allowedLength) { 1112 int i = allowedLength - (list.size() == 0 ? prefixLength : indent); 1113 while (i > 0 && line.charAt(i) != ' ') 1114 i--; 1115 if (i == 0) 1116 break; 1117 list.add(line.substring(0, i)); 1118 line = line.substring(i + 1); 1119 } 1120 list.add(line); 1121 StringBuilder b = new StringBuilder(); 1122 boolean first = true; 1123 for (String s : list) { 1124 if (first) 1125 first = false; 1126 else 1127 b.append("\r\n" + padLeft("", ' ', indent)); 1128 b.append(s); 1129 } 1130 return b.toString(); 1131 } 1132 1133 public static String makeId(String name) { 1134 StringBuilder b = new StringBuilder(); 1135 for (char ch : name.toCharArray()) { 1136 if (ch >= 'a' && ch <= 'z') 1137 b.append(ch); 1138 else if (ch >= 'A' && ch <= 'Z') 1139 b.append(ch); 1140 else if (ch >= '0' && ch <= '9') 1141 b.append(ch); 1142 else if (ch == '-' || ch == '.') 1143 b.append(ch); 1144 } 1145 return b.toString(); 1146 } 1147 1148 1149 public static String extractBaseUrl(String url) { 1150 if (url == null) 1151 return null; 1152 else if (url.contains("/")) 1153 return url.substring(0, url.lastIndexOf("/")); 1154 else 1155 return url; 1156 } 1157 1158 public static String listCanonicalUrls(Set<String> keys) { 1159 return keys.toString(); 1160 } 1161 1162 public static class CaseInsensitiveSorter implements Comparator<String> { 1163 @Override 1164 public int compare(String o1, String o2) { 1165 return o1.compareToIgnoreCase(o2); 1166 } 1167 } 1168 1169 public static List<String> sortedCaseInsensitive(Collection<String> set) { 1170 List<String> list = new ArrayList<>(); 1171 list.addAll(set); 1172 Collections.sort(list, new CaseInsensitiveSorter()); 1173 return list; 1174 } 1175 1176 1177 public static List<String> sorted(Collection<String> set) { 1178 List<String> list = new ArrayList<>(); 1179 list.addAll(set); 1180 Collections.sort(list); 1181 return list; 1182 } 1183 1184 public static List<String> sortedReverse(Collection<String> set) { 1185 List<String> list = new ArrayList<>(); 1186 list.addAll(set); 1187 Collections.sort(list); 1188 List<String> rlist = new ArrayList<>(); 1189 for (int i = list.size()-1; i >= 0; i--) { 1190 rlist.add(list.get(i)); 1191 } 1192 return rlist; 1193 } 1194 1195 public static List<String> sorted(String[] set) { 1196 List<String> list = new ArrayList<>(); 1197 for (String s : set) { 1198 list.add(s); 1199 } 1200 Collections.sort(list); 1201 return list; 1202 } 1203 1204 1205 public static List<String> reverseSorted(Collection<String> set) { 1206 List<String> list = new ArrayList<>(); 1207 list.addAll(set); 1208 Collections.sort(list, Collections.reverseOrder()); 1209 return list; 1210 } 1211 1212 public static List<String> reverseSorted(String[] set) { 1213 List<String> list = new ArrayList<>(); 1214 for (String s : set) { 1215 list.add(s); 1216 } 1217 Collections.sort(list, Collections.reverseOrder()); 1218 return list; 1219 } 1220 1221 1222 public static void analyseStringDiffs(Set<String> source, Set<String> target, Set<String> missed, Set<String> extra) { 1223 for (String s : source) 1224 if (!target.contains(s)) 1225 missed.add(s); 1226 for (String s : target) 1227 if (!source.contains(s)) 1228 extra.add(s); 1229 1230 } 1231 1232 /** 1233 * Only handles simple FHIRPath expressions of the type produced by the validator 1234 * 1235 * @param path 1236 * @return 1237 */ 1238 public static String fhirPathToXPath(String path) { 1239 String[] p = path.split("\\."); 1240 CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder("."); 1241 int i = 0; 1242 while (i < p.length) { 1243 String s = p[i]; 1244 if (s.contains("[")) { 1245 String si = s.substring(s.indexOf("[") + 1, s.length() - 1); 1246 if (!Utilities.isInteger(si)) 1247 throw new FHIRException("The FHIRPath expression '" + path + "' is not valid"); 1248 s = s.substring(0, s.indexOf("[")) + "[" + Integer.toString(Integer.parseInt(si) + 1) + "]"; 1249 } 1250 if (i < p.length - 1 && p[i + 1].startsWith(".ofType(")) { 1251 i++; 1252 s = s + capitalize(p[i].substring(8, p.length - 1)); 1253 } 1254 b.append(s); 1255 i++; 1256 } 1257 return b.toString(); 1258 } 1259 1260 public static String describeDuration(Duration d) { 1261 if (d.toDays() > 2) { 1262 return String.format("%s days", d.toDays()); 1263 } else if (d.toHours() > 2) { 1264 return String.format("%s hours", d.toHours()); 1265 } else if (d.toMinutes() > 2) { 1266 return String.format("%s mins", d.toMinutes()); 1267 } else { 1268 return String.format("%s ms", d.toMillis()); 1269 } 1270 } 1271 1272 public static String describeDuration(long ms) { 1273 long days = ms / (1000 * 60 * 60 * 24); 1274 long hours = ms / (1000 * 60 * 60) % 24; 1275 long mins = ms / (1000 * 60) % 60; 1276 long secs = ms / (1000) % 60; 1277 ms = ms % 1000; 1278 if (days > 0) { 1279 return ""+days+"d "+pad(hours,2)+":"+pad(mins,2)+":"+pad(secs,2)+"."+ms; 1280 } else { 1281 return ""+pad(hours, 2)+":"+pad(mins,2)+":"+pad(secs,2)+"."+ms; 1282 } 1283 } 1284 1285 private static String pad(long v, int i) { 1286 return padLeft(Long.toString(v), '0', i); 1287 } 1288 1289 public static boolean startsWithInList(String s, String... list) { 1290 if (s == null) { 1291 return false; 1292 } 1293 for (String l : list) { 1294 if (l != null) { 1295 if (s.startsWith(l)) { 1296 return true; 1297 } 1298 } 1299 } 1300 return false; 1301 } 1302 1303 public static boolean startsWithInList(String s, Collection<String> list) { 1304 if (s == null || list == null) { 1305 return false; 1306 } 1307 for (String l : list) { 1308 if (s.startsWith(l)) { 1309 return true; 1310 } 1311 } 1312 return false; 1313 } 1314 1315 public static boolean endsWithInList(String s, String... list) { 1316 if (s == null) { 1317 return false; 1318 } 1319 for (String l : list) { 1320 if (s.endsWith(l)) { 1321 return true; 1322 } 1323 } 1324 return false; 1325 } 1326 1327 public static boolean endsWithInList(String s, Collection<String> list) { 1328 if (s == null) { 1329 return false; 1330 } 1331 for (String l : list) { 1332 if (s.endsWith(l)) { 1333 return true; 1334 } 1335 } 1336 return false; 1337 } 1338 1339 public static final int ONE_MB = 1024; 1340 public static final String GB = "Gb"; 1341 public static final String MB = "Mb"; 1342 public static final String KB = "Kb"; 1343 public static final String BT = "b"; 1344 1345 public static String describeSize(int length) { 1346 if (length < 0) throw new IllegalArgumentException("File length of < 0 passed in..."); 1347 1348 if (length > Math.pow(ONE_MB, 3)) { 1349 return length / ((long) Math.pow(ONE_MB, 3)) + GB; 1350 } 1351 if (length > Math.pow(ONE_MB, 2)) { 1352 return length / ((long) Math.pow(ONE_MB, 2)) + MB; 1353 } 1354 if (length > ONE_MB) { 1355 return length / (ONE_MB) + KB; 1356 } 1357 return length + BT; 1358 } 1359 1360 public static String describeSize(long length) { 1361 if (length < 0) throw new IllegalArgumentException("File length of < 0 passed in..."); 1362 1363 if (length > Math.pow(ONE_MB, 3)) { 1364 return length / ((long) Math.pow(ONE_MB, 3)) + GB; 1365 } 1366 if (length > Math.pow(ONE_MB, 2)) { 1367 return length / ((long) Math.pow(ONE_MB, 2)) + MB; 1368 } 1369 if (length > ONE_MB) { 1370 return length / (ONE_MB) + KB; 1371 } 1372 return length + BT; 1373 } 1374 1375 public static List<byte[]> splitBytes(byte[] array, byte[] delimiter) { 1376 List<byte[]> byteArrays = new LinkedList<byte[]>(); 1377 if (delimiter.length == 0) 1378 { 1379 return byteArrays; 1380 } 1381 int begin = 0; 1382 1383 outer: for (int i = 0; i < array.length - delimiter.length + 1; i++) 1384 { 1385 for (int j = 0; j < delimiter.length; j++) 1386 { 1387 if (array[i + j] != delimiter[j]) 1388 { 1389 continue outer; 1390 } 1391 } 1392 1393 // If delimiter is at the beginning then there will not be any data. 1394 if (begin < i) 1395 byteArrays.add(Arrays.copyOfRange(array, begin, i)); 1396 begin = i + delimiter.length; 1397 } 1398 1399 // delimiter at the very end with no data following? 1400 if (begin != array.length) 1401 byteArrays.add(Arrays.copyOfRange(array, begin, array.length)); 1402 1403 return byteArrays; 1404 } 1405 1406 final static int[] illegalChars = {34, 60, 62, 124, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 58, 42, 63, 92, 47}; 1407 1408 static { 1409 Arrays.sort(illegalChars); 1410 } 1411 1412 public static int findinList(String[] list, String val) { 1413 for (int i = 0; i < list.length; i++) { 1414 if (val.equals(list[i])) { 1415 return i; 1416 } 1417 } 1418 return -1; 1419 } 1420 1421 public static String toString(String[] expected) { 1422 return "['"+String.join("' | '", expected)+"']"; 1423 } 1424 1425 public static String lowBoundaryForDecimal(String value, int precision) { 1426 if (Utilities.noString(value)) { 1427 throw new FHIRException("Unable to calculate lowBoundary for a null decimal string"); 1428 } 1429 String e = value.contains("e") ? value.substring(value.indexOf("e")+1) : null; 1430 if (value.contains("e")) { 1431 value = value.substring(0, value.indexOf("e")); 1432 } 1433 if (isZero(value)) { 1434 return applyPrecision("-0.5000000000000000000000000", precision, true); 1435 } else if (value.startsWith("-")) { 1436 return "-"+highBoundaryForDecimal(value.substring(1), precision)+(e == null ? "" : e); 1437 } else { 1438 if (value.contains(".")) { 1439 return applyPrecision(minusOne(value)+"50000000000000000000000000000", precision, true)+(e == null ? "" : e); 1440 } else { 1441 return applyPrecision(minusOne(value)+".50000000000000000000000000000", precision, true)+(e == null ? "" : e); 1442 } 1443 } 1444 } 1445 1446 private static String applyPrecision(String v, int p, boolean down) { 1447 String nv = v; 1448 int dp = -1; 1449 if (nv.contains(".")) { 1450 dp = nv.indexOf("."); 1451 nv = nv.substring(0, dp)+nv.substring(dp+1); 1452 } 1453 String s = null; 1454 int d = p - getDecimalPrecision(v); 1455 if (d == 0) { 1456 s = nv; 1457 } else if (d > 0) { 1458 s = nv + padLeft("", '0', d); 1459 } else { 1460 int l = v.length(); 1461 int ld = l+d; 1462 if (dp > -1) { 1463 ld--; 1464 } 1465 if (nv.charAt(ld) >= '5' && !down) { 1466 s = nv.substring(0, ld-1)+((char) (nv.charAt(ld-1)+1)); 1467 } else { 1468 s = nv.substring(0, ld); 1469 } 1470 } 1471 if (s.endsWith(".")) { 1472 s = s.substring(0, s.length()-1); 1473 } 1474 return dp == -1 || dp >= s.length() ? s : s.substring(0, dp)+"."+s.substring(dp); 1475 } 1476 1477 private static String minusOne(String value) { 1478 StringBuffer s = new StringBuffer(value); 1479 for (int i = s.length()-1; i >= 0; i--) { 1480 if (s.charAt(i) == '0') { 1481 s.setCharAt(i, '9'); 1482 } else if (s.charAt(i) != '.') { 1483 s.setCharAt(i, (char) (s.charAt(i)-1)); 1484 break; 1485 } 1486 } 1487 return s.toString(); 1488 } 1489 1490 1491 public static String highBoundaryForDecimal(String value, int precision) { 1492 if (Utilities.noString(value)) { 1493 throw new FHIRException("Unable to calculate highBoundary for a null decimal string"); 1494 } 1495 String e = value.contains("e") ? value.substring(value.indexOf("e")+1) : null; 1496 if (value.contains("e")) { 1497 value = value.substring(0, value.indexOf("e")); 1498 } 1499 if (isZero(value)) { 1500 return applyPrecision("0.50000000000000000000000000000", precision, false); 1501 } else if (value.startsWith("-")) { 1502 return "-"+lowBoundaryForDecimal(value.substring(1), precision)+(e == null ? "" : e); 1503 } else { 1504 if (value.contains(".")) { 1505 return applyPrecision(value+"50000000000000000000000000000", precision, false)+(e == null ? "" : e); 1506 } else { 1507 return applyPrecision(value+".50000000000000000000000000000", precision, false)+(e == null ? "" : e); 1508 } 1509 } 1510 } 1511 1512 private static boolean isZero(String value) { 1513 return value.replace(".", "").replace("-", "").replace("0", "").length() == 0; 1514 } 1515 1516 public static Integer getDecimalPrecision(String value) { 1517 if (value.contains("e")) { 1518 value = value.substring(0, value.indexOf("e")); 1519 } 1520 if (value.contains(".")) { 1521 return value.split("\\.")[1].length(); 1522 } else { 1523 return 0; 1524 } 1525 } 1526 1527 1528 public static String padInt(int i, int len) { 1529 return Utilities.padLeft(Integer.toString(i), ' ', len); 1530 } 1531 1532 public static String padInt(long i, int len) { 1533 return Utilities.padLeft(Long.toString(i), ' ', len); 1534 } 1535 1536 public static Object makeSingleLine(String text) { 1537 text = text.replace("\r", " "); 1538 text = text.replace("\n", " "); 1539 while (text.contains(" ")) { 1540 text = text.replace(" ", " "); 1541 } 1542 return text; 1543 } 1544 1545 public static int parseInt(String value, int def) { 1546 if (isInteger(value)) { 1547 return Integer.parseInt(value); 1548 } else { 1549 return def; 1550 } 1551 } 1552 1553 /** 1554 * Appends a text from a derived element to its base element. 1555 * 1556 * @param baseText The text set in the base element, or {@code null}. 1557 * @param derivedText The text set in the derived element, starting with "...". 1558 * @return The resulting text. 1559 */ 1560 public static String appendDerivedTextToBase(@Nullable final String baseText, 1561 final String derivedText) { 1562 if (baseText == null) { 1563 return derivedText.substring(3); 1564 } 1565 return baseText + "\r\n" + derivedText.substring(3); 1566 } 1567 1568 public static String getRelativeUrlPath(String root, String path) { 1569 String res = path.substring(root.length()); 1570 if (res.startsWith("/")) { 1571 res = res.substring(1); 1572 } 1573 return res; 1574 } 1575 1576 public static boolean isValidCRName(String name) { 1577 return name != null && name.matches("[A-Z]([A-Za-z0-9_]){1,254}"); 1578 } 1579 1580 public static boolean isAllWhitespace(String s) { 1581 if (Utilities.noString(s)) { 1582 return true; 1583 } 1584 for (char ch : s.toCharArray()) { 1585 if (!isWhitespace(ch)) { 1586 return false; 1587 } 1588 } 1589 return true; 1590 } 1591 1592 public static String trimWS(String s) { 1593 if (Utilities.noString(s)) { 1594 return s; 1595 } 1596 int start = 0; 1597 while (start < s.length() && isWhitespace(s.charAt(start))) { 1598 start++; 1599 } 1600 if (start == s.length()) { 1601 return ""; 1602 } 1603 int end = s.length() - 1; 1604 while (end >= 0 && isWhitespace(s.charAt(end))) { 1605 end--; 1606 } 1607 if (start > end) { 1608 return ""; 1609 } 1610 return s.substring(start, end+1); 1611 } 1612 1613 // from https://en.wikipedia.org/wiki/Whitespace_character#Unicode 1614 public static boolean isWhitespace(int ch) { 1615 return Utilities.existsInList(ch, '\u0009', '\n', '\u000B','\u000C','\r','\u0020','\u0085','\u00A0', 1616 '\u1680','\u2000','\u2001','\u2002','\u2003','\u2004','\u2005','\u2006','\u2007','\u2008','\u2009','\u200A', 1617 '\u2028', '\u2029', '\u202F', '\u205F', '\u3000'); 1618 } 1619 1620 public static boolean stringsEqual(String s1, String s2) { 1621 if (s1 == null && s2 == null) { 1622 return true; 1623 } else if (s1 == null) { 1624 return false; 1625 } else { 1626 return s1.equals(s2); 1627 } 1628 } 1629 1630 public static String tail(String url) { 1631 int i = url.length()-1; 1632 while (i >= 0 && (isTokenChar(url.charAt(i)) || isDigit(url.charAt(i))) ) { 1633 i--; 1634 } 1635 if (i < 0) { 1636 return url; 1637 } else { 1638 return url.substring(i+1); 1639 } 1640 } 1641 1642 public static List<String> strings(String... members) { 1643 List<String> ret = new ArrayList<>(); 1644 for (String m : members) { 1645 ret.add(m); 1646 } 1647 return ret; 1648 } 1649 1650 public static List<String> splitStrings(String src, String regex) { 1651 List<String> ret = new ArrayList<>(); 1652 for (String m : src.split(regex)) { 1653 ret.add(m); 1654 } 1655 return ret; 1656 } 1657 1658 public static String stripPara(String p) { 1659 if (noString(p)) { 1660 return ""; 1661 } 1662 p = p.trim(); 1663 if (p.startsWith("<p>")) { 1664 p = p.substring(3); 1665 } 1666 if (p.endsWith("</p>")) { 1667 p = p.substring(0, p.length()-4); 1668 } 1669 return p; 1670 } 1671 1672 public static String stripAllPara(String p) { 1673 if (noString(p)) { 1674 return ""; 1675 } 1676 p = p.trim(); 1677 if (p.startsWith("<p>")) { 1678 p = p.substring(3); 1679 } 1680 if (p.endsWith("</p>")) { 1681 p = p.substring(0, p.length()-4); 1682 } 1683 p = p.replace("</p>", " "); 1684 p = p.replace("<p>", ""); 1685 while (p.contains("<p ")) { 1686 int start = p.indexOf("<p "); 1687 int end = start; 1688 while (end < p.length() && p.charAt(end) != '>') { 1689 end++; 1690 } 1691 p = p.substring(start, end); 1692 } 1693 return p; 1694 } 1695 1696 1697 1698 //public static boolean !isWhitespace(String s) { 1699 //boolean ok = true; 1700 //for (int i = 0; i < s.length(); i++) 1701 // ok = ok && Character.isWhitespace(s.charAt(i)); 1702 //return ok; 1703 // 1704 //} 1705 1706 1707 public static boolean isTxFhirOrgServer(String s) { 1708 return Utilities.startsWithInList(s.replace("https://", "http://"), FhirSettings.getTxFhirProduction(), FhirSettings.getTxFhirDevelopment(), FhirSettings.getTxFhirLocal()); 1709 } 1710 1711 public static String[] splitLines(String txt) { 1712 return txt.split("\\r?\\n|\\r"); 1713 } 1714 1715 public static String rightTrim(String s) { 1716 int i = s.length()-1; 1717 while (i > 0 && Character.isWhitespace(s.charAt(i))) { 1718 i--; 1719 } 1720 return i == 0 ? "" : s.substring(0, i+1); 1721 } 1722 1723 public static String urlTail(String url) { 1724 if (url == null) { 1725 return null; 1726 } 1727 return url.contains("/") ? url.substring(url.lastIndexOf("/")+1) : url; 1728 } 1729 1730 public static String escapeSql(String s) { 1731 return s.replace("'", "''"); 1732 } 1733 1734 public static String[] simpleSplit(String cnt, String div) { 1735 if (cnt == null) { 1736 return new String[] {}; 1737 } 1738 List<String> parts = new ArrayList<>(); 1739 int cursor = 0; 1740 int last = 0; 1741 while (cursor < cnt.length()) { 1742 if (matches(cnt, div, cursor)) { 1743 parts.add(cnt.substring(last, cursor)); 1744 cursor = cursor + div.length(); 1745 last = cursor; 1746 } else { 1747 cursor++; 1748 } 1749 } 1750 parts.add(cnt.substring(last, cursor)); 1751 return parts.toArray(new String[] {}); 1752 } 1753 1754 private static boolean matches(String cnt, String div, int cursor) { 1755 if (div.length() + cursor > cnt.length()) { 1756 return false; 1757 } 1758 for (int i = 0; i < div.length(); i++) { 1759 if (cnt.charAt(cursor+i) != div.charAt(i)) { 1760 return false; 1761 } 1762 } 1763 return true; 1764 } 1765 1766 public static String stripEoln(String text) { 1767 if (text == null) { 1768 return ""; 1769 } 1770 return text.replace("\r\n", " ").replace("\n", " ").replace("\r", " "); 1771 } 1772 1773 public static String extractDomain(String source) { 1774 try { 1775 URI uri = URI.create(source); 1776 return uri.getHost(); 1777 } catch (Exception e) { 1778 return "??"; 1779 } 1780 } 1781 1782 public static boolean isValidHtmlAnchorChar(char c) { 1783 if ( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) { 1784 return true; 1785 } 1786 switch (c) { 1787 case '!': 1788 case '$': 1789 case '&': 1790 case '\'': 1791 case '(': 1792 case ')': 1793 case '*': 1794 case '+': 1795 case ',': 1796 case ';': 1797 case '=': 1798 case '.': 1799 case '_': 1800 case '-': 1801 case '~': 1802 case ':': 1803 case '@': 1804 case '/': 1805 case '?': 1806 return true; 1807 default: 1808 return false; 1809 } 1810 } 1811 1812 public static boolean listValueStartsWith(String s, Set<String> list) { 1813 if (s == null || list == null) { 1814 return false; 1815 } 1816 for (String l : list) { 1817 if (l.startsWith(s)) { 1818 return true; 1819 } 1820 } 1821 return false; 1822 } 1823 1824 public static String extractByRegex(String input, String regex) { 1825 Pattern pattern = Pattern.compile(regex); 1826 Matcher matcher = pattern.matcher(input); 1827 1828 StringBuilder result = new StringBuilder(); 1829 while (matcher.find()) { 1830 result.append(matcher.group(1)); 1831 } 1832 return result.length() == 0 ? null : result.toString(); 1833 } 1834 1835 public static String getDirectoryForURL(String url) { 1836 return url.contains("/") && url.lastIndexOf("/") > 10 ? url.substring(0, url.lastIndexOf("/")) : url; 1837 } 1838 1839 public static List<String> copyAdd(List<String> oldList, String newItem) { 1840 List<String> newList = new ArrayList<>(oldList); 1841 newList.add(newItem); 1842 return newList; 1843 } 1844 1845 1846 1847}