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