001package org.hl7.fhir.utilities;
002
003import java.io.File;
004import java.io.FileInputStream;
005import java.io.FileNotFoundException;
006import java.io.FileOutputStream;
007import java.io.FilenameFilter;
008import java.io.IOException;
009import java.io.InputStream;
010import java.io.OutputStream;
011import java.nio.charset.StandardCharsets;
012import java.nio.file.Files;
013import java.nio.file.Path;
014import java.nio.file.Paths;
015import java.nio.file.StandardCopyOption;
016import java.nio.file.StandardOpenOption;
017import java.util.ArrayList;
018import java.util.Arrays;
019import java.util.List;
020import java.util.regex.Pattern;
021
022import org.apache.commons.io.FileUtils;
023import org.hl7.fhir.exceptions.FHIRException;
024import org.hl7.fhir.utilities.FileNotifier.FileNotifier2;
025import org.hl7.fhir.utilities.filesystem.CSFile;
026import org.hl7.fhir.utilities.filesystem.ManagedFileAccess;
027
028
029public class FileUtilities {
030
031  public static String bytesToString(final byte[] bs) throws IOException {
032    return new String(bs, StandardCharsets.UTF_8);
033  }
034
035  public static String bytesToString(final byte[] bs, final boolean removeBOM) throws IOException {
036    final String read = new String(bs, StandardCharsets.UTF_8);
037    if (removeBOM)
038      return read.replace("\uFEFF", "");
039    else
040      return read;
041  }
042
043  public static void bytesToFile(final byte[] bytes, final String path) throws IOException {
044    try (final OutputStream sw = ManagedFileAccess.outStream(ManagedFileAccess.csfile(path))) {
045      sw.write(bytes);
046    }
047  }
048  
049  public static void bytesToFile(final byte[] bytes, final File f) throws IOException {
050    try (final OutputStream sw = ManagedFileAccess.outStream(f)) {
051      sw.write(bytes);
052    }
053  }
054  
055  public static void appendBytesToFile(final byte[] bytes, final String path) throws IOException {
056    byte[] linebreak = new byte[] {13, 10};
057    Files.write(Paths.get(path), linebreak, StandardOpenOption.APPEND);
058    Files.write(Paths.get(path), bytes, StandardOpenOption.APPEND);
059  }
060
061  public static void stringToStream(final String content, final OutputStream stream) throws IOException {
062    stream.write(content.getBytes(StandardCharsets.UTF_8));
063  }
064  
065  public static byte[] stringToBytes(final String content) throws IOException {
066    return content.getBytes(StandardCharsets.UTF_8);
067  }
068  
069  public static void stringToFile(final String content, final String path) throws IOException  {
070    final File file = ManagedFileAccess.csfile(path);
071    stringToFile(content, file);
072  }
073
074  public static void stringToFile(final String content, final File file) throws IOException {
075    try (final OutputStream output = Files.newOutputStream(file.toPath())) {
076      output.write(content.getBytes(StandardCharsets.UTF_8));
077    }
078  }  
079  
080  public static void stringToFileWithBOM(final String content, final File file) throws IOException  {
081    try (final OutputStream output = Files.newOutputStream(file.toPath())) {
082      output.write(new byte[]{(byte)239, (byte)187, (byte)191});
083      output.write(content.getBytes(StandardCharsets.UTF_8));
084    }
085  }
086  
087  public static void stringToFileWithBOM(final String content, final String path) throws IOException  {
088    final File file = ManagedFileAccess.csfile(path);
089    stringToFileWithBOM(content, file);
090  }
091  
092  public static String fileToString(final File f) throws FileNotFoundException, IOException {
093    // Files.readString(Path) will fail on invalid UTF-8 byte sequences, so we use Files.readAllBytes() instead.
094    // This would happen when reading an XSLX file, for example.
095    return new String(Files.readAllBytes(f.toPath()), StandardCharsets.UTF_8);
096  }
097  
098  public static String fileToString(final String src) throws FileNotFoundException, IOException  {
099    final CSFile f = ManagedFileAccess.csfile(src);
100    if (!f.exists()) {
101      throw new IOException("File "+src+" not found");
102    }
103    return fileToString(f);
104  }
105
106  public static byte[] fileToBytes(final String srcFile) throws FileNotFoundException, IOException {
107    final File f = ManagedFileAccess.csfile(srcFile);
108    return Files.readAllBytes(f.toPath());
109  }
110
111  public static byte[] fileToBytes(final File file) throws FileNotFoundException, IOException {
112    return Files.readAllBytes(file.toPath());
113  }
114
115  /**
116   * 
117   * fileToBytes insists in case correctness to ensure that stuff works across linux and windows, but it's not always appropriate to check case (e.g. validator parameters)
118   * 
119   * @param srcFile
120   * @return
121   * @throws FileNotFoundException
122   * @throws IOException
123   */
124  public static byte[] fileToBytesNCS(final String srcFile) throws FileNotFoundException, IOException {
125    return Files.readAllBytes(Path.of(srcFile));
126  }
127
128  public static List<String> fileToLines(String file) throws FileNotFoundException, IOException {
129    Pattern LINE_SEP_PATTERN = Pattern.compile("\\R");
130    List<String> res = new ArrayList<String>();
131    for (String s : LINE_SEP_PATTERN.split(fileToString(file))) {
132      res.add(s);
133    }
134    return res;
135  }
136
137  public static String[] fileToLines(File file) throws FileNotFoundException, IOException {
138    Pattern LINE_SEP_PATTERN = Pattern.compile("\\R");
139    return LINE_SEP_PATTERN.split(fileToString(file));
140  }
141
142  public static String streamToString(final InputStream input) throws IOException  {
143    return new String(input.readAllBytes(), StandardCharsets.UTF_8).replace("\uFEFF", "");
144  }
145
146  public static byte[] streamToBytes(final InputStream input) throws IOException  {
147    if (input == null) {
148      return null;
149    }
150    final byte[] read = input.readAllBytes();
151    input.close();
152    return read;
153  }
154
155  public static byte[] streamToBytesNoClose(final InputStream input) throws IOException  {
156    if (input == null) {
157      return null;
158    }
159    return input.readAllBytes();
160  }
161
162  public static void streamToFile(final InputStream stream, final String filename) throws IOException {
163    Files.copy(stream, Path.of(filename), StandardCopyOption.REPLACE_EXISTING);
164    stream.close();
165  }
166
167  public static void streamToFileNoClose(final InputStream stream, final String filename) throws IOException {
168    Files.copy(stream, Path.of(filename), StandardCopyOption.REPLACE_EXISTING);
169  }
170        
171  public static void linesToFile(File f, String[] lines) throws IOException {
172    Files.write(f.toPath(), List.of(lines), StandardCharsets.UTF_8);
173  }
174  
175  public static void linesToFile(String path, String[] lines) throws IOException  {
176    final File file = ManagedFileAccess.csfile(path);
177    Files.write(file.toPath(), List.of(lines), StandardCharsets.UTF_8);
178  }
179  
180  public static void linesToFile(String path, List<String> lines) throws IOException  {
181    final File file = ManagedFileAccess.csfile(path);
182    Files.write(file.toPath(), lines, StandardCharsets.UTF_8);
183  }
184  
185  public static String fileTitle(String file) throws IOException {
186    if (file == null)
187      return null;
188    String s = ManagedFileAccess.file(file).getName();
189    return s.indexOf(".") == -1 ? s : s.substring(0, s.indexOf("."));
190  }
191
192  public static String getDirectoryForFile(String filepath) throws IOException {
193    File f = ManagedFileAccess.file(filepath);
194    return f.getParent();
195  }
196
197  public static String getDirectoryForFile(File file) throws IOException {
198    return file.getParent();
199  }
200
201  public static String getRelativePath(String root, String path) {
202    String res = path.substring(root.length());
203    if (res.startsWith(File.separator)) {
204      res = res.substring(1);
205    }
206    return res;
207  }
208
209  public static File createDirectory(String path) throws IOException {
210    ManagedFileAccess.csfile(path).mkdirs();
211    return ManagedFileAccess.file(path);
212  }
213
214  public static File createDirectoryNC(String path) throws IOException {
215    ManagedFileAccess.file(path).mkdirs();
216    return ManagedFileAccess.file(path);
217  }
218
219  public static void copyFile(File sourceFile, File destFile) throws IOException {
220    if (!destFile.exists()) {
221      if (!ManagedFileAccess.csfile(destFile.getParent()).exists()) {
222        createDirectory(destFile.getParent());
223      }
224      destFile.createNewFile();
225    } else if (!destFile.getCanonicalFile().getName().equals(destFile.getName())) {
226      // case mismatch
227      destFile.delete();
228      destFile.createNewFile();
229    }
230  
231    FileInputStream source = null;
232    FileOutputStream destination = null;
233  
234    try {
235      source = ManagedFileAccess.inStream(sourceFile);
236      destination = ManagedFileAccess.outStream(destFile);
237      destination.getChannel().transferFrom(source.getChannel(), 0, source.getChannel().size());
238    } finally {
239      if (source != null) {
240        source.close();
241      }
242      if (destination != null) {
243        destination.close();
244      }
245    }
246  }
247
248  public static void copyFile(String source, String dest) throws IOException {
249    copyFile(ManagedFileAccess.file(source), ManagedFileAccess.file(dest));
250  }
251
252  public static void copyDirectory(String sourceFolder, String destFolder, FileNotifier notifier) throws IOException, FHIRException {
253    CSFile src = ManagedFileAccess.csfile(sourceFolder);
254    if (!src.exists())
255      throw new FHIRException("Folder " + sourceFolder + " not found");
256    File dst = ManagedFileAccess.file(destFolder);
257    if(!dst.getCanonicalFile().getName().equals(dst.getName())) {
258      File tmp = ManagedFileAccess.file(destFolder+System.currentTimeMillis());
259      if (!dst.renameTo(tmp)) {
260        throw new IOException("fixing case from "+dst.getCanonicalFile().getName()+" to "+tmp.getName()+" failed");
261      }
262      if (!tmp.renameTo(dst)) {
263        throw new IOException("fixing case from "+tmp.getCanonicalFile().getName()+" to "+dst.getName()+" failed");
264      }
265    } else if (!dst.exists()) {    
266      createDirectory(destFolder);
267    }
268  
269    String[] files = src.list();
270    for (String f : files) {
271      if (ManagedFileAccess.csfile(sourceFolder + File.separator + f).isDirectory()) {
272        if (!f.startsWith(".")) { // ignore .git files...
273          copyDirectory(sourceFolder + File.separator + f, destFolder + File.separator + f, notifier);
274        }
275      } else {
276        if (notifier != null)
277          notifier.copyFile(sourceFolder + File.separator + f, destFolder + File.separator + f);
278        FileUtilities.copyFile(ManagedFileAccess.csfile(sourceFolder + File.separator + f), new /*CS*/File(destFolder + File.separator + f)); // case doesn't have to match on the target
279      }
280    }
281  }
282
283  public static void copyDirectory2(String sourceFolder, String destFolder, FileNotifier2 notifier) throws IOException, FHIRException {
284    CSFile src = ManagedFileAccess.csfile(sourceFolder);
285    if (!src.exists())
286      throw new FHIRException("Folder " + sourceFolder + " not found");
287    createDirectory(destFolder);
288  
289    String[] files = src.list();
290    for (String f : files) {
291      if (ManagedFileAccess.csfile(sourceFolder + File.separator + f).isDirectory()) {
292        if (!f.startsWith(".")) { // ignore .git files...
293          boolean doCopy = notifier != null ? notifier.copyFolder(sourceFolder + File.separator + f, destFolder + File.separator + f) : true;
294          if (doCopy) {
295            copyDirectory2(sourceFolder + File.separator + f, destFolder + File.separator + f, notifier);
296          }
297        }
298      } else {
299        boolean doCopy = notifier != null ? notifier.copyFile(sourceFolder + File.separator + f, destFolder + File.separator + f) : true;
300        if (doCopy) {
301          FileUtilities.copyFile(ManagedFileAccess.csfile(sourceFolder + File.separator + f), ManagedFileAccess.csfile(destFolder + File.separator + f));
302        }
303      }
304    }
305  }
306
307  public static void copyFileToDirectory(File source, File destDir) throws IOException {
308    FileUtilities.copyFile(source, ManagedFileAccess.file(Utilities.path(destDir.getAbsolutePath(), source.getName())));
309  }
310
311  public static void renameDirectory(String source, String dest) throws FHIRException, IOException {
312    File src = ManagedFileAccess.file(source);
313    File dst = ManagedFileAccess.file(dest);
314    if (!src.renameTo(dst)) {
315      int i = 0;
316      do {
317        try {
318          Thread.sleep(20);
319        } catch (Exception e) {
320          // nothing
321        }
322        System.gc();
323        i++;
324      } while (!src.renameTo(dst) && i < 10);
325      if (src.exists()) {
326        copyDirectory(source, dest, null);
327        try {
328          src.delete(); 
329        } catch (Exception e) {
330          // nothing
331        }
332      }
333    }
334  
335  }
336
337  public static List<String> listAllFiles(String path, List<String> ignoreList) throws IOException {
338    List<String> res = new ArrayList<>();
339    scanForFiles(res, path, ManagedFileAccess.file(path), ignoreList);
340    return res;
341  }
342  
343  private static void scanForFiles(List<String> res, String root, File dir, List<String> ignoreList) {
344    for (File f : dir.listFiles()) {
345      if (ignoreList == null || !ignoreList.contains(f.getAbsolutePath())) {
346        if (f.isDirectory()) {
347          scanForFiles(res, root, f, ignoreList);
348        } else if (!f.getName().equals(".DS_Store")) {
349          res.add(getRelativePath(root, f.getAbsolutePath()));
350        }
351      }
352    }
353  }
354
355  /**
356   * Delete a directory atomically by first renaming it to a temp directory in
357   * its parent, and then deleting its contents.
358   *
359   * @param path The directory to delete.
360   */
361  public static void atomicDeleteDirectory(String path) throws IOException {
362
363      File directory = ManagedFileAccess.file(path);
364
365      String tempDirectoryPath = Utilities.generateUniqueRandomUUIDPath(directory.getParent());
366      File tempDirectory = ManagedFileAccess.file(tempDirectoryPath);
367     if (!directory.renameTo(tempDirectory)) {
368       throw new IOException("Unable to rename directory " + path + " to " + tempDirectory +" for atomic delete");
369     }
370     clearDirectory(tempDirectory.getAbsolutePath());
371     if (!tempDirectory.delete()) {
372       throw new IOException("Unable to delete temp directory " + tempDirectory + " when atomically deleting " + path);
373     }
374  }
375
376  public interface FileVisitor {
377    void visitFile(File file) throws FileNotFoundException, IOException;
378  }
379
380  public static void visitFiles(String folder, String extension, FileVisitor visitor) throws FileNotFoundException, IOException {
381    visitFiles(ManagedFileAccess.file(folder), extension, visitor);
382  }
383
384  public static void visitFiles(File folder, String extension, FileVisitor visitor) throws FileNotFoundException, IOException {
385    for (File file : folder.listFiles()) {
386      if (file.isDirectory())
387        visitFiles(file, extension, visitor);
388      else if (extension == null || file.getName().endsWith(extension))
389        visitor.visitFile(file);
390    }
391  }
392
393  public static int countFilesInDirectory(String dirName) throws IOException {
394    File dir = ManagedFileAccess.file(dirName);
395    if (dir.exists() == false) {
396      return 0;
397    }
398    int i = 0;
399    for (File f : dir.listFiles())
400      if (!f.isDirectory())
401        i++;
402    return i;
403  }
404
405  public static boolean checkFileExists(String purpose, String dir, String file, List<String> errors)
406      throws IOException {
407    if (!ManagedFileAccess.csfile(dir + file).exists()) {
408      if (errors != null)
409        errors.add("Unable to find " + purpose + " file " + file + " in " + dir);
410      return false;
411    } else {
412      return true;
413    }
414  }
415
416  public static boolean checkFolderExists(String dir, List<String> errors)
417      throws IOException {
418    if (!ManagedFileAccess.csfile(dir).exists()) {
419      errors.add("Unable to find directory " + dir);
420      return false;
421    } else {
422      return true;
423    }
424  }
425
426  public static File createTempFile(String prefix, String suffix) throws IOException {
427    // this allows use to eaily identify all our dtemp files and delete them, since delete on Exit doesn't really work.
428    File file = File.createTempFile("ohfu-" + prefix, suffix);
429    file.deleteOnExit();
430    return file;
431  }
432
433  public static void deleteTempFiles() throws IOException {
434    File file = createTempFile("test", "test");
435    String folder = getDirectoryForFile(file.getAbsolutePath());
436    String[] list = ManagedFileAccess.file(folder).list(new FilenameFilter() {
437      public boolean accept(File dir, String name) {
438        return name.startsWith("ohfu-");
439      }
440    });
441    if (list != null) {
442      for (String n : list) {
443        ManagedFileAccess.file(Utilities.path(folder, n)).delete();
444      }
445    }
446  }
447
448  public static void clearDirectory(String folder, String... exemptions) throws IOException {
449    File dir = ManagedFileAccess.file(folder);
450    if (dir.exists()) {
451      if (exemptions.length == 0)
452        FileUtils.cleanDirectory(dir);
453      else {
454        String[] files = ManagedFileAccess.csfile(folder).list();
455        if (files != null) {
456          for (String f : files) {
457            if (!Utilities.existsInList(f, exemptions)) {
458              File fh = ManagedFileAccess.csfile(folder + File.separatorChar + f);
459              if (fh.isDirectory())
460                clearDirectory(fh.getAbsolutePath());
461              fh.delete();
462            }
463          }
464        }
465      }
466    }
467  }
468  
469  public static void deleteAllFiles(String folder, String type) throws IOException {
470    File src = ManagedFileAccess.file(folder);
471    String[] files = src.list();
472    for (String f : files) {
473      if (ManagedFileAccess.file(folder + File.separator + f).isDirectory()) {
474        deleteAllFiles(folder + File.separator + f, type);
475      } else if (f.endsWith(type)) {
476        ManagedFileAccess.file(folder + File.separator + f).delete();
477      }
478    }
479  
480  }
481
482  public static String changeFileExt(String name, String ext) {
483    if (name.lastIndexOf('.') > -1)
484      return name.substring(0, name.lastIndexOf('.')) + ext;
485    else
486      return name + ext;
487  }
488
489  public static boolean isIgnorableFile(File file) {
490    return Utilities.existsInList(file.getName(), ".DS_Store");
491  }
492
493  public static void deleteEmptyFolders(File df) {
494    for (File f : df.listFiles()) {
495      if (f.isDirectory()) {
496        deleteEmptyFolders(f);
497      }
498    }
499    boolean empty = true;
500    for (File f : df.listFiles()) {
501      empty = false;
502      break;
503    }
504    if (empty) {
505      df.delete();
506    }
507  }
508
509  public static String cleanFileName(String badFileName) {
510    StringBuilder cleanName = new StringBuilder();
511    int len = badFileName.codePointCount(0, badFileName.length());
512    for (int i=0; i<len; i++) {
513      int c = badFileName.codePointAt(i);
514      if (Arrays.binarySearch(Utilities.illegalChars, c) < 0) {
515        cleanName.appendCodePoint(c);
516      }
517    }
518    return cleanName.toString();
519  }
520
521  public static void copyFiles(String source, String dest, String... extensions) throws IOException {
522    for (File f : new File(source).listFiles()) {
523      boolean copy = false;
524      for (String e : extensions) {
525        if (f.getName().endsWith(e)) {
526          copy = true;
527        }
528      }
529      if (copy) {
530        FileUtilities.copyFile(f.getAbsolutePath(), Utilities.path(dest, f.getName()));
531      }
532    }
533    
534  }
535
536}