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.FileInputStream; 008import java.io.FileNotFoundException; 009import java.io.FileOutputStream; 010import java.io.FilenameFilter; 011import java.io.IOException; 012import java.io.InputStream; 013import java.io.UnsupportedEncodingException; 014import java.math.BigDecimal; 015import java.math.RoundingMode; 016import java.net.URI; 017import java.net.URLDecoder; 018import java.net.URLEncoder; 019import java.nio.file.Files; 020import java.nio.file.Path; 021import java.nio.file.StandardCopyOption; 022import java.time.Duration; 023import java.util.ArrayList; 024import java.util.Arrays; 025import java.util.Collection; 026import java.util.Collections; 027import java.util.Comparator; 028import java.util.LinkedList; 029import java.util.List; 030import java.util.Set; 031import java.util.UUID; 032import java.util.zip.ZipEntry; 033import java.util.zip.ZipInputStream; 034 035import javax.annotation.Nullable; 036 037/* 038 Copyright (c) 2011+, HL7, Inc. 039 All rights reserved. 040 041 Redistribution and use in source and binary forms, with or without modification, 042 are permitted provided that the following conditions are met: 043 044 * Redistributions of source code must retain the above copyright notice, this 045 list of conditions and the following disclaimer. 046 * Redistributions in binary form must reproduce the above copyright notice, 047 this list of conditions and the following disclaimer in the documentation 048 and/or other materials provided with the distribution. 049 * Neither the name of HL7 nor the names of its contributors may be used to 050 endorse or promote products derived from this software without specific 051 prior written permission. 052 053 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 054 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 055 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 056 IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 057 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 058 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 059 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 060 WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 061 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 062 POSSIBILITY OF SUCH DAMAGE. 063 064 */ 065 066 067import org.apache.commons.io.FileUtils; 068import org.hl7.fhir.exceptions.FHIRException; 069import org.hl7.fhir.utilities.FileNotifier.FileNotifier2; 070import org.hl7.fhir.utilities.Utilities.CaseInsensitiveSorter; 071import org.hl7.fhir.utilities.filesystem.CSFile; 072import org.hl7.fhir.utilities.filesystem.ManagedFileAccess; 073import org.hl7.fhir.utilities.settings.FhirSettings; 074 075public class Utilities { 076 077 private static final String UUID_REGEX = "[0-9a-f]{8}\\-[0-9a-f]{4}\\-[0-9a-f]{4}\\-[0-9a-f]{4}\\-[0-9a-f]{12}"; 078 private static final String OID_REGEX = "[0-2](\\.(0|[1-9][0-9]*))+"; 079 static final String C_TEMP_DIR = "c:\\temp"; 080 081 /** 082 * Returns the plural form of the word in the string. 083 * <p> 084 * Examples: 085 * 086 * <pre> 087 * inflector.pluralize("post") #=> "posts" 088 * inflector.pluralize("octopus") #=> "octopi" 089 * inflector.pluralize("sheep") #=> "sheep" 090 * inflector.pluralize("words") #=> "words" 091 * inflector.pluralize("the blue mailman") #=> "the blue mailmen" 092 * inflector.pluralize("CamelOctopus") #=> "CamelOctopi" 093 * </pre> 094 * <p> 095 * <p> 096 * <p> 097 * Note that if the {@link Object#toString()} is called on the supplied object, so this method works for non-strings, too. 098 * 099 * @param word the word that is to be pluralized. 100 * @return the pluralized form of the word, or the word itself if it could not be pluralized 101 * @see Inflector#singularize(Object) 102 */ 103 public static String pluralizeMe(String word) { 104 Inflector inf = new Inflector(); 105 return inf.pluralize(word); 106 } 107 108 public static String pluralize(String word, int count) { 109 if (count == 1) 110 return word; 111 Inflector inf = new Inflector(); 112 return inf.pluralize(word); 113 } 114 115 public static String singularise(String word) { 116 Inflector inf = new Inflector(); 117 return inf.singularize(word); 118 } 119 120 121 public static boolean isInteger(String string) { 122 if (isBlank(string)) { 123 return false; 124 } 125 String value = string.startsWith("-") ? string.substring(1) : string; 126 if (Utilities.noString(value)) { 127 return false; 128 } 129 for (char next : value.toCharArray()) { 130 if (!Character.isDigit(next)) { 131 return false; 132 } 133 } 134 // check bounds -2,147,483,648..2,147,483,647 135 if (value.length() > 10) 136 return false; 137 if (string.startsWith("-")) { 138 if (value.length() == 10 && string.compareTo("2147483648") > 0) 139 return false; 140 } else { 141 if (value.length() == 10 && string.compareTo("2147483647") > 0) 142 return false; 143 } 144 return true; 145 } 146 147 public static boolean isLong(String string) { 148 if (isBlank(string)) { 149 return false; 150 } 151 String value = string.startsWith("-") ? string.substring(1) : string; 152 for (char next : value.toCharArray()) { 153 if (!Character.isDigit(next)) { 154 return false; 155 } 156 } 157 // check bounds -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 158 if (value.length() > 20) 159 return false; 160 if (string.startsWith("-")) { 161 if (value.length() == 20 && string.compareTo("9223372036854775808") > 0) 162 return false; 163 } else { 164 if (value.length() == 20 && string.compareTo("9223372036854775807") > 0) 165 return false; 166 } 167 return true; 168 } 169 170 public static boolean isHex(String string) { 171 try { 172 int i = Integer.parseInt(string, 16); 173 return i != i + 1; 174 } catch (Exception e) { 175 return false; 176 } 177 } 178 179 public enum DecimalStatus { 180 BLANK, SYNTAX, RANGE, OK 181 } 182 183 public static boolean isDecimal(String value, boolean allowExponent, boolean allowLeadingZero) { 184 DecimalStatus ds = checkDecimal(value, allowExponent, true); 185 return ds == DecimalStatus.OK || ds == DecimalStatus.RANGE; 186 } 187 188 public static boolean isDecimal(String value, boolean allowExponent) { 189 DecimalStatus ds = checkDecimal(value, allowExponent, false); 190 return ds == DecimalStatus.OK || ds == DecimalStatus.RANGE; 191 } 192 193 public static DecimalStatus checkDecimal(String value, boolean allowExponent, boolean allowLeadingZero) { 194 if (isBlank(value)) { 195 return DecimalStatus.BLANK; 196 } 197 198 // check for leading zeros 199 if (!allowLeadingZero) { 200 if (value.startsWith("0") && !"0".equals(value) && !value.startsWith("0.")) 201 return DecimalStatus.SYNTAX; 202 if (value.startsWith("-0") && !"-0".equals(value) && !value.startsWith("-0.")) 203 return DecimalStatus.SYNTAX; 204 if (value.startsWith("+0") && !"+0".equals(value) && !value.startsWith("+0.")) 205 return DecimalStatus.SYNTAX; 206 } 207 208 // check for trailing dot 209 if (value.endsWith(".")) { 210 return DecimalStatus.SYNTAX; 211 } 212 213 boolean havePeriod = false; 214 boolean haveExponent = false; 215 boolean haveSign = false; 216 boolean haveDigits = false; 217 int preDecLength = 0; 218 int postDecLength = 0; 219 int exponentLength = 0; 220 int length = 0; 221 for (char next : value.toCharArray()) { 222 if (next == '.') { 223 if (!haveDigits || havePeriod || haveExponent) 224 return DecimalStatus.SYNTAX; 225 havePeriod = true; 226 preDecLength = length; 227 length = 0; 228 } else if (next == '-' || next == '+') { 229 if (haveDigits || haveSign) 230 return DecimalStatus.SYNTAX; 231 haveSign = true; 232 } else if (next == 'e' || next == 'E') { 233 if (!haveDigits || haveExponent || !allowExponent) 234 return DecimalStatus.SYNTAX; 235 haveExponent = true; 236 haveSign = false; 237 haveDigits = false; 238 if (havePeriod) 239 postDecLength = length; 240 else 241 preDecLength = length; 242 length = 0; 243 } else if (!Character.isDigit(next)) { 244 return DecimalStatus.SYNTAX; 245 } else { 246 haveDigits = true; 247 length++; 248 } 249 } 250 if (haveExponent && !haveDigits) 251 return DecimalStatus.SYNTAX; 252 if (haveExponent) 253 exponentLength = length; 254 else if (havePeriod) 255 postDecLength = length; 256 else 257 preDecLength = length; 258 259 // now, bounds checking - these are arbitrary 260 if (exponentLength > 4) 261 return DecimalStatus.RANGE; 262 if (preDecLength + postDecLength > 18) 263 return DecimalStatus.RANGE; 264 265 return DecimalStatus.OK; 266 } 267 268 public static String camelCase(String value) { 269 return new Inflector().camelCase(value.trim().replace(" ", "_"), false); 270 } 271 272 public static String upperCamelCase(String value) { 273 return new Inflector().upperCamelCase(value.trim().replace(" ", "_")); 274 } 275 276 public static String escapeXml(String doco) { 277 if (doco == null) 278 return ""; 279 280 StringBuilder b = new StringBuilder(); 281 for (char c : doco.toCharArray()) { 282 if (c == '<') 283 b.append("<"); 284 else if (c == '>') 285 b.append(">"); 286 else if (c == '&') 287 b.append("&"); 288 else if (c == '"') 289 b.append("""); 290 else 291 b.append(c); 292 } 293 return b.toString(); 294 } 295 296 public static String titleize(String s) { 297 StringBuilder b = new StringBuilder(); 298 boolean up = true; 299 for (char c : s.toCharArray()) { 300 if (up) 301 b.append(Character.toUpperCase(c)); 302 else 303 b.append(c); 304 up = c == ' '; 305 } 306 return b.toString(); 307 } 308 309 public static String capitalize(String s) { 310 if (s == null) return null; 311 if (s.length() == 0) return s; 312 if (s.length() == 1) return s.toUpperCase(); 313 314 return s.substring(0, 1).toUpperCase() + s.substring(1); 315 } 316 317 public static void copyDirectory(String sourceFolder, String destFolder, FileNotifier notifier) throws IOException, FHIRException { 318 CSFile src = ManagedFileAccess.csfile(sourceFolder); 319 if (!src.exists()) 320 throw new FHIRException("Folder " + sourceFolder + " not found"); 321 File dst = ManagedFileAccess.file(destFolder); 322 if(!dst.getCanonicalFile().getName().equals(dst.getName())) { 323 File tmp = ManagedFileAccess.file(destFolder+System.currentTimeMillis()); 324 if (!dst.renameTo(tmp)) { 325 throw new IOException("fixing case from "+dst.getCanonicalFile().getName()+" to "+tmp.getName()+" failed"); 326 } 327 if (!tmp.renameTo(dst)) { 328 throw new IOException("fixing case from "+tmp.getCanonicalFile().getName()+" to "+dst.getName()+" failed"); 329 } 330 } else if (!dst.exists()) { 331 createDirectory(destFolder); 332 } 333 334 String[] files = src.list(); 335 for (String f : files) { 336 if (ManagedFileAccess.csfile(sourceFolder + File.separator + f).isDirectory()) { 337 if (!f.startsWith(".")) { // ignore .git files... 338 copyDirectory(sourceFolder + File.separator + f, destFolder + File.separator + f, notifier); 339 } 340 } else { 341 if (notifier != null) 342 notifier.copyFile(sourceFolder + File.separator + f, destFolder + File.separator + f); 343 copyFile(ManagedFileAccess.csfile(sourceFolder + File.separator + f), new /*CS*/File(destFolder + File.separator + f)); // case doesn't have to match on the target 344 } 345 } 346 } 347 348 349 public static void copyDirectory2(String sourceFolder, String destFolder, FileNotifier2 notifier) throws IOException, FHIRException { 350 CSFile src = ManagedFileAccess.csfile(sourceFolder); 351 if (!src.exists()) 352 throw new FHIRException("Folder " + sourceFolder + " not found"); 353 createDirectory(destFolder); 354 355 String[] files = src.list(); 356 for (String f : files) { 357 if (ManagedFileAccess.csfile(sourceFolder + File.separator + f).isDirectory()) { 358 if (!f.startsWith(".")) { // ignore .git files... 359 boolean doCopy = notifier != null ? notifier.copyFolder(sourceFolder + File.separator + f, destFolder + File.separator + f) : true; 360 if (doCopy) { 361 copyDirectory2(sourceFolder + File.separator + f, destFolder + File.separator + f, notifier); 362 } 363 } 364 } else { 365 boolean doCopy = notifier != null ? notifier.copyFile(sourceFolder + File.separator + f, destFolder + File.separator + f) : true; 366 if (doCopy) { 367 copyFile(ManagedFileAccess.csfile(sourceFolder + File.separator + f), ManagedFileAccess.csfile(destFolder + File.separator + f)); 368 } 369 } 370 } 371 } 372 373 public static void copyFile(String source, String dest) throws IOException { 374 copyFile(ManagedFileAccess.file(source), ManagedFileAccess.file(dest)); 375 } 376 377 public static void copyFile(File sourceFile, File destFile) throws IOException { 378 if (!destFile.exists()) { 379 if (!ManagedFileAccess.csfile(destFile.getParent()).exists()) { 380 createDirectory(destFile.getParent()); 381 } 382 destFile.createNewFile(); 383 } else if (!destFile.getCanonicalFile().getName().equals(destFile.getName())) { 384 // case mismatch 385 destFile.delete(); 386 destFile.createNewFile(); 387 } 388 389 FileInputStream source = null; 390 FileOutputStream destination = null; 391 392 try { 393 source = ManagedFileAccess.inStream(sourceFile); 394 destination = ManagedFileAccess.outStream(destFile); 395 destination.getChannel().transferFrom(source.getChannel(), 0, source.getChannel().size()); 396 } finally { 397 if (source != null) { 398 source.close(); 399 } 400 if (destination != null) { 401 destination.close(); 402 } 403 } 404 } 405 406 public static boolean checkFolder(String dir, List<String> errors) 407 throws IOException { 408 if (!ManagedFileAccess.csfile(dir).exists()) { 409 errors.add("Unable to find directory " + dir); 410 return false; 411 } else { 412 return true; 413 } 414 } 415 416 public static boolean checkFile(String purpose, String dir, String file, List<String> errors) 417 throws IOException { 418 if (!ManagedFileAccess.csfile(dir + file).exists()) { 419 if (errors != null) 420 errors.add("Unable to find " + purpose + " file " + file + " in " + dir); 421 return false; 422 } else { 423 return true; 424 } 425 } 426 427 public static String asCSV(List<String> strings) { 428 StringBuilder s = new StringBuilder(); 429 boolean first = true; 430 for (String n : strings) { 431 if (!first) 432 s.append(","); 433 s.append(n); 434 first = false; 435 } 436 return s.toString(); 437 } 438 439 public static String asHtmlBr(String prefix, List<String> strings) { 440 StringBuilder s = new StringBuilder(); 441 boolean first = true; 442 for (String n : strings) { 443 if (!first) 444 s.append("<br/>"); 445 s.append(prefix); 446 s.append(n); 447 first = false; 448 } 449 return s.toString(); 450 } 451 452 public static void clearDirectory(String folder, String... exemptions) throws IOException { 453 File dir = ManagedFileAccess.file(folder); 454 if (dir.exists()) { 455 if (exemptions.length == 0) 456 FileUtils.cleanDirectory(dir); 457 else { 458 String[] files = ManagedFileAccess.csfile(folder).list(); 459 if (files != null) { 460 for (String f : files) { 461 if (!existsInList(f, exemptions)) { 462 File fh = ManagedFileAccess.csfile(folder + File.separatorChar + f); 463 if (fh.isDirectory()) 464 clearDirectory(fh.getAbsolutePath()); 465 fh.delete(); 466 } 467 } 468 } 469 } 470 } 471 } 472 473 public static File createDirectory(String path) throws IOException { 474 ManagedFileAccess.csfile(path).mkdirs(); 475 return ManagedFileAccess.file(path); 476 } 477 478 public static String changeFileExt(String name, String ext) { 479 if (name.lastIndexOf('.') > -1) 480 return name.substring(0, name.lastIndexOf('.')) + ext; 481 else 482 return name + ext; 483 } 484 485 public static String cleanupTextString(String contents) { 486 if (contents == null || contents.trim().equals("")) 487 return null; 488 else 489 return contents.trim(); 490 } 491 492 493 public static boolean noString(String v) { 494 return v == null || v.equals(""); 495 } 496 497 498 public static void bytesToFile(byte[] content, String filename) throws IOException { 499 FileOutputStream out = ManagedFileAccess.outStream(filename); 500 out.write(content); 501 out.close(); 502 503 } 504 505 506 public static String appendSlash(String definitions) { 507 return definitions.endsWith(File.separator) ? definitions : definitions + File.separator; 508 } 509 510 public static String appendForwardSlash(String definitions) { 511 if (definitions == null) { 512 return "/"; 513 } 514 return definitions.endsWith("/") ? definitions : definitions + "/"; 515 } 516 517 518 public static String fileTitle(String file) throws IOException { 519 if (file == null) 520 return null; 521 String s = ManagedFileAccess.file(file).getName(); 522 return s.indexOf(".") == -1 ? s : s.substring(0, s.indexOf(".")); 523 } 524 525 526 public static String systemEol() { 527 return System.getProperty("line.separator"); 528 } 529 530 public static String normaliseEolns(String value) { 531 return value.replace("\r\n", "\r").replace("\n", "\r").replace("\r", "\r\n"); 532 } 533 534 public static String unescapeXml(String xml) throws FHIRException { 535 if (xml == null) 536 return null; 537 538 StringBuilder b = new StringBuilder(); 539 int i = 0; 540 while (i < xml.length()) { 541 if (xml.charAt(i) == '&') { 542 StringBuilder e = new StringBuilder(); 543 i++; 544 while (xml.charAt(i) != ';') { 545 e.append(xml.charAt(i)); 546 i++; 547 } 548 if (e.toString().equals("lt")) 549 b.append("<"); 550 else if (e.toString().equals("gt")) 551 b.append(">"); 552 else if (e.toString().equals("amp")) 553 b.append("&"); 554 else if (e.toString().equals("quot")) 555 b.append("\""); 556 else if (e.toString().equals("mu")) 557 b.append((char) 956); 558 else 559 throw new FHIRException("unknown XML entity \"" + e.toString() + "\""); 560 } else 561 b.append(xml.charAt(i)); 562 i++; 563 } 564 return b.toString(); 565 } 566 567 568 569 public static String unescapeJson(String json) throws FHIRException { 570 if (json == null) 571 return null; 572 573 StringBuilder b = new StringBuilder(); 574 int i = 0; 575 while (i < json.length()) { 576 if (json.charAt(i) == '\\') { 577 i++; 578 char ch = json.charAt(i); 579 switch (ch) { 580 case '"': 581 b.append('b'); 582 break; 583 case '\\': 584 b.append('\\'); 585 break; 586 case '/': 587 b.append('/'); 588 break; 589 case 'b': 590 b.append('\b'); 591 break; 592 case 'f': 593 b.append('\f'); 594 break; 595 case 'n': 596 b.append('\n'); 597 break; 598 case 'r': 599 b.append('\r'); 600 break; 601 case 't': 602 b.append('\t'); 603 break; 604 case 'u': 605 String hex = json.substring(i + 1, i + 5); 606 b.append(Character.toString(Integer.parseInt(hex, 16))); 607 break; 608 default: 609 throw new FHIRException("Unknown JSON escape \\" + ch); 610 } 611 } else 612 b.append(json.charAt(i)); 613 i++; 614 } 615 return b.toString(); 616 } 617 618 619 public static boolean isPlural(String word) { 620 word = word.toLowerCase(); 621 if ("restricts".equals(word) || "contains".equals(word) || "data".equals(word) || "specimen".equals(word) || "replaces".equals(word) || "addresses".equals(word) 622 || "supplementalData".equals(word) || "instantiates".equals(word) || "imports".equals(word) || "covers".equals(word)) 623 return false; 624 Inflector inf = new Inflector(); 625 return !inf.singularize(word).equals(word); 626 } 627 628 629 public static String padRight(String src, char c, int len) { 630 StringBuilder s = new StringBuilder(); 631 s.append(src); 632 for (int i = 0; i < len - src.length(); i++) 633 s.append(c); 634 return s.toString(); 635 } 636 637 638 public static String padLeft(String src, char c, int len) { 639 StringBuilder s = new StringBuilder(); 640 for (int i = 0; i < len - src.length(); i++) 641 s.append(c); 642 s.append(src); 643 return s.toString(); 644 } 645 646 /** 647 * Composes a path string using by concatenating the passed arguments. 648 * 649 * This method enables all checks for unintended path locations. 650 * 651 * @param args 652 * @return 653 * @throws IOException 654 * @see PathBuilder#buildPath(String...) 655 */ 656 public static String path(String... args) throws IOException { 657 return PathBuilder.getPathBuilder().buildPath(args); 658 } 659 660 public static File pathFile(String... args) throws IOException { 661 return ManagedFileAccess.file(PathBuilder.getPathBuilder().buildPath(args)); 662 } 663 664 public static String path(File f, String... args) throws IOException { 665 String[] a = new String[args.length+1]; 666 a[0] = f.getAbsolutePath(); 667 for (int i = 0; i < args.length; i++) { 668 a[i+1] = args[i]; 669 } 670 return PathBuilder.getPathBuilder().buildPath(a); 671 } 672 673 /** 674 * Composes a path string using by concatenating the passed arguments. 675 * 676 * This method does not check for unintentional access to areas of the file 677 * system outside of the first entry. ONLY USE THIS METHOD IN CASES WHERE YOU 678 * ARE CERTAIN THE COMPOSED PATH IS NOT MALICIOUS. 679 * 680 * @param args 681 * @return 682 * @throws IOException 683 * 684 * @see PathBuilder#buildPath(String...) 685 */ 686 @Deprecated 687 public static String uncheckedPath(String... args) throws IOException { 688 return PathBuilder.getPathBuilder() 689 .withRequireNonRootFirstEntry(false) 690 .withRequireNonNullNonEmptyFirstEntry(false) 691 .withRequirePathIsChildOfTarget(false) 692 .buildPath(args); 693 } 694 695 696 public static String pathURL(String... args) { 697 StringBuilder s = new StringBuilder(); 698 boolean d = false; 699 for (String arg : args) { 700 if (arg != null) { 701 if (!d) 702 d = !noString(arg); 703 else if (s.toString() != null && !s.toString().endsWith("/") && !arg.startsWith("/")) 704 s.append("/"); 705 s.append(arg); 706 } 707 } 708 return s.toString(); 709 } 710 711 public static String nmtokenize(String cs) { 712 if (cs == null) 713 return ""; 714 StringBuilder s = new StringBuilder(); 715 for (int i = 0; i < cs.length(); i++) { 716 char c = cs.charAt(i); 717 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_') 718 s.append(c); 719 else if (c != ' ') 720 s.append("." + Integer.toString(c)); 721 } 722 return s.toString(); 723 } 724 725 public static String javaTokenize(String cs, boolean capFirst) { 726 if (cs == null) 727 return ""; 728 StringBuilder s = new StringBuilder(); 729 boolean upcase = capFirst; 730 for (int i = 0; i < cs.length(); i++) { 731 char c = cs.charAt(i); 732 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_') { 733 if (upcase) { 734 s.append(Character.toUpperCase(c)); 735 upcase = false; 736 } else { 737 s.append(c); 738 } 739 } else { 740 upcase = true; 741 } 742 } 743 return s.toString(); 744 } 745 746 747 public static boolean isToken(String tail) { 748 if (tail == null || tail.length() == 0) 749 return false; 750 boolean result = isAlphabetic(tail.charAt(0)); 751 for (int i = 1; i < tail.length(); i++) { 752 result = result && (isAlphabetic(tail.charAt(i)) || isDigit(tail.charAt(i)) || (tail.charAt(i) == '_') || (tail.charAt(i) == '[') || (tail.charAt(i) == ']')); 753 } 754 return result; 755 } 756 757 public static boolean isTokenChar(char ch) { 758 return isAlphabetic(ch) || (ch == '_'); 759 } 760 761 public static boolean isDigit(char c) { 762 return (c >= '0') && (c <= '9'); 763 } 764 765 766 public static boolean isAlphabetic(char c) { 767 return ((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')); 768 } 769 770 771 public static String getDirectoryForFile(String filepath) throws IOException { 772 File f = ManagedFileAccess.file(filepath); 773 return f.getParent(); 774 } 775 776 public static String getDirectoryForURL(String url) { 777 return url.contains("/") && url.lastIndexOf("/") > 10 ? url.substring(0, url.lastIndexOf("/")) : url; 778 } 779 780 public static String appendPeriod(String s) { 781 if (Utilities.noString(s)) 782 return s; 783 s = s.trim(); 784 if (s.endsWith(".") || s.endsWith("?")) 785 return s; 786 return s + "."; 787 } 788 789 790 public static String removePeriod(String s) { 791 if (Utilities.noString(s)) 792 return s; 793 if (s.endsWith(".")) 794 return s.substring(0, s.length() - 1); 795 return s; 796 } 797 798 799 public static String stripBOM(String string) { 800 return string == null ? null : string.replace("\uFEFF", ""); 801 } 802 803 804 public static String oidTail(String id) { 805 if (id == null || !id.contains(".")) 806 return id; 807 return id.substring(id.lastIndexOf(".") + 1); 808 } 809 810 811 public static String oidRoot(String id) { 812 if (id == null || !id.contains(".")) 813 return id; 814 return id.substring(0, id.indexOf(".")); 815 } 816 817 public static String escapeJava(String doco) { 818 if (doco == null) 819 return ""; 820 821 StringBuilder b = new StringBuilder(); 822 for (char c : doco.toCharArray()) { 823 if (c == '\r') 824 b.append("\\r"); 825 else if (c == '\n') 826 b.append("\\n"); 827 else if (c == '"') 828 b.append("\\\""); 829 else if (c == '\\') 830 b.append("\\\\"); 831 else 832 b.append(c); 833 } 834 return b.toString(); 835 } 836 837 838 public static String[] splitByCamelCase(String name) { 839 List<String> parts = new ArrayList<String>(); 840 StringBuilder b = new StringBuilder(); 841 for (int i = 0; i < name.length(); i++) { 842 if (i > 0 && Character.isUpperCase(name.charAt(i))) { 843 parts.add(b.toString()); 844 b = new StringBuilder(); 845 } 846 b.append(Character.toLowerCase(name.charAt(i))); 847 } 848 parts.add(b.toString()); 849 return parts.toArray(new String[]{}); 850 } 851 852 853 public static String encodeUri(String v) { 854 return v.replace("%", "%25").replace(" ", "%20").replace("?", "%3F").replace("=", "%3D").replace("|", "%7C").replace("+", "%2B"); 855 } 856 857 858 public static String normalize(String s) { 859 if (noString(s)) 860 return null; 861 StringBuilder b = new StringBuilder(); 862 boolean isWhitespace = false; 863 for (int i = 0; i < s.length(); i++) { 864 char c = s.charAt(i); 865 if (!isWhitespace(c)) { 866 b.append(Character.toLowerCase(c)); 867 isWhitespace = false; 868 } else if (!isWhitespace) { 869 if (c == '\r' || c == '\n') { 870 b.append('\n'); 871 } else { 872 b.append(' '); 873 } 874 isWhitespace = true; 875 } 876 } 877 return b.toString().trim(); 878 } 879 880 public static String normalizeSameCase(String s) { 881 if (noString(s)) 882 return null; 883 StringBuilder b = new StringBuilder(); 884 boolean isWhitespace = false; 885 for (int i = 0; i < s.length(); i++) { 886 char c = s.charAt(i); 887 if (!Character.isWhitespace(c)) { 888 b.append(c); 889 isWhitespace = false; 890 } else if (!isWhitespace) { 891 b.append(' '); 892 isWhitespace = true; 893 } 894 } 895 return b.toString().trim(); 896 } 897 898 899 public static void copyFileToDirectory(File source, File destDir) throws IOException { 900 copyFile(source, ManagedFileAccess.file(path(destDir.getAbsolutePath(), source.getName()))); 901 } 902 903 904 public static String URLEncode(String string) { 905 try { 906 return URLEncoder.encode(string, "UTF-8"); 907 } catch (UnsupportedEncodingException e) { 908 throw new Error(e.getMessage()); 909 } 910 } 911 912 913 public static String URLDecode(String ref) { 914 try { 915 return URLDecoder.decode(ref, "UTF-8"); 916 } catch (UnsupportedEncodingException e) { 917 throw new Error(e.getMessage()); 918 } 919 } 920 921 public static boolean charInSet(char value, char... array) { 922 for (int i : array) 923 if (value == i) 924 return true; 925 return false; 926 } 927 928 929 public static boolean charInRange(char ch, char a, char z) { 930 return ch >= a && ch <= z; 931 } 932 933 public static boolean existsInList(String value, List<String> array) { 934 if (value == null) 935 return false; 936 for (String s : array) 937 if (value.equals(s)) 938 return true; 939 return false; 940 } 941 942 public static boolean containsInList(String value, String... array) { 943 if (value == null) 944 return false; 945 for (String s : array) 946 if (value.contains(s)) 947 return true; 948 return false; 949 } 950 951 public static boolean existsInList(String value, String... array) { 952 if (value == null) 953 return false; 954 for (String s : array) 955 if (value.equals(s)) 956 return true; 957 return false; 958 } 959 960 public static boolean existsInListTrimmed(String value, String... array) { 961 if (value == null) 962 return false; 963 for (String s : array) 964 if (value.equals(s.trim())) 965 return true; 966 return false; 967 } 968 969 public static boolean existsInList(int value, int... array) { 970 for (int i : array) 971 if (value == i) 972 return true; 973 return false; 974 } 975 976 public static boolean existsInListNC(String value, String... array) { 977 for (String s : array) 978 if (value.equalsIgnoreCase(s)) 979 return true; 980 return false; 981 } 982 983 public static String stringJoin(String sep, String... array) { 984 CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder(sep); 985 for (String s : array) 986 if (!noString(s)) 987 b.append(s); 988 return b.toString(); 989 } 990 991 992 public static String getFileNameForName(String name) { 993 return name.toLowerCase(); 994 } 995 996 public static void deleteTempFiles() throws IOException { 997 File file = createTempFile("test", "test"); 998 String folder = getDirectoryForFile(file.getAbsolutePath()); 999 String[] list = ManagedFileAccess.file(folder).list(new FilenameFilter() { 1000 public boolean accept(File dir, String name) { 1001 return name.startsWith("ohfu-"); 1002 } 1003 }); 1004 if (list != null) { 1005 for (String n : list) { 1006 ManagedFileAccess.file(path(folder, n)).delete(); 1007 } 1008 } 1009 } 1010 1011 public static File createTempFile(String prefix, String suffix) throws IOException { 1012 // this allows use to eaily identify all our dtemp files and delete them, since delete on Exit doesn't really work. 1013 File file = File.createTempFile("ohfu-" + prefix, suffix); 1014 file.deleteOnExit(); 1015 return file; 1016 } 1017 1018 1019 public static boolean isAsciiChar(char ch) { 1020 return ch >= ' ' && ch <= '~'; 1021 } 1022 1023 1024 public static String makeUuidLC() { 1025 return UUID.randomUUID().toString().toLowerCase(); 1026 } 1027 1028 public static String makeUuidUrn() { 1029 return "urn:uuid:" + UUID.randomUUID().toString().toLowerCase(); 1030 } 1031 1032 public static boolean isURL(String s) { 1033 boolean ok = s.matches("^http(s{0,1})://[a-zA-Z0-9_/\\-\\.]+\\.([A-Za-z/]{2,5})[a-zA-Z0-9_/\\&\\?\\=\\-\\.\\~\\%]*"); 1034 return ok; 1035 } 1036 1037 1038 public static String escapeCSV(String value) { 1039 if (value == null) 1040 return ""; 1041 1042 StringBuilder b = new StringBuilder(); 1043 for (char c : value.toCharArray()) { 1044 if (c == '"') 1045 b.append("\"\""); 1046 else if (isWhitespace(c)) 1047 b.append(" "); 1048 else 1049 b.append(c); 1050 } 1051 return b.toString(); 1052 } 1053 1054 1055 public static String escapeJson(String value) { 1056 return escapeJson(value, true); 1057 } 1058 1059 public static String escapeJson(String value, boolean escapeUnicodeWhitespace) { 1060 if (value == null) 1061 return ""; 1062 1063 StringBuilder b = new StringBuilder(); 1064 for (char c : value.toCharArray()) { 1065 if (c == '\r') 1066 b.append("\\r"); 1067 else if (c == '\n') 1068 b.append("\\n"); 1069 else if (c == '\t') 1070 b.append("\\t"); 1071 else if (c == '"') 1072 b.append("\\\""); 1073 else if (c == '\\') 1074 b.append("\\\\"); 1075 else if (c == ' ') 1076 b.append(" "); 1077 else if ((c == '\r' || c == '\n') || (isWhitespace(c) && escapeUnicodeWhitespace)) { 1078 b.append("\\u"+Utilities.padLeft(Integer.toHexString(c), '0', 4)); 1079 } else if (((int) c) < 32) 1080 b.append("\\u" + Utilities.padLeft(Integer.toHexString(c), '0', 4)); 1081 else 1082 b.append(c); 1083 } 1084 return b.toString(); 1085 } 1086 1087 public static String humanize(String code) { 1088 StringBuilder b = new StringBuilder(); 1089 boolean lastBreak = true; 1090 for (char c : code.toCharArray()) { 1091 if (Character.isLetter(c)) { 1092 if (lastBreak) 1093 b.append(Character.toUpperCase(c)); 1094 else { 1095 if (Character.isUpperCase(c)) 1096 b.append(" "); 1097 b.append(c); 1098 } 1099 lastBreak = false; 1100 } else { 1101 b.append(" "); 1102 lastBreak = true; 1103 } 1104 } 1105 if (b.length() == 0) 1106 return code; 1107 else 1108 return b.toString(); 1109 } 1110 1111 1112 public static String uncapitalize(String s) { 1113 if (s == null) return null; 1114 if (s.length() == 0) return s; 1115 if (s.length() == 1) return s.toLowerCase(); 1116 1117 return s.substring(0, 1).toLowerCase() + s.substring(1); 1118 } 1119 1120 public static int charCount(String s, char c) { 1121 int res = 0; 1122 for (char ch : s.toCharArray()) 1123 if (ch == c) 1124 res++; 1125 return res; 1126 } 1127 1128 public static boolean isOid(String cc) { 1129 return cc.matches(OID_REGEX); 1130 } 1131 1132 public static boolean equals(String one, String two) { 1133 if (one == null && two == null) 1134 return true; 1135 if (one == null || two == null) 1136 return false; 1137 return one.equals(two); 1138 } 1139 1140 1141 public static void deleteAllFiles(String folder, String type) throws IOException { 1142 File src = ManagedFileAccess.file(folder); 1143 String[] files = src.list(); 1144 for (String f : files) { 1145 if (ManagedFileAccess.file(folder + File.separator + f).isDirectory()) { 1146 deleteAllFiles(folder + File.separator + f, type); 1147 } else if (f.endsWith(type)) { 1148 ManagedFileAccess.file(folder + File.separator + f).delete(); 1149 } 1150 } 1151 1152 } 1153 1154 public static boolean compareIgnoreWhitespace(File f1, File f2) throws IOException { 1155 InputStream in1 = null; 1156 InputStream in2 = null; 1157 try { 1158 in1 = new BufferedInputStream(ManagedFileAccess.inStream(f1)); 1159 in2 = new BufferedInputStream(ManagedFileAccess.inStream(f2)); 1160 1161 int expectedByte = in1.read(); 1162 while (expectedByte != -1) { 1163 boolean w1 = Character.isWhitespace(expectedByte); 1164 if (w1) 1165 while (Character.isWhitespace(expectedByte)) 1166 expectedByte = in1.read(); 1167 int foundByte = in2.read(); 1168 if (w1) { 1169 if (!Character.isWhitespace(foundByte)) 1170 return false; 1171 while (Character.isWhitespace(foundByte)) 1172 foundByte = in2.read(); 1173 } 1174 if (expectedByte != foundByte) 1175 return false; 1176 expectedByte = in1.read(); 1177 } 1178 if (in2.read() != -1) { 1179 return false; 1180 } 1181 return true; 1182 } finally { 1183 if (in1 != null) { 1184 try { 1185 in1.close(); 1186 } catch (IOException e) { 1187 } 1188 } 1189 if (in2 != null) { 1190 try { 1191 in2.close(); 1192 } catch (IOException e) { 1193 } 1194 } 1195 } 1196 } 1197 1198 1199 public static boolean compareIgnoreWhitespace(String fn1, String fn2) throws IOException { 1200 return compareIgnoreWhitespace(ManagedFileAccess.file(fn1), ManagedFileAccess.file(fn2)); 1201 } 1202 1203 1204 public static boolean isAbsoluteUrl(String ref) { 1205 if (ref != null && ref.contains(":")) { 1206 String scheme = ref.substring(0, ref.indexOf(":")); 1207 String details = ref.substring(ref.indexOf(":")+1); 1208 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:")) 1209 && details != null && details.length() > 0 && !details.contains(" "); // rfc5141 1210 } 1211 return false; 1212 } 1213 1214 public static boolean isAbsoluteUrlLinkable(String ref) { 1215 if (ref != null && ref.contains(":")) { 1216 String scheme = ref.substring(0, ref.indexOf(":")); 1217 String details = ref.substring(ref.indexOf(":")+1); 1218 return (existsInList(scheme, "http", "https", "ftp")) 1219 && details != null && details.length() > 0 && !details.contains(" "); // rfc5141 1220 } 1221 return false; 1222 } 1223 1224 public static boolean equivalent(String l, String r) { 1225 if (Utilities.noString(l) && Utilities.noString(r)) 1226 return true; 1227 if (Utilities.noString(l) || Utilities.noString(r)) 1228 return false; 1229 return l.toLowerCase().equals(r.toLowerCase()); 1230 } 1231 1232 1233 public static boolean equivalentNumber(String l, String r) { 1234 if (Utilities.noString(l) && Utilities.noString(r)) 1235 return true; 1236 if (Utilities.noString(l) || Utilities.noString(r)) 1237 return false; 1238 if (!Utilities.isDecimal(l, true) || !Utilities.isDecimal(r, true)) 1239 return false; 1240 BigDecimal dl = new BigDecimal(l); 1241 BigDecimal dr = new BigDecimal(r); 1242 if (dl.scale() < dr.scale()) { 1243 dr = dr.setScale(dl.scale(), RoundingMode.HALF_UP); 1244 } else if (dl.scale() > dr.scale()) { 1245 dl = dl.setScale(dr.scale(), RoundingMode.HALF_UP); 1246 } 1247 return dl.equals(dr); 1248 } 1249 1250 public static String getFileExtension(String fn) { 1251 return fn.contains(".") ? fn.substring(fn.lastIndexOf(".") + 1) : ""; 1252 } 1253 1254 public static String unCamelCaseKeepCapitals(String name) { 1255 StringBuilder b = new StringBuilder(); 1256 boolean first = true; 1257 for (char c : name.toCharArray()) { 1258 if (Character.isUpperCase(c)) { 1259 if (!first) 1260 b.append(" "); 1261 b.append(c); 1262 } else 1263 b.append(c); 1264 first = false; 1265 } 1266 return b.toString(); 1267 } 1268 1269 public static String unCamelCase(String name) { 1270 StringBuilder b = new StringBuilder(); 1271 boolean first = true; 1272 for (char c : name.toCharArray()) { 1273 if (Character.isUpperCase(c)) { 1274 if (!first) 1275 b.append(" "); 1276 b.append(Character.toLowerCase(c)); 1277 } else 1278 b.append(c); 1279 first = false; 1280 } 1281 return b.toString(); 1282 } 1283 1284 1285 public static boolean isAbsoluteFileName(String source) { 1286 if (isWindows()) 1287 return (source.length() > 2 && source.charAt(1) == ':') || source.startsWith("\\\\"); 1288 else 1289 return source.startsWith("//"); 1290 } 1291 1292 1293 public static boolean isWindows() { 1294 return System.getProperty("os.name").startsWith("Windows"); 1295 } 1296 1297 1298 public static String splitLineForLength(String line, int prefixLength, int indent, int allowedLength) { 1299 List<String> list = new ArrayList<String>(); 1300 while (prefixLength + line.length() > allowedLength) { 1301 int i = allowedLength - (list.size() == 0 ? prefixLength : indent); 1302 while (i > 0 && line.charAt(i) != ' ') 1303 i--; 1304 if (i == 0) 1305 break; 1306 list.add(line.substring(0, i)); 1307 line = line.substring(i + 1); 1308 } 1309 list.add(line); 1310 StringBuilder b = new StringBuilder(); 1311 boolean first = true; 1312 for (String s : list) { 1313 if (first) 1314 first = false; 1315 else 1316 b.append("\r\n" + padLeft("", ' ', indent)); 1317 b.append(s); 1318 } 1319 return b.toString(); 1320 } 1321 1322 1323 public static int countFilesInDirectory(String dirName) throws IOException { 1324 File dir = ManagedFileAccess.file(dirName); 1325 if (dir.exists() == false) { 1326 return 0; 1327 } 1328 int i = 0; 1329 for (File f : dir.listFiles()) 1330 if (!f.isDirectory()) 1331 i++; 1332 return i; 1333 } 1334 1335 public static String makeId(String name) { 1336 StringBuilder b = new StringBuilder(); 1337 for (char ch : name.toCharArray()) { 1338 if (ch >= 'a' && ch <= 'z') 1339 b.append(ch); 1340 else if (ch >= 'A' && ch <= 'Z') 1341 b.append(ch); 1342 else if (ch >= '0' && ch <= '9') 1343 b.append(ch); 1344 else if (ch == '-' || ch == '.') 1345 b.append(ch); 1346 } 1347 return b.toString(); 1348 } 1349 1350 public interface FileVisitor { 1351 void visitFile(File file) throws FileNotFoundException, IOException; 1352 } 1353 1354 public static void visitFiles(String folder, String extension, FileVisitor visitor) throws FileNotFoundException, IOException { 1355 visitFiles(ManagedFileAccess.file(folder), extension, visitor); 1356 } 1357 1358 public static void visitFiles(File folder, String extension, FileVisitor visitor) throws FileNotFoundException, IOException { 1359 for (File file : folder.listFiles()) { 1360 if (file.isDirectory()) 1361 visitFiles(file, extension, visitor); 1362 else if (extension == null || file.getName().endsWith(extension)) 1363 visitor.visitFile(file); 1364 } 1365 } 1366 1367 public static String extractBaseUrl(String url) { 1368 if (url == null) 1369 return null; 1370 else if (url.contains("/")) 1371 return url.substring(0, url.lastIndexOf("/")); 1372 else 1373 return url; 1374 } 1375 1376 public static String listCanonicalUrls(Set<String> keys) { 1377 return keys.toString(); 1378 } 1379 1380 public static boolean isValidId(String id) { 1381 return id.matches("[A-Za-z0-9\\-\\.]{1,64}"); 1382 } 1383 1384 public static class CaseInsensitiveSorter implements Comparator<String> { 1385 @Override 1386 public int compare(String o1, String o2) { 1387 return o1.compareToIgnoreCase(o2); 1388 } 1389 } 1390 1391 public static List<String> sortedCaseInsensitive(Collection<String> set) { 1392 List<String> list = new ArrayList<>(); 1393 list.addAll(set); 1394 Collections.sort(list, new CaseInsensitiveSorter()); 1395 return list; 1396 } 1397 1398 1399 public static List<String> sorted(Collection<String> set) { 1400 List<String> list = new ArrayList<>(); 1401 list.addAll(set); 1402 Collections.sort(list); 1403 return list; 1404 } 1405 1406 public static List<String> sorted(String[] set) { 1407 List<String> list = new ArrayList<>(); 1408 for (String s : set) { 1409 list.add(s); 1410 } 1411 Collections.sort(list); 1412 return list; 1413 } 1414 1415 1416 public static List<String> reverseSorted(Collection<String> set) { 1417 List<String> list = new ArrayList<>(); 1418 list.addAll(set); 1419 Collections.sort(list, Collections.reverseOrder()); 1420 return list; 1421 } 1422 1423 public static List<String> reverseSorted(String[] set) { 1424 List<String> list = new ArrayList<>(); 1425 for (String s : set) { 1426 list.add(s); 1427 } 1428 Collections.sort(list, Collections.reverseOrder()); 1429 return list; 1430 } 1431 1432 1433 public static void analyseStringDiffs(Set<String> source, Set<String> target, Set<String> missed, Set<String> extra) { 1434 for (String s : source) 1435 if (!target.contains(s)) 1436 missed.add(s); 1437 for (String s : target) 1438 if (!source.contains(s)) 1439 extra.add(s); 1440 1441 } 1442 1443 /** 1444 * Only handles simple FHIRPath expressions of the type produced by the validator 1445 * 1446 * @param path 1447 * @return 1448 */ 1449 public static String fhirPathToXPath(String path) { 1450 String[] p = path.split("\\."); 1451 CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder("."); 1452 int i = 0; 1453 while (i < p.length) { 1454 String s = p[i]; 1455 if (s.contains("[")) { 1456 String si = s.substring(s.indexOf("[") + 1, s.length() - 1); 1457 if (!Utilities.isInteger(si)) 1458 throw new FHIRException("The FHIRPath expression '" + path + "' is not valid"); 1459 s = s.substring(0, s.indexOf("[")) + "[" + Integer.toString(Integer.parseInt(si) + 1) + "]"; 1460 } 1461 if (i < p.length - 1 && p[i + 1].startsWith(".ofType(")) { 1462 i++; 1463 s = s + capitalize(p[i].substring(8, p.length - 1)); 1464 } 1465 b.append(s); 1466 i++; 1467 } 1468 return b.toString(); 1469 } 1470 1471 public static String describeDuration(Duration d) { 1472 if (d.toDays() > 2) { 1473 return String.format("%s days", d.toDays()); 1474 } else if (d.toHours() > 2) { 1475 return String.format("%s hours", d.toHours()); 1476 } else if (d.toMinutes() > 2) { 1477 return String.format("%s mins", d.toMinutes()); 1478 } else { 1479 return String.format("%s ms", d.toMillis()); 1480 } 1481 } 1482 1483 public static String describeDuration(long ms) { 1484 long days = ms / (1000 * 60 * 60 * 24); 1485 long hours = ms / (1000 * 60 * 60) % 24; 1486 long mins = ms / (1000 * 60) % 60; 1487 long secs = ms / (1000) % 60; 1488 ms = ms % 1000; 1489 if (days > 0) { 1490 return ""+days+"d "+pad(hours,2)+":"+pad(mins,2)+":"+pad(secs,2)+"."+ms; 1491 } else { 1492 return ""+pad(hours, 2)+":"+pad(mins,2)+":"+pad(secs,2)+"."+ms; 1493 } 1494 } 1495 1496 private static String pad(long v, int i) { 1497 return padLeft(Long.toString(v), '0', i); 1498 } 1499 1500 public static boolean startsWithInList(String s, String... list) { 1501 if (s == null) { 1502 return false; 1503 } 1504 for (String l : list) { 1505 if (l != null) { 1506 if (s.startsWith(l)) { 1507 return true; 1508 } 1509 } 1510 } 1511 return false; 1512 } 1513 1514 public static boolean startsWithInList(String s, Collection<String> list) { 1515 if (s == null || list == null) { 1516 return false; 1517 } 1518 for (String l : list) { 1519 if (s.startsWith(l)) { 1520 return true; 1521 } 1522 } 1523 return false; 1524 } 1525 1526 public static boolean endsWithInList(String s, String... list) { 1527 if (s == null) { 1528 return false; 1529 } 1530 for (String l : list) { 1531 if (s.endsWith(l)) { 1532 return true; 1533 } 1534 } 1535 return false; 1536 } 1537 1538 public static boolean endsWithInList(String s, Collection<String> list) { 1539 if (s == null) { 1540 return false; 1541 } 1542 for (String l : list) { 1543 if (s.endsWith(l)) { 1544 return true; 1545 } 1546 } 1547 return false; 1548 } 1549 1550 public static final int ONE_MB = 1024; 1551 public static final String GB = "Gb"; 1552 public static final String MB = "Mb"; 1553 public static final String KB = "Kb"; 1554 public static final String BT = "b"; 1555 1556 public static String describeSize(int length) { 1557 if (length < 0) throw new IllegalArgumentException("File length of < 0 passed in..."); 1558 1559 if (length > Math.pow(ONE_MB, 3)) { 1560 return length / ((long) Math.pow(ONE_MB, 3)) + GB; 1561 } 1562 if (length > Math.pow(ONE_MB, 2)) { 1563 return length / ((long) Math.pow(ONE_MB, 2)) + MB; 1564 } 1565 if (length > ONE_MB) { 1566 return length / (ONE_MB) + KB; 1567 } 1568 return length + BT; 1569 } 1570 1571 public static String describeSize(long length) { 1572 if (length < 0) throw new IllegalArgumentException("File length of < 0 passed in..."); 1573 1574 if (length > Math.pow(ONE_MB, 3)) { 1575 return length / ((long) Math.pow(ONE_MB, 3)) + GB; 1576 } 1577 if (length > Math.pow(ONE_MB, 2)) { 1578 return length / ((long) Math.pow(ONE_MB, 2)) + MB; 1579 } 1580 if (length > ONE_MB) { 1581 return length / (ONE_MB) + KB; 1582 } 1583 return length + BT; 1584 } 1585 1586 public static List<byte[]> splitBytes(byte[] array, byte[] delimiter) { 1587 List<byte[]> byteArrays = new LinkedList<byte[]>(); 1588 if (delimiter.length == 0) 1589 { 1590 return byteArrays; 1591 } 1592 int begin = 0; 1593 1594 outer: for (int i = 0; i < array.length - delimiter.length + 1; i++) 1595 { 1596 for (int j = 0; j < delimiter.length; j++) 1597 { 1598 if (array[i + j] != delimiter[j]) 1599 { 1600 continue outer; 1601 } 1602 } 1603 1604 // If delimiter is at the beginning then there will not be any data. 1605 if (begin < i) 1606 byteArrays.add(Arrays.copyOfRange(array, begin, i)); 1607 begin = i + delimiter.length; 1608 } 1609 1610 // delimiter at the very end with no data following? 1611 if (begin != array.length) 1612 byteArrays.add(Arrays.copyOfRange(array, begin, array.length)); 1613 1614 return byteArrays; 1615 } 1616 1617 public static void unzip(InputStream zip, String target) throws IOException { 1618 unzip(zip, Path.of(target)); 1619 } 1620 1621 public static void unzip(InputStream zip, Path target) throws IOException { 1622 try (ZipInputStream zis = new ZipInputStream(zip)) { 1623 ZipEntry zipEntry = zis.getNextEntry(); 1624 while (zipEntry != null) { 1625 boolean isDirectory = false; 1626 1627 String n = makeOSSafe(zipEntry.getName()); 1628 1629 if (n.endsWith(File.separator)) { 1630 isDirectory = true; 1631 } 1632 Path newPath = zipSlipProtect(n, target); 1633 if (isDirectory) { 1634 Files.createDirectories(newPath); 1635 } else { 1636 if (newPath.getParent() != null) { 1637 if (Files.notExists(newPath.getParent())) { 1638 Files.createDirectories(newPath.getParent()); 1639 } 1640 } 1641 Files.copy(zis, newPath, StandardCopyOption.REPLACE_EXISTING); 1642 } 1643 zipEntry = zis.getNextEntry(); 1644 } 1645 zis.closeEntry(); 1646 } 1647 } 1648 1649 public static String makeOSSafe(String name) { 1650 return name.replace("\\", File.separator).replace("/", File.separator); 1651 } 1652 1653 public static Path zipSlipProtect(String zipName, Path targetDir) 1654 throws IOException { 1655 1656 // test zip slip vulnerability 1657 // Path targetDirResolved = targetDir.resolve("../../" + zipEntry.getName()); 1658 1659 Path targetDirResolved = targetDir.resolve(zipName); 1660 1661 // make sure normalized file still has targetDir as its prefix 1662 // else throws exception 1663 Path normalizePath = targetDirResolved.normalize(); 1664 if (!normalizePath.startsWith(targetDir)) { 1665 throw new IOException("Bad zip entry: " + zipName); 1666 } 1667 1668 return normalizePath; 1669 } 1670 1671 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}; 1672 1673 static { 1674 Arrays.sort(illegalChars); 1675 } 1676 1677 public static String cleanFileName(String badFileName) { 1678 StringBuilder cleanName = new StringBuilder(); 1679 int len = badFileName.codePointCount(0, badFileName.length()); 1680 for (int i=0; i<len; i++) { 1681 int c = badFileName.codePointAt(i); 1682 if (Arrays.binarySearch(illegalChars, c) < 0) { 1683 cleanName.appendCodePoint(c); 1684 } 1685 } 1686 return cleanName.toString(); 1687 } 1688 1689 public static boolean isValidUUID(String uuid) { 1690 return uuid.matches(UUID_REGEX); 1691 } 1692 1693 public static boolean isValidOID(String oid) { 1694 return oid.matches(OID_REGEX); 1695 } 1696 1697 public static int findinList(String[] list, String val) { 1698 for (int i = 0; i < list.length; i++) { 1699 if (val.equals(list[i])) { 1700 return i; 1701 } 1702 } 1703 return -1; 1704 } 1705 1706 public static String toString(String[] expected) { 1707 return "['"+String.join("' | '", expected)+"']"; 1708 } 1709 1710 public static String lowBoundaryForDecimal(String value, int precision) { 1711 if (Utilities.noString(value)) { 1712 throw new FHIRException("Unable to calculate lowBoundary for a null decimal string"); 1713 } 1714 String e = value.contains("e") ? value.substring(value.indexOf("e")+1) : null; 1715 if (value.contains("e")) { 1716 value = value.substring(0, value.indexOf("e")); 1717 } 1718 if (isZero(value)) { 1719 return applyPrecision("-0.5000000000000000000000000", precision, true); 1720 } else if (value.startsWith("-")) { 1721 return "-"+highBoundaryForDecimal(value.substring(1), precision)+(e == null ? "" : e); 1722 } else { 1723 if (value.contains(".")) { 1724 return applyPrecision(minusOne(value)+"50000000000000000000000000000", precision, true)+(e == null ? "" : e); 1725 } else { 1726 return applyPrecision(minusOne(value)+".50000000000000000000000000000", precision, true)+(e == null ? "" : e); 1727 } 1728 } 1729 } 1730 1731 private static String applyPrecision(String v, int p, boolean down) { 1732 String nv = v; 1733 int dp = -1; 1734 if (nv.contains(".")) { 1735 dp = nv.indexOf("."); 1736 nv = nv.substring(0, dp)+nv.substring(dp+1); 1737 } 1738 String s = null; 1739 int d = p - getDecimalPrecision(v); 1740 if (d == 0) { 1741 s = nv; 1742 } else if (d > 0) { 1743 s = nv + padLeft("", '0', d); 1744 } else { 1745 int l = v.length(); 1746 int ld = l+d; 1747 if (dp > -1) { 1748 ld--; 1749 } 1750 if (nv.charAt(ld) >= '5' && !down) { 1751 s = nv.substring(0, ld-1)+((char) (nv.charAt(ld-1)+1)); 1752 } else { 1753 s = nv.substring(0, ld); 1754 } 1755 } 1756 if (s.endsWith(".")) { 1757 s = s.substring(0, s.length()-1); 1758 } 1759 return dp == -1 || dp >= s.length() ? s : s.substring(0, dp)+"."+s.substring(dp); 1760 } 1761 1762 private static String minusOne(String value) { 1763 StringBuffer s = new StringBuffer(value); 1764 for (int i = s.length()-1; i >= 0; i--) { 1765 if (s.charAt(i) == '0') { 1766 s.setCharAt(i, '9'); 1767 } else if (s.charAt(i) != '.') { 1768 s.setCharAt(i, (char) (s.charAt(i)-1)); 1769 break; 1770 } 1771 } 1772 return s.toString(); 1773 } 1774 1775 public static String lowBoundaryForDate(String value, int precision) { 1776 String[] res = splitTimezone(value); 1777 StringBuilder b = new StringBuilder(res[0]); 1778 if (b.length() == 4) { 1779 b.append("-01"); 1780 } 1781 if (b.length() == 7) { 1782 b.append("-01"); 1783 } 1784 if (b.length() == 10) { 1785 b.append("T00:00"); 1786 } 1787 if (b.length() == 16) { 1788 b.append(":00"); 1789 } 1790 if (b.length() == 19) { 1791 b.append(".000"); 1792 } 1793 String tz; 1794 if (precision <= 10) { 1795 tz = ""; 1796 } else { 1797 tz = Utilities.noString(res[1]) ? defLowTimezone(b.toString()) : res[1]; 1798 } 1799 return applyDatePrecision(b.toString(), precision)+tz; 1800 } 1801 1802 private static String defLowTimezone(String string) { 1803 return "+14:00"; // Kiribati permanent timezone since 1994 and we don't worry about before then 1804 } 1805 1806 private static String defHighTimezone(String string) { 1807 return "-12:00"; // Parts of Russia, Antarctica, Baker Island and Midway Atoll 1808 } 1809 1810 public static String lowBoundaryForTime(String value, int precision) { 1811 String[] res = splitTimezone(value); 1812 StringBuilder b = new StringBuilder(res[0]); 1813 if (b.length() == 2) { 1814 b.append(":00"); 1815 } 1816 if (b.length() == 5) { 1817 b.append(":00"); 1818 } 1819 if (b.length() == 8) { 1820 b.append(".000"); 1821 } 1822 return applyTimePrecision(b.toString(), precision)+res[1]; 1823 } 1824 1825 public static String highBoundaryForTime(String value, int precision) { 1826 String[] res = splitTimezone(value); 1827 StringBuilder b = new StringBuilder(res[0]); 1828 if (b.length() == 2) { 1829 b.append(":59"); 1830 } 1831 if (b.length() == 5) { 1832 b.append(":59"); 1833 } 1834 if (b.length() == 8) { 1835 b.append(".999"); 1836 } 1837 return applyTimePrecision(b.toString(), precision)+res[1]; 1838 } 1839 1840 1841 private static Object applyDatePrecision(String v, int precision) { 1842 switch (precision) { 1843 case 4: 1844 return v.substring(0, 4); 1845 case 6: 1846 case 7: 1847 return v.substring(0, 7); 1848 case 8: 1849 case 10: 1850 return v.substring(0, 10); 1851 case 14: return v.substring(0, 17); 1852 case 17: return v; 1853 } 1854 throw new FHIRException("Unsupported Date precision for boundary operation: "+precision); 1855 } 1856 1857 private static Object applyTimePrecision(String v, int precision) { 1858 switch (precision) { 1859 case 2: return v.substring(0, 3); 1860 case 4: return v.substring(0, 6); 1861 case 6: return v.substring(0, 9); 1862 case 9: return v; 1863 } 1864 throw new FHIRException("Unsupported Time precision for boundary operation: "+precision); 1865 } 1866 1867 public static String highBoundaryForDecimal(String value, int precision) { 1868 if (Utilities.noString(value)) { 1869 throw new FHIRException("Unable to calculate highBoundary for a null decimal string"); 1870 } 1871 String e = value.contains("e") ? value.substring(value.indexOf("e")+1) : null; 1872 if (value.contains("e")) { 1873 value = value.substring(0, value.indexOf("e")); 1874 } 1875 if (isZero(value)) { 1876 return applyPrecision("0.50000000000000000000000000000", precision, false); 1877 } else if (value.startsWith("-")) { 1878 return "-"+lowBoundaryForDecimal(value.substring(1), precision)+(e == null ? "" : e); 1879 } else { 1880 if (value.contains(".")) { 1881 return applyPrecision(value+"50000000000000000000000000000", precision, false)+(e == null ? "" : e); 1882 } else { 1883 return applyPrecision(value+".50000000000000000000000000000", precision, false)+(e == null ? "" : e); 1884 } 1885 } 1886 } 1887 1888 private static boolean isZero(String value) { 1889 return value.replace(".", "").replace("-", "").replace("0", "").length() == 0; 1890 } 1891 1892 public static String highBoundaryForDate(String value, int precision) { 1893 String[] res = splitTimezone(value); 1894 StringBuilder b = new StringBuilder(res[0]); 1895 if (b.length() == 4) { 1896 b.append("-12"); 1897 } 1898 if (b.length() == 7) { 1899 b.append("-"+dayCount(Integer.parseInt(b.substring(0,4)), Integer.parseInt(b.substring(5,7)))); 1900 } 1901 if (b.length() == 10) { 1902 b.append("T23:59"); 1903 } 1904 if (b.length() == 16) { 1905 b.append(":59"); 1906 } 1907 if (b.length() == 19) { 1908 b.append(".999"); 1909 } 1910 String tz; 1911 if (precision <= 10) { 1912 tz = ""; 1913 } else { 1914 tz = Utilities.noString(res[1]) ? defHighTimezone(b.toString()) : res[1]; 1915 } 1916 return applyDatePrecision(b.toString(), precision)+tz; 1917 } 1918 1919 private static String dayCount(int y, int m) { 1920 switch (m) { 1921 case 1: return "31"; 1922 case 2: return ((y % 4 == 0) && (y % 400 == 0 || !(y % 100 == 0))) ? "29" : "28"; 1923 case 3: return "31"; 1924 case 4: return "30"; 1925 case 5: return "31"; 1926 case 6: return "30"; 1927 case 7: return "31"; 1928 case 8: return "31"; 1929 case 9: return "30"; 1930 case 10: return "31"; 1931 case 11: return "30"; 1932 case 12: return "31"; 1933 default: return "30"; // make the compiler happy 1934 } 1935 } 1936 1937 public static Integer getDecimalPrecision(String value) { 1938 if (value.contains("e")) { 1939 value = value.substring(0, value.indexOf("e")); 1940 } 1941 if (value.contains(".")) { 1942 return value.split("\\.")[1].length(); 1943 } else { 1944 return 0; 1945 } 1946 } 1947 1948 1949 private static String[] splitTimezone(String value) { 1950 String[] res = new String[2]; 1951 1952 if (value.contains("+")) { 1953 res[0] = value.substring(0, value.indexOf("+")); 1954 res[1] = value.substring(value.indexOf("+")); 1955 } else if (value.contains("-") && value.contains("T") && value.lastIndexOf("-") > value.indexOf("T")) { 1956 res[0] = value.substring(0, value.lastIndexOf("-")); 1957 res[1] = value.substring(value.lastIndexOf("-")); 1958 } else if (value.contains("Z")) { 1959 res[0] = value.substring(0, value.indexOf("Z")); 1960 res[1] = value.substring(value.indexOf("Z")); 1961 } else { 1962 res[0] = value; 1963 res[1] = ""; 1964 } 1965 return res; 1966 } 1967 1968 public static Integer getDatePrecision(String value) { 1969 return splitTimezone(value)[0].replace("-", "").replace("T", "").replace(":", "").replace(".", "").length(); 1970 } 1971 1972 public static Integer getTimePrecision(String value) { 1973 return splitTimezone(value)[0].replace("T", "").replace(":", "").replace(".", "").length(); 1974 } 1975 1976 public static String padInt(int i, int len) { 1977 return Utilities.padLeft(Integer.toString(i), ' ', len); 1978 } 1979 1980 public static String padInt(long i, int len) { 1981 return Utilities.padLeft(Long.toString(i), ' ', len); 1982 } 1983 1984 public static Object makeSingleLine(String text) { 1985 text = text.replace("\r", " "); 1986 text = text.replace("\n", " "); 1987 while (text.contains(" ")) { 1988 text = text.replace(" ", " "); 1989 } 1990 return text; 1991 } 1992 1993 public static int parseInt(String value, int def) { 1994 if (isInteger(value)) { 1995 return Integer.parseInt(value); 1996 } else { 1997 return def; 1998 } 1999 } 2000 2001 /** 2002 * Appends a text from a derived element to its base element. 2003 * 2004 * @param baseText The text set in the base element, or {@code null}. 2005 * @param derivedText The text set in the derived element, starting with "...". 2006 * @return The resulting text. 2007 */ 2008 public static String appendDerivedTextToBase(@Nullable final String baseText, 2009 final String derivedText) { 2010 if (baseText == null) { 2011 return derivedText.substring(3); 2012 } 2013 return baseText + "\r\n" + derivedText.substring(3); 2014 } 2015 2016 public static void deleteEmptyFolders(File df) { 2017 for (File f : df.listFiles()) { 2018 if (f.isDirectory()) { 2019 deleteEmptyFolders(f); 2020 } 2021 } 2022 boolean empty = true; 2023 for (File f : df.listFiles()) { 2024 empty = false; 2025 break; 2026 } 2027 if (empty) { 2028 df.delete(); 2029 } 2030 } 2031 2032 public static String getRelativePath(String root, String path) { 2033 String res = path.substring(root.length()); 2034 if (res.startsWith(File.separator)) { 2035 res = res.substring(1); 2036 } 2037 return res; 2038 } 2039 2040 public static String getRelativeUrlPath(String root, String path) { 2041 String res = path.substring(root.length()); 2042 if (res.startsWith("/")) { 2043 res = res.substring(1); 2044 } 2045 return res; 2046 } 2047 2048 public static List<String> listAllFiles(String path, List<String> ignoreList) throws IOException { 2049 List<String> res = new ArrayList<>(); 2050 addAllFiles(res, path, ManagedFileAccess.file(path), ignoreList); 2051 return res; 2052 } 2053 2054 private static void addAllFiles(List<String> res, String root, File dir, List<String> ignoreList) { 2055 for (File f : dir.listFiles()) { 2056 if (ignoreList == null || !ignoreList.contains(f.getAbsolutePath())) { 2057 if (f.isDirectory()) { 2058 addAllFiles(res, root, f, ignoreList); 2059 } else if (!f.getName().equals(".DS_Store")) { 2060 res.add(getRelativePath(root, f.getAbsolutePath())); 2061 } 2062 } 2063 } 2064 2065 } 2066 2067 public static boolean isValidCRName(String name) { 2068 return name != null && name.matches("[A-Z]([A-Za-z0-9_]){1,254}"); 2069 } 2070 2071 public static boolean isAllWhitespace(String s) { 2072 if (Utilities.noString(s)) { 2073 return true; 2074 } 2075 for (char ch : s.toCharArray()) { 2076 if (!isWhitespace(ch)) { 2077 return false; 2078 } 2079 } 2080 return true; 2081 } 2082 2083 public static String trimWS(String s) { 2084 if (Utilities.noString(s)) { 2085 return s; 2086 } 2087 int start = 0; 2088 while (start < s.length() && isWhitespace(s.charAt(start))) { 2089 start++; 2090 } 2091 if (start == s.length()) { 2092 return ""; 2093 } 2094 int end = s.length() - 1; 2095 while (end >= 0 && isWhitespace(s.charAt(end))) { 2096 end--; 2097 } 2098 if (start > end) { 2099 return ""; 2100 } 2101 return s.substring(start, end+1); 2102 } 2103 2104 // from https://en.wikipedia.org/wiki/Whitespace_character#Unicode 2105 public static boolean isWhitespace(int ch) { 2106 return Utilities.existsInList(ch, '\u0009', '\n', '\u000B','\u000C','\r','\u0020','\u0085','\u00A0', 2107 '\u1680','\u2000','\u2001','\u2002','\u2003','\u2004','\u2005','\u2006','\u2007','\u2008','\u2009','\u200A', 2108 '\u2028', '\u2029', '\u202F', '\u205F', '\u3000'); 2109 } 2110 2111 public static boolean stringsEqual(String s1, String s2) { 2112 if (s1 == null && s2 == null) { 2113 return true; 2114 } else if (s1 == null) { 2115 return false; 2116 } else { 2117 return s1.equals(s2); 2118 } 2119 } 2120 2121 public static String tail(String url) { 2122 int i = url.length()-1; 2123 while (i >= 0 && (isTokenChar(url.charAt(i)) || isDigit(url.charAt(i))) ) { 2124 i--; 2125 } 2126 if (i < 0) { 2127 return url; 2128 } else { 2129 return url.substring(i+1); 2130 } 2131 } 2132 2133 public static List<String> strings(String... members) { 2134 List<String> ret = new ArrayList<>(); 2135 for (String m : members) { 2136 ret.add(m); 2137 } 2138 return ret; 2139 } 2140 2141 public static List<String> splitStrings(String src, String regex) { 2142 List<String> ret = new ArrayList<>(); 2143 for (String m : src.split(regex)) { 2144 ret.add(m); 2145 } 2146 return ret; 2147 } 2148 2149 public static String stripPara(String p) { 2150 if (noString(p)) { 2151 return ""; 2152 } 2153 p = p.trim(); 2154 if (p.startsWith("<p>")) { 2155 p = p.substring(3); 2156 } 2157 if (p.endsWith("</p>")) { 2158 p = p.substring(0, p.length()-4); 2159 } 2160 return p; 2161 } 2162 2163 public static String stripAllPara(String p) { 2164 if (noString(p)) { 2165 return ""; 2166 } 2167 p = p.trim(); 2168 if (p.startsWith("<p>")) { 2169 p = p.substring(3); 2170 } 2171 if (p.endsWith("</p>")) { 2172 p = p.substring(0, p.length()-4); 2173 } 2174 p = p.replace("</p>", " "); 2175 p = p.replace("<p>", ""); 2176 while (p.contains("<p ")) { 2177 int start = p.indexOf("<p "); 2178 int end = start; 2179 while (end < p.length() && p.charAt(end) != '>') { 2180 end++; 2181 } 2182 p = p.substring(start, end); 2183 } 2184 return p; 2185 } 2186 2187 2188 2189 //public static boolean !isWhitespace(String s) { 2190 //boolean ok = true; 2191 //for (int i = 0; i < s.length(); i++) 2192 // ok = ok && Character.isWhitespace(s.charAt(i)); 2193 //return ok; 2194 // 2195 //} 2196 2197 2198 public static boolean isTxFhirOrgServer(String s) { 2199 return Utilities.startsWithInList(s.replace("https://", "http://"), FhirSettings.getTxFhirProduction(), FhirSettings.getTxFhirDevelopment(), FhirSettings.getTxFhirLocal()); 2200 } 2201 2202 public static String[] splitLines(String txt) { 2203 return txt.split("\\r?\\n|\\r"); 2204 } 2205 2206 public static boolean isIgnorableFile(File file) { 2207 return Utilities.existsInList(file.getName(), ".DS_Store"); 2208 } 2209 2210 public static String rightTrim(String s) { 2211 int i = s.length()-1; 2212 while (i > 0 && Character.isWhitespace(s.charAt(i))) { 2213 i--; 2214 } 2215 return i == 0 ? "" : s.substring(0, i+1); 2216 } 2217 2218 public static void renameDirectory(String source, String dest) throws FHIRException, IOException { 2219 File src = ManagedFileAccess.file(source); 2220 File dst = ManagedFileAccess.file(dest); 2221 if (!src.renameTo(dst)) { 2222 int i = 0; 2223 do { 2224 try { 2225 Thread.sleep(20); 2226 } catch (Exception e) { 2227 // nothing 2228 } 2229 System.gc(); 2230 i++; 2231 } while (!src.renameTo(dst) && i < 10); 2232 if (src.exists()) { 2233 copyDirectory(source, dest, null); 2234 try { 2235 src.delete(); 2236 } catch (Exception e) { 2237 // nothing 2238 } 2239 } 2240 } 2241 2242 } 2243 2244 public static String urlTail(String url) { 2245 if (url == null) { 2246 return null; 2247 } 2248 return url.contains("/") ? url.substring(url.lastIndexOf("/")+1) : url; 2249 } 2250 2251 public static String escapeSql(String s) { 2252 return s.replace("'", "''"); 2253 } 2254 2255 public static String[] simpleSplit(String cnt, String div) { 2256 if (cnt == null) { 2257 return new String[] {}; 2258 } 2259 List<String> parts = new ArrayList<>(); 2260 int cursor = 0; 2261 int last = 0; 2262 while (cursor < cnt.length()) { 2263 if (matches(cnt, div, cursor)) { 2264 parts.add(cnt.substring(last, cursor)); 2265 cursor = cursor + div.length(); 2266 last = cursor; 2267 } else { 2268 cursor++; 2269 } 2270 } 2271 parts.add(cnt.substring(last, cursor)); 2272 return parts.toArray(new String[] {}); 2273 } 2274 2275 private static boolean matches(String cnt, String div, int cursor) { 2276 if (div.length() + cursor > cnt.length()) { 2277 return false; 2278 } 2279 for (int i = 0; i < div.length(); i++) { 2280 if (cnt.charAt(cursor+i) != div.charAt(i)) { 2281 return false; 2282 } 2283 } 2284 return true; 2285 } 2286 2287 public static String stripEoln(String text) { 2288 if (text == null) { 2289 return ""; 2290 } 2291 return text.replace("\r\n", " ").replace("\n", " ").replace("\r", " "); 2292 } 2293 2294 public static String extractDomain(String source) { 2295 try { 2296 URI uri = URI.create(source); 2297 return uri.getHost(); 2298 } catch (Exception e) { 2299 return "??"; 2300 } 2301 } 2302 2303 public static boolean isValidHtmlAnchorChar(char c) { 2304 if ( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) { 2305 return true; 2306 } 2307 switch (c) { 2308 case '!': 2309 case '$': 2310 case '&': 2311 case '\'': 2312 case '(': 2313 case ')': 2314 case '*': 2315 case '+': 2316 case ',': 2317 case ';': 2318 case '=': 2319 case '.': 2320 case '_': 2321 case '-': 2322 case '~': 2323 case ':': 2324 case '@': 2325 case '/': 2326 case '?': 2327 return true; 2328 default: 2329 return false; 2330 } 2331 } 2332 2333 public static boolean listValueStartsWith(String s, Set<String> list) { 2334 if (s == null || list == null) { 2335 return false; 2336 } 2337 for (String l : list) { 2338 if (l.startsWith(s)) { 2339 return true; 2340 } 2341 } 2342 return false; 2343 } 2344 2345}