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