001package org.hl7.fhir.utilities; 002 003/* 004 Copyright (c) 2011+, HL7, Inc. 005 All rights reserved. 006 007 Redistribution and use in source and binary forms, with or without modification, 008 are permitted provided that the following conditions are met: 009 010 * Redistributions of source code must retain the above copyright notice, this 011 list of conditions and the following disclaimer. 012 * Redistributions in binary form must reproduce the above copyright notice, 013 this list of conditions and the following disclaimer in the documentation 014 and/or other materials provided with the distribution. 015 * Neither the name of HL7 nor the names of its contributors may be used to 016 endorse or promote products derived from this software without specific 017 prior written permission. 018 019 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 020 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 021 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 022 IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 023 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 024 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 025 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 026 WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 027 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 028 POSSIBILITY OF SUCH DAMAGE. 029 030 */ 031 032 033import org.apache.commons.io.FileUtils; 034import org.hl7.fhir.exceptions.FHIRException; 035 036import java.io.BufferedInputStream; 037import java.io.File; 038import java.io.FileInputStream; 039import java.io.FileNotFoundException; 040import java.io.FileOutputStream; 041import java.io.FilenameFilter; 042import java.io.IOException; 043import java.io.InputStream; 044import java.io.UnsupportedEncodingException; 045import java.net.URLDecoder; 046import java.net.URLEncoder; 047import java.nio.channels.FileChannel; 048import java.nio.file.Paths; 049import java.time.Duration; 050import java.util.ArrayList; 051import java.util.Collection; 052import java.util.Collections; 053import java.util.List; 054import java.util.Set; 055import java.util.UUID; 056 057import static org.apache.commons.lang3.StringUtils.isBlank; 058 059public class Utilities { 060 061 private static final String OID_REGEX = "[0-2](\\.(0|[1-9][0-9]*))+"; 062 063 /** 064 * Returns the plural form of the word in the string. 065 * <p> 066 * Examples: 067 * 068 * <pre> 069 * inflector.pluralize("post") #=> "posts" 070 * inflector.pluralize("octopus") #=> "octopi" 071 * inflector.pluralize("sheep") #=> "sheep" 072 * inflector.pluralize("words") #=> "words" 073 * inflector.pluralize("the blue mailman") #=> "the blue mailmen" 074 * inflector.pluralize("CamelOctopus") #=> "CamelOctopi" 075 * </pre> 076 * <p> 077 * <p> 078 * <p> 079 * Note that if the {@link Object#toString()} is called on the supplied object, so this method works for non-strings, too. 080 * 081 * @param word the word that is to be pluralized. 082 * @return the pluralized form of the word, or the word itself if it could not be pluralized 083 * @see #singularize(Object) 084 */ 085 public static String pluralizeMe(String word) { 086 Inflector inf = new Inflector(); 087 return inf.pluralize(word); 088 } 089 090 public static String pluralize(String word, int count) { 091 if (count == 1) 092 return word; 093 Inflector inf = new Inflector(); 094 return inf.pluralize(word); 095 } 096 097 098 public static boolean isInteger(String string) { 099 if (isBlank(string)) { 100 return false; 101 } 102 String value = string.startsWith("-") ? string.substring(1) : string; 103 for (char next : value.toCharArray()) { 104 if (!Character.isDigit(next)) { 105 return false; 106 } 107 } 108 // check bounds -2,147,483,648..2,147,483,647 109 if (value.length() > 10) 110 return false; 111 if (string.startsWith("-")) { 112 if (value.length() == 10 && string.compareTo("2147483648") > 0) 113 return false; 114 } else { 115 if (value.length() == 10 && string.compareTo("2147483647") > 0) 116 return false; 117 } 118 return true; 119 } 120 121 public static boolean isLong(String string) { 122 if (isBlank(string)) { 123 return false; 124 } 125 String value = string.startsWith("-") ? string.substring(1) : string; 126 for (char next : value.toCharArray()) { 127 if (!Character.isDigit(next)) { 128 return false; 129 } 130 } 131 // check bounds -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 132 if (value.length() > 20) 133 return false; 134 if (string.startsWith("-")) { 135 if (value.length() == 20 && string.compareTo("9223372036854775808") > 0) 136 return false; 137 } else { 138 if (value.length() == 20 && string.compareTo("9223372036854775807") > 0) 139 return false; 140 } 141 return true; 142 } 143 144 public static boolean isHex(String string) { 145 try { 146 int i = Integer.parseInt(string, 16); 147 return i != i + 1; 148 } catch (Exception e) { 149 return false; 150 } 151 } 152 153 public enum DecimalStatus { 154 BLANK, SYNTAX, RANGE, OK 155 } 156 157 public static boolean isDecimal(String value, boolean allowExponent, boolean allowLeadingZero) { 158 DecimalStatus ds = checkDecimal(value, allowExponent, true); 159 return ds == DecimalStatus.OK || ds == DecimalStatus.RANGE; 160 } 161 162 public static boolean isDecimal(String value, boolean allowExponent) { 163 DecimalStatus ds = checkDecimal(value, allowExponent, false); 164 return ds == DecimalStatus.OK || ds == DecimalStatus.RANGE; 165 } 166 167 public static DecimalStatus checkDecimal(String value, boolean allowExponent, boolean allowLeadingZero) { 168 if (isBlank(value)) { 169 return DecimalStatus.BLANK; 170 } 171 172 // check for leading zeros 173 if (!allowLeadingZero) { 174 if (value.startsWith("0") && !"0".equals(value) && !value.startsWith("0.")) 175 return DecimalStatus.SYNTAX; 176 if (value.startsWith("-0") && !"-0".equals(value) && !value.startsWith("-0.")) 177 return DecimalStatus.SYNTAX; 178 if (value.startsWith("+0") && !"+0".equals(value) && !value.startsWith("+0.")) 179 return DecimalStatus.SYNTAX; 180 } 181 182 // check for trailing dot 183 if (value.endsWith(".")) { 184 return DecimalStatus.SYNTAX; 185 } 186 187 boolean havePeriod = false; 188 boolean haveExponent = false; 189 boolean haveSign = false; 190 boolean haveDigits = false; 191 int preDecLength = 0; 192 int postDecLength = 0; 193 int exponentLength = 0; 194 int length = 0; 195 for (char next : value.toCharArray()) { 196 if (next == '.') { 197 if (!haveDigits || havePeriod || haveExponent) 198 return DecimalStatus.SYNTAX; 199 havePeriod = true; 200 preDecLength = length; 201 length = 0; 202 } else if (next == '-' || next == '+') { 203 if (haveDigits || haveSign) 204 return DecimalStatus.SYNTAX; 205 haveSign = true; 206 } else if (next == 'e' || next == 'E') { 207 if (!haveDigits || haveExponent || !allowExponent) 208 return DecimalStatus.SYNTAX; 209 haveExponent = true; 210 haveSign = false; 211 haveDigits = false; 212 if (havePeriod) 213 postDecLength = length; 214 else 215 preDecLength = length; 216 length = 0; 217 } else if (!Character.isDigit(next)) { 218 return DecimalStatus.SYNTAX; 219 } else { 220 haveDigits = true; 221 length++; 222 } 223 } 224 if (haveExponent && !haveDigits) 225 return DecimalStatus.SYNTAX; 226 if (haveExponent) 227 exponentLength = length; 228 else if (havePeriod) 229 postDecLength = length; 230 else 231 preDecLength = length; 232 233 // now, bounds checking - these are arbitrary 234 if (exponentLength > 4) 235 return DecimalStatus.RANGE; 236 if (preDecLength + postDecLength > 18) 237 return DecimalStatus.RANGE; 238 239 return DecimalStatus.OK; 240 } 241 242 public static String camelCase(String value) { 243 return new Inflector().camelCase(value.trim().replace(" ", "_"), false); 244 } 245 246 public static String escapeXml(String doco) { 247 if (doco == null) 248 return ""; 249 250 StringBuilder b = new StringBuilder(); 251 for (char c : doco.toCharArray()) { 252 if (c == '<') 253 b.append("<"); 254 else if (c == '>') 255 b.append(">"); 256 else if (c == '&') 257 b.append("&"); 258 else if (c == '"') 259 b.append("""); 260 else 261 b.append(c); 262 } 263 return b.toString(); 264 } 265 266 public static String titleize(String s) { 267 StringBuilder b = new StringBuilder(); 268 boolean up = true; 269 for (char c : s.toCharArray()) { 270 if (up) 271 b.append(Character.toUpperCase(c)); 272 else 273 b.append(c); 274 up = c == ' '; 275 } 276 return b.toString(); 277 } 278 279 public static String capitalize(String s) { 280 if (s == null) return null; 281 if (s.length() == 0) return s; 282 if (s.length() == 1) return s.toUpperCase(); 283 284 return s.substring(0, 1).toUpperCase() + s.substring(1); 285 } 286 287 public static void copyDirectory(String sourceFolder, String destFolder, FileNotifier notifier) throws IOException, FHIRException { 288 CSFile src = new CSFile(sourceFolder); 289 if (!src.exists()) 290 throw new FHIRException("Folder " + sourceFolder + " not found"); 291 createDirectory(destFolder); 292 293 String[] files = src.list(); 294 for (String f : files) { 295 if (new CSFile(sourceFolder + File.separator + f).isDirectory()) { 296 if (!f.startsWith(".")) // ignore .git files... 297 copyDirectory(sourceFolder + File.separator + f, destFolder + File.separator + f, notifier); 298 } else { 299 if (notifier != null) 300 notifier.copyFile(sourceFolder + File.separator + f, destFolder + File.separator + f); 301 copyFile(new CSFile(sourceFolder + File.separator + f), new CSFile(destFolder + File.separator + f)); 302 } 303 } 304 } 305 306 public static void copyFile(String source, String dest) throws IOException { 307 copyFile(new File(source), new File(dest)); 308 } 309 310 public static void copyFile(File sourceFile, File destFile) throws IOException { 311 if (!destFile.exists()) { 312 if (!new CSFile(destFile.getParent()).exists()) { 313 createDirectory(destFile.getParent()); 314 } 315 destFile.createNewFile(); 316 } 317 318 FileChannel source = null; 319 FileChannel destination = null; 320 321 try { 322 source = new FileInputStream(sourceFile).getChannel(); 323 destination = new FileOutputStream(destFile).getChannel(); 324 destination.transferFrom(source, 0, source.size()); 325 } finally { 326 if (source != null) { 327 source.close(); 328 } 329 if (destination != null) { 330 destination.close(); 331 } 332 } 333 } 334 335 public static boolean checkFolder(String dir, List<String> errors) 336 throws IOException { 337 if (!new CSFile(dir).exists()) { 338 errors.add("Unable to find directory " + dir); 339 return false; 340 } else { 341 return true; 342 } 343 } 344 345 public static boolean checkFile(String purpose, String dir, String file, List<String> errors) 346 throws IOException { 347 if (!new CSFile(dir + file).exists()) { 348 if (errors != null) 349 errors.add("Unable to find " + purpose + " file " + file + " in " + dir); 350 return false; 351 } else { 352 return true; 353 } 354 } 355 356 public static String asCSV(List<String> strings) { 357 StringBuilder s = new StringBuilder(); 358 boolean first = true; 359 for (String n : strings) { 360 if (!first) 361 s.append(","); 362 s.append(n); 363 first = false; 364 } 365 return s.toString(); 366 } 367 368 public static String asHtmlBr(String prefix, List<String> strings) { 369 StringBuilder s = new StringBuilder(); 370 boolean first = true; 371 for (String n : strings) { 372 if (!first) 373 s.append("<br/>"); 374 s.append(prefix); 375 s.append(n); 376 first = false; 377 } 378 return s.toString(); 379 } 380 381 public static void clearDirectory(String folder, String... exemptions) throws IOException { 382 File dir = new File(folder); 383 if (dir.exists()) { 384 if (exemptions.length == 0) 385 FileUtils.cleanDirectory(dir); 386 else { 387 String[] files = new CSFile(folder).list(); 388 if (files != null) { 389 for (String f : files) { 390 if (!existsInList(f, exemptions)) { 391 File fh = new CSFile(folder + File.separatorChar + f); 392 if (fh.isDirectory()) 393 clearDirectory(fh.getAbsolutePath()); 394 fh.delete(); 395 } 396 } 397 } 398 } 399 } 400 } 401 402 public static File createDirectory(String path) throws IOException { 403 new CSFile(path).mkdirs(); 404 return new File(path); 405 } 406 407 public static String changeFileExt(String name, String ext) { 408 if (name.lastIndexOf('.') > -1) 409 return name.substring(0, name.lastIndexOf('.')) + ext; 410 else 411 return name + ext; 412 } 413 414 public static String cleanupTextString(String contents) { 415 if (contents == null || contents.trim().equals("")) 416 return null; 417 else 418 return contents.trim(); 419 } 420 421 422 public static boolean noString(String v) { 423 return v == null || v.equals(""); 424 } 425 426 427 public static void bytesToFile(byte[] content, String filename) throws IOException { 428 FileOutputStream out = new FileOutputStream(filename); 429 out.write(content); 430 out.close(); 431 432 } 433 434 435 public static String appendSlash(String definitions) { 436 return definitions.endsWith(File.separator) ? definitions : definitions + File.separator; 437 } 438 439 public static String appendForwardSlash(String definitions) { 440 return definitions.endsWith("/") ? definitions : definitions + "/"; 441 } 442 443 444 public static String fileTitle(String file) { 445 if (file == null) 446 return null; 447 String s = new File(file).getName(); 448 return s.indexOf(".") == -1 ? s : s.substring(0, s.indexOf(".")); 449 } 450 451 452 public static String systemEol() { 453 return System.getProperty("line.separator"); 454 } 455 456 public static String normaliseEolns(String value) { 457 return value.replace("\r\n", "\r").replace("\n", "\r").replace("\r", "\r\n"); 458 } 459 460 461 public static String unescapeXml(String xml) throws FHIRException { 462 if (xml == null) 463 return null; 464 465 StringBuilder b = new StringBuilder(); 466 int i = 0; 467 while (i < xml.length()) { 468 if (xml.charAt(i) == '&') { 469 StringBuilder e = new StringBuilder(); 470 i++; 471 while (xml.charAt(i) != ';') { 472 e.append(xml.charAt(i)); 473 i++; 474 } 475 if (e.toString().equals("lt")) 476 b.append("<"); 477 else if (e.toString().equals("gt")) 478 b.append(">"); 479 else if (e.toString().equals("amp")) 480 b.append("&"); 481 else if (e.toString().equals("quot")) 482 b.append("\""); 483 else if (e.toString().equals("mu")) 484 b.append((char) 956); 485 else 486 throw new FHIRException("unknown XML entity \"" + e.toString() + "\""); 487 } else 488 b.append(xml.charAt(i)); 489 i++; 490 } 491 return b.toString(); 492 } 493 494 public static String unescapeJson(String json) throws FHIRException { 495 if (json == null) 496 return null; 497 498 StringBuilder b = new StringBuilder(); 499 int i = 0; 500 while (i < json.length()) { 501 if (json.charAt(i) == '\\') { 502 i++; 503 char ch = json.charAt(i); 504 switch (ch) { 505 case '"': 506 b.append('b'); 507 break; 508 case '\\': 509 b.append('\\'); 510 break; 511 case '/': 512 b.append('/'); 513 break; 514 case 'b': 515 b.append('\b'); 516 break; 517 case 'f': 518 b.append('\f'); 519 break; 520 case 'n': 521 b.append('\n'); 522 break; 523 case 'r': 524 b.append('\r'); 525 break; 526 case 't': 527 b.append('\t'); 528 break; 529 case 'u': 530 String hex = json.substring(i + 1, i + 5); 531 b.append((char) Integer.parseInt(hex, 16)); 532 break; 533 default: 534 throw new FHIRException("Unknown JSON escape \\" + ch); 535 } 536 } else 537 b.append(json.charAt(i)); 538 i++; 539 } 540 return b.toString(); 541 } 542 543 544 public static boolean isPlural(String word) { 545 word = word.toLowerCase(); 546 if ("restricts".equals(word) || "contains".equals(word) || "data".equals(word) || "specimen".equals(word) || "replaces".equals(word) || "addresses".equals(word) 547 || "supplementalData".equals(word) || "instantiates".equals(word) || "imports".equals(word)) 548 return false; 549 Inflector inf = new Inflector(); 550 return !inf.singularize(word).equals(word); 551 } 552 553 554 public static String padRight(String src, char c, int len) { 555 StringBuilder s = new StringBuilder(); 556 s.append(src); 557 for (int i = 0; i < len - src.length(); i++) 558 s.append(c); 559 return s.toString(); 560 } 561 562 563 public static String padLeft(String src, char c, int len) { 564 StringBuilder s = new StringBuilder(); 565 for (int i = 0; i < len - src.length(); i++) 566 s.append(c); 567 s.append(src); 568 return s.toString(); 569 } 570 571 572 public static String path(String... args) throws IOException { 573 StringBuilder s = new StringBuilder(); 574 boolean d = false; 575 boolean first = true; 576 for (String arg : args) { 577 if (first && arg == null) 578 continue; 579 first = false; 580 if (!d) 581 d = !noString(arg); 582 else if (!s.toString().endsWith(File.separator)) 583 s.append(File.separator); 584 String a = arg; 585 if (s.length() == 0) { 586 if ("[tmp]".equals(a)) { 587 if (hasCTempDir()) { 588 a = "c:\\temp"; 589 } else { 590 a = System.getProperty("java.io.tmpdir"); 591 } 592 } else if ("[user]".equals(a)) { 593 a = System.getProperty("user.home"); 594 } else if (a.startsWith("[") && a.endsWith("]")) { 595 String ev = System.getenv(a.replace("[", "").replace("]", "")); 596 if (ev != null) { 597 a = ev; 598 } else { 599 a = "null"; 600 } 601 } 602 } 603 a = a.replace("\\", File.separator); 604 a = a.replace("/", File.separator); 605 if (s.length() > 0 && a.startsWith(File.separator)) 606 a = a.substring(File.separator.length()); 607 608 while (a.startsWith(".." + File.separator)) { 609 if (s.length() == 0) { 610 s = new StringBuilder(Paths.get(".").toAbsolutePath().normalize().toString()); 611 } else { 612 String p = s.toString().substring(0, s.length() - 1); 613 if (!p.contains(File.separator)) { 614 s = new StringBuilder(); 615 } else { 616 s = new StringBuilder(p.substring(0, p.lastIndexOf(File.separator)) + File.separator); 617 } 618 } 619 a = a.substring(3); 620 } 621 if ("..".equals(a)) { 622 int i = s.substring(0, s.length() - 1).lastIndexOf(File.separator); 623 s = new StringBuilder(s.substring(0, i + 1)); 624 } else 625 s.append(a); 626 } 627 return s.toString(); 628 } 629 630 private static boolean hasCTempDir() { 631 if (!System.getProperty("os.name").toLowerCase().contains("win")) { 632 return false; 633 } 634 File tmp = new File("c:\\temp"); 635 return tmp.exists() && tmp.isDirectory(); 636 } 637 638 public static String pathURL(String... args) { 639 StringBuilder s = new StringBuilder(); 640 boolean d = false; 641 for (String arg : args) { 642 if (!d) 643 d = !noString(arg); 644 else if (!s.toString().endsWith("/") && !arg.startsWith("/")) 645 s.append("/"); 646 s.append(arg); 647 } 648 return s.toString(); 649 } 650 651 652// public static void checkCase(String filename) { 653// File f = new CSFile(filename); 654// if (!f.getName().equals(filename)) 655// throw new FHIRException("Filename ") 656// 657// } 658 659 public static String nmtokenize(String cs) { 660 if (cs == null) 661 return ""; 662 StringBuilder s = new StringBuilder(); 663 for (int i = 0; i < cs.length(); i++) { 664 char c = cs.charAt(i); 665 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_') 666 s.append(c); 667 else if (c != ' ') 668 s.append("." + Integer.toString(c)); 669 } 670 return s.toString(); 671 } 672 673 674 public static boolean isToken(String tail) { 675 if (tail == null || tail.length() == 0) 676 return false; 677 boolean result = isAlphabetic(tail.charAt(0)); 678 for (int i = 1; i < tail.length(); i++) { 679 result = result && (isAlphabetic(tail.charAt(i)) || isDigit(tail.charAt(i)) || (tail.charAt(i) == '_') || (tail.charAt(i) == '[') || (tail.charAt(i) == ']')); 680 } 681 return result; 682 } 683 684 685 public static boolean isDigit(char c) { 686 return (c >= '0') && (c <= '9'); 687 } 688 689 690 public static boolean isAlphabetic(char c) { 691 return ((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')); 692 } 693 694 695 public static String getDirectoryForFile(String filepath) { 696 File f = new File(filepath); 697 return f.getParent(); 698 } 699 700 public static String appendPeriod(String s) { 701 if (Utilities.noString(s)) 702 return s; 703 s = s.trim(); 704 if (s.endsWith(".") || s.endsWith("?")) 705 return s; 706 return s + "."; 707 } 708 709 710 public static String removePeriod(String s) { 711 if (Utilities.noString(s)) 712 return s; 713 if (s.endsWith(".")) 714 return s.substring(0, s.length() - 1); 715 return s; 716 } 717 718 719 public static String stripBOM(String string) { 720 return string.replace("\uFEFF", ""); 721 } 722 723 724 public static String oidTail(String id) { 725 if (id == null || !id.contains(".")) 726 return id; 727 return id.substring(id.lastIndexOf(".") + 1); 728 } 729 730 731 public static String oidRoot(String id) { 732 if (id == null || !id.contains(".")) 733 return id; 734 return id.substring(0, id.indexOf(".")); 735 } 736 737 public static String escapeJava(String doco) { 738 if (doco == null) 739 return ""; 740 741 StringBuilder b = new StringBuilder(); 742 for (char c : doco.toCharArray()) { 743 if (c == '\r') 744 b.append("\\r"); 745 else if (c == '\n') 746 b.append("\\n"); 747 else if (c == '"') 748 b.append("\\\""); 749 else if (c == '\\') 750 b.append("\\\\"); 751 else 752 b.append(c); 753 } 754 return b.toString(); 755 } 756 757 758 public static String[] splitByCamelCase(String name) { 759 List<String> parts = new ArrayList<String>(); 760 StringBuilder b = new StringBuilder(); 761 for (int i = 0; i < name.length(); i++) { 762 if (i > 0 && Character.isUpperCase(name.charAt(i))) { 763 parts.add(b.toString()); 764 b = new StringBuilder(); 765 } 766 b.append(Character.toLowerCase(name.charAt(i))); 767 } 768 parts.add(b.toString()); 769 return parts.toArray(new String[]{}); 770 } 771 772 773 public static String encodeUri(String v) { 774 return v.replace(" ", "%20").replace("?", "%3F").replace("=", "%3D"); 775 } 776 777 778 public static String normalize(String s) { 779 if (noString(s)) 780 return null; 781 StringBuilder b = new StringBuilder(); 782 boolean isWhitespace = false; 783 for (int i = 0; i < s.length(); i++) { 784 char c = s.charAt(i); 785 if (!Character.isWhitespace(c)) { 786 b.append(Character.toLowerCase(c)); 787 isWhitespace = false; 788 } else if (!isWhitespace) { 789 b.append(' '); 790 isWhitespace = true; 791 } 792 } 793 return b.toString().trim(); 794 } 795 796 public static String normalizeSameCase(String s) { 797 if (noString(s)) 798 return null; 799 StringBuilder b = new StringBuilder(); 800 boolean isWhitespace = false; 801 for (int i = 0; i < s.length(); i++) { 802 char c = s.charAt(i); 803 if (!Character.isWhitespace(c)) { 804 b.append(c); 805 isWhitespace = false; 806 } else if (!isWhitespace) { 807 b.append(' '); 808 isWhitespace = true; 809 } 810 } 811 return b.toString().trim(); 812 } 813 814 815 public static void copyFileToDirectory(File source, File destDir) throws IOException { 816 copyFile(source, new File(path(destDir.getAbsolutePath(), source.getName()))); 817 } 818 819 820 public static boolean isWhitespace(String s) { 821 boolean ok = true; 822 for (int i = 0; i < s.length(); i++) 823 ok = ok && Character.isWhitespace(s.charAt(i)); 824 return ok; 825 826 } 827 828 829 public static String URLEncode(String string) { 830 try { 831 return URLEncoder.encode(string, "UTF-8"); 832 } catch (UnsupportedEncodingException e) { 833 throw new Error(e.getMessage()); 834 } 835 } 836 837 838 public static String URLDecode(String ref) { 839 try { 840 return URLDecoder.decode(ref, "UTF-8"); 841 } catch (UnsupportedEncodingException e) { 842 throw new Error(e.getMessage()); 843 } 844 } 845 846 public static boolean charInSet(char value, char... array) { 847 for (int i : array) 848 if (value == i) 849 return true; 850 return false; 851 } 852 853 854 public static boolean charInRange(char ch, char a, char z) { 855 return ch >= a && ch <= z; 856 } 857 858 public static boolean existsInList(String value, List<String> array) { 859 if (value == null) 860 return false; 861 for (String s : array) 862 if (value.equals(s)) 863 return true; 864 return false; 865 } 866 867 public static boolean existsInList(String value, String... array) { 868 if (value == null) 869 return false; 870 for (String s : array) 871 if (value.equals(s)) 872 return true; 873 return false; 874 } 875 876 public static boolean existsInList(int value, int... array) { 877 for (int i : array) 878 if (value == i) 879 return true; 880 return false; 881 } 882 883 public static boolean existsInListNC(String value, String... array) { 884 for (String s : array) 885 if (value.equalsIgnoreCase(s)) 886 return true; 887 return false; 888 } 889 890 891 public static String getFileNameForName(String name) { 892 return name.toLowerCase(); 893 } 894 895 public static void deleteTempFiles() throws IOException { 896 File file = createTempFile("test", "test"); 897 String folder = getDirectoryForFile(file.getAbsolutePath()); 898 String[] list = new File(folder).list(new FilenameFilter() { 899 public boolean accept(File dir, String name) { 900 return name.startsWith("ohfu-"); 901 } 902 }); 903 if (list != null) { 904 for (String n : list) { 905 new File(path(folder, n)).delete(); 906 } 907 } 908 } 909 910 public static File createTempFile(String prefix, String suffix) throws IOException { 911 // this allows use to eaily identify all our dtemp files and delete them, since delete on Exit doesn't really work. 912 File file = File.createTempFile("ohfu-" + prefix, suffix); 913 file.deleteOnExit(); 914 return file; 915 } 916 917 918 public static boolean isAsciiChar(char ch) { 919 return ch >= ' ' && ch <= '~'; 920 } 921 922 923 public static String makeUuidLC() { 924 return UUID.randomUUID().toString().toLowerCase(); 925 } 926 927 public static String makeUuidUrn() { 928 return "urn:uuid:" + UUID.randomUUID().toString().toLowerCase(); 929 } 930 931 public static boolean isURL(String s) { 932 boolean ok = s.matches("^http(s{0,1})://[a-zA-Z0-9_/\\-\\.]+\\.([A-Za-z/]{2,5})[a-zA-Z0-9_/\\&\\?\\=\\-\\.\\~\\%]*"); 933 return ok; 934 } 935 936 937 public static String escapeJson(String value) { 938 if (value == null) 939 return ""; 940 941 StringBuilder b = new StringBuilder(); 942 for (char c : value.toCharArray()) { 943 if (c == '\r') 944 b.append("\\r"); 945 else if (c == '\n') 946 b.append("\\n"); 947 else if (c == '\t') 948 b.append("\\t"); 949 else if (c == '"') 950 b.append("\\\""); 951 else if (c == '\\') 952 b.append("\\\\"); 953 else if (((int) c) < 32) 954 b.append("\\u" + Utilities.padLeft(String.valueOf((int) c), '0', 4)); 955 else 956 b.append(c); 957 } 958 return b.toString(); 959 } 960 961 public static String humanize(String code) { 962 StringBuilder b = new StringBuilder(); 963 boolean lastBreak = true; 964 for (char c : code.toCharArray()) { 965 if (Character.isLetter(c)) { 966 if (lastBreak) 967 b.append(Character.toUpperCase(c)); 968 else { 969 if (Character.isUpperCase(c)) 970 b.append(" "); 971 b.append(c); 972 } 973 lastBreak = false; 974 } else { 975 b.append(" "); 976 lastBreak = true; 977 } 978 } 979 if (b.length() == 0) 980 return code; 981 else 982 return b.toString(); 983 } 984 985 986 public static String uncapitalize(String s) { 987 if (s == null) return null; 988 if (s.length() == 0) return s; 989 if (s.length() == 1) return s.toLowerCase(); 990 991 return s.substring(0, 1).toLowerCase() + s.substring(1); 992 } 993 994 995 public static int charCount(String s, char c) { 996 int res = 0; 997 for (char ch : s.toCharArray()) 998 if (ch == c) 999 res++; 1000 return res; 1001 } 1002 1003 1004 public static boolean isOid(String cc) { 1005 return cc.matches(OID_REGEX) && cc.lastIndexOf('.') >= 5; 1006 } 1007 1008 1009 public static boolean equals(String one, String two) { 1010 if (one == null && two == null) 1011 return true; 1012 if (one == null || two == null) 1013 return false; 1014 return one.equals(two); 1015 } 1016 1017 1018 public static void deleteAllFiles(String folder, String type) { 1019 File src = new File(folder); 1020 String[] files = src.list(); 1021 for (String f : files) { 1022 if (new File(folder + File.separator + f).isDirectory()) { 1023 deleteAllFiles(folder + File.separator + f, type); 1024 } else if (f.endsWith(type)) { 1025 new File(folder + File.separator + f).delete(); 1026 } 1027 } 1028 1029 } 1030 1031 public static boolean compareIgnoreWhitespace(File f1, File f2) throws IOException { 1032 InputStream in1 = null; 1033 InputStream in2 = null; 1034 try { 1035 in1 = new BufferedInputStream(new FileInputStream(f1)); 1036 in2 = new BufferedInputStream(new FileInputStream(f2)); 1037 1038 int expectedByte = in1.read(); 1039 while (expectedByte != -1) { 1040 boolean w1 = isWhitespace(expectedByte); 1041 if (w1) 1042 while (isWhitespace(expectedByte)) 1043 expectedByte = in1.read(); 1044 int foundByte = in2.read(); 1045 if (w1) { 1046 if (!isWhitespace(foundByte)) 1047 return false; 1048 while (isWhitespace(foundByte)) 1049 foundByte = in2.read(); 1050 } 1051 if (expectedByte != foundByte) 1052 return false; 1053 expectedByte = in1.read(); 1054 } 1055 if (in2.read() != -1) { 1056 return false; 1057 } 1058 return true; 1059 } finally { 1060 if (in1 != null) { 1061 try { 1062 in1.close(); 1063 } catch (IOException e) { 1064 } 1065 } 1066 if (in2 != null) { 1067 try { 1068 in2.close(); 1069 } catch (IOException e) { 1070 } 1071 } 1072 } 1073 } 1074 1075 private static boolean isWhitespace(int b) { 1076 return b == 9 || b == 10 || b == 13 || b == 32; 1077 } 1078 1079 1080 public static boolean compareIgnoreWhitespace(String fn1, String fn2) throws IOException { 1081 return compareIgnoreWhitespace(new File(fn1), new File(fn2)); 1082 } 1083 1084 1085 public static boolean isAbsoluteUrl(String ref) { 1086 return ref != null && (ref.startsWith("http:") || ref.startsWith("https:") || ref.startsWith("urn:uuid:") || ref.startsWith("urn:oid:")); 1087 } 1088 1089 1090 public static boolean equivalent(String l, String r) { 1091 if (Utilities.noString(l) && Utilities.noString(r)) 1092 return true; 1093 if (Utilities.noString(l) || Utilities.noString(r)) 1094 return false; 1095 return l.toLowerCase().equals(r.toLowerCase()); 1096 } 1097 1098 1099 public static boolean equivalentNumber(String l, String r) { 1100 if (Utilities.noString(l) && Utilities.noString(r)) 1101 return true; 1102 if (Utilities.noString(l) || Utilities.noString(r)) 1103 return false; 1104 l = l.toLowerCase().trim(); 1105 r = r.toLowerCase().trim(); // not that this should make any difference 1106 return l.startsWith(r) || r.startsWith(l); 1107 } 1108 1109 1110 public static String getFileExtension(String fn) { 1111 return fn.contains(".") ? fn.substring(fn.lastIndexOf(".") + 1) : ""; 1112 } 1113 1114 1115 public static String unCamelCase(String name) { 1116 StringBuilder b = new StringBuilder(); 1117 boolean first = true; 1118 for (char c : name.toCharArray()) { 1119 if (Character.isUpperCase(c)) { 1120 if (!first) 1121 b.append(" "); 1122 b.append(Character.toLowerCase(c)); 1123 } else 1124 b.append(c); 1125 first = false; 1126 } 1127 return b.toString(); 1128 } 1129 1130 1131 public static boolean isAbsoluteFileName(String source) { 1132 if (isWindows()) 1133 return (source.length() > 2 && source.charAt(1) == ':') || source.startsWith("\\\\"); 1134 else 1135 return source.startsWith("//"); 1136 } 1137 1138 1139 public static boolean isWindows() { 1140 return System.getProperty("os.name").startsWith("Windows"); 1141 } 1142 1143 1144 public static String splitLineForLength(String line, int prefixLength, int indent, int allowedLength) { 1145 List<String> list = new ArrayList<String>(); 1146 while (prefixLength + line.length() > allowedLength) { 1147 int i = allowedLength - (list.size() == 0 ? prefixLength : indent); 1148 while (i > 0 && line.charAt(i) != ' ') 1149 i--; 1150 if (i == 0) 1151 break; 1152 list.add(line.substring(0, i)); 1153 line = line.substring(i + 1); 1154 } 1155 list.add(line); 1156 StringBuilder b = new StringBuilder(); 1157 boolean first = true; 1158 for (String s : list) { 1159 if (first) 1160 first = false; 1161 else 1162 b.append("\r\n" + padLeft("", ' ', indent)); 1163 b.append(s); 1164 } 1165 return b.toString(); 1166 } 1167 1168 1169 public static int countFilesInDirectory(String dirName) { 1170 File dir = new File(dirName); 1171 if (dir.exists() == false) { 1172 return 0; 1173 } 1174 int i = 0; 1175 for (File f : dir.listFiles()) 1176 if (!f.isDirectory()) 1177 i++; 1178 return i; 1179 } 1180 1181 public static String makeId(String name) { 1182 StringBuilder b = new StringBuilder(); 1183 for (char ch : name.toCharArray()) { 1184 if (ch >= 'a' && ch <= 'z') 1185 b.append(ch); 1186 else if (ch >= 'A' && ch <= 'Z') 1187 b.append(ch); 1188 else if (ch >= '0' && ch <= '9') 1189 b.append(ch); 1190 else if (ch == '-' || ch == '.') 1191 b.append(ch); 1192 } 1193 return b.toString(); 1194 } 1195 1196 public interface FileVisitor { 1197 void visitFile(File file) throws FileNotFoundException, IOException; 1198 } 1199 1200 public static void visitFiles(String folder, String extension, FileVisitor visitor) throws FileNotFoundException, IOException { 1201 visitFiles(new File(folder), extension, visitor); 1202 } 1203 1204 public static void visitFiles(File folder, String extension, FileVisitor visitor) throws FileNotFoundException, IOException { 1205 for (File file : folder.listFiles()) { 1206 if (file.isDirectory()) 1207 visitFiles(file, extension, visitor); 1208 else if (extension == null || file.getName().endsWith(extension)) 1209 visitor.visitFile(file); 1210 } 1211 } 1212 1213 public static String extractBaseUrl(String url) { 1214 if (url == null) 1215 return null; 1216 else if (url.contains("/")) 1217 return url.substring(0, url.lastIndexOf("/")); 1218 else 1219 return url; 1220 } 1221 1222 public static String listCanonicalUrls(Set<String> keys) { 1223 return keys.toString(); 1224 } 1225 1226 public static boolean isValidId(String id) { 1227 return id.matches("[A-Za-z0-9\\-\\.]{1,64}"); 1228 } 1229 1230 public static List<String> sorted(Set<String> set) { 1231 List<String> list = new ArrayList<>(); 1232 list.addAll(set); 1233 Collections.sort(list); 1234 return list; 1235 } 1236 1237 public static void analyseStringDiffs(Set<String> source, Set<String> target, Set<String> missed, Set<String> extra) { 1238 for (String s : source) 1239 if (!target.contains(s)) 1240 missed.add(s); 1241 for (String s : target) 1242 if (!source.contains(s)) 1243 extra.add(s); 1244 1245 } 1246 1247 /** 1248 * Only handles simple FHIRPath expressions of the type produced by the validator 1249 * 1250 * @param path 1251 * @return 1252 */ 1253 public static String fhirPathToXPath(String path) { 1254 String[] p = path.split("\\."); 1255 CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder("."); 1256 int i = 0; 1257 while (i < p.length) { 1258 String s = p[i]; 1259 if (s.contains("[")) { 1260 String si = s.substring(s.indexOf("[") + 1, s.length() - 1); 1261 if (!Utilities.isInteger(si)) 1262 throw new FHIRException("The FHIRPath expression '" + path + "' is not valid"); 1263 s = s.substring(0, s.indexOf("[")) + "[" + Integer.toString(Integer.parseInt(si) + 1) + "]"; 1264 } 1265 if (i < p.length - 1 && p[i + 1].startsWith(".ofType(")) { 1266 i++; 1267 s = s + capitalize(p[i].substring(8, p.length - 1)); 1268 } 1269 b.append(s); 1270 i++; 1271 } 1272 return b.toString(); 1273 } 1274 1275 public static String describeDuration(Duration d) { 1276 if (d.toDays() > 2) { 1277 return String.format("%s days", d.toDays()); 1278 } else if (d.toHours() > 2) { 1279 return String.format("%s hours", d.toHours()); 1280 } else if (d.toMinutes() > 2) { 1281 return String.format("%s mins", d.toMinutes()); 1282 } else { 1283 return String.format("%s ms", d.toMillis()); 1284 } 1285 } 1286 1287 public static boolean startsWithInList(String s, String... list) { 1288 if (s == null) { 1289 return false; 1290 } 1291 for (String l : list) { 1292 if (s.startsWith(l)) { 1293 return true; 1294 } 1295 } 1296 return false; 1297 } 1298 1299 public static boolean startsWithInList(String s, Collection<String> list) { 1300 if (s == null) { 1301 return false; 1302 } 1303 for (String l : list) { 1304 if (s.startsWith(l)) { 1305 return true; 1306 } 1307 } 1308 return false; 1309 } 1310 1311 public static final int ONE_MB = 1024; 1312 public static final String GB = "Gb"; 1313 public static final String MB = "Mb"; 1314 public static final String KB = "Kb"; 1315 public static final String BT = "b"; 1316 1317 public static String describeSize(int length) { 1318 if (length < 0) throw new IllegalArgumentException("File length of < 0 passed in..."); 1319 1320 if (length > Math.pow(ONE_MB, 3)) { 1321 return length / ((long) Math.pow(ONE_MB, 3)) + GB; 1322 } 1323 if (length > Math.pow(ONE_MB, 2)) { 1324 return length / ((long) Math.pow(ONE_MB, 2)) + MB; 1325 } 1326 if (length > ONE_MB) { 1327 return length / (ONE_MB) + KB; 1328 } 1329 return length + BT; 1330 } 1331}