001package org.hl7.fhir.validation.testexecutor;
002
003import java.io.FileOutputStream;
004import java.io.IOException;
005import java.net.URL;
006import java.nio.file.Path;
007import java.nio.file.Paths;
008import java.util.zip.ZipEntry;
009import java.util.zip.ZipInputStream;
010
011public class TxCacheResourceExtractor {
012  public static void extractTxCacheResources(String targetDirectory) throws IOException {
013    Path targetPath = Paths.get(targetDirectory);
014
015    URL jar = TestExecutor.class.getProtectionDomain().getCodeSource().getLocation();
016    ZipInputStream zip = new ZipInputStream(jar.openStream());
017    while(true) {
018      ZipEntry e = zip.getNextEntry();
019      if (e == null)
020        break;
021      processZipEntry(zip, targetPath, e);
022    }
023  }
024
025  private static void processZipEntry(ZipInputStream zip, Path targetPath, ZipEntry e) throws IOException {
026    String name = e.getName();
027    if (!name.startsWith(TestExecutor.TX_CACHE)) {
028      zip.closeEntry();
029      return;
030    }
031
032    Path sourcePath = Paths.get(name);
033    if (sourcePath.getNameCount() <= 1) {
034      zip.closeEntry();
035      return;
036    }
037
038    if (e.isDirectory()) {
039      zip.closeEntry();
040      return;
041    }
042    extractFileFromZipInputStream(zip, sourcePath, targetPath);
043  }
044
045  private static void extractFileFromZipInputStream(ZipInputStream zip, Path sourcePath, Path targetPath) throws IOException {
046    Path fileTargetPath = targetPath.resolve(sourcePath.subpath(1, sourcePath.getNameCount()));
047
048    makeFileParentDirsIfNotExist(fileTargetPath);
049
050    FileOutputStream fileOutputStream = new FileOutputStream(fileTargetPath.toFile());
051    for (int c = zip.read(); c != -1; c = zip.read()) {
052      fileOutputStream.write(c);
053    }
054    zip.closeEntry();
055    fileOutputStream.close();
056  }
057
058  private static void makeFileParentDirsIfNotExist(Path filePath) {
059    Path parent = filePath.getParent();
060    if (!parent.toFile().exists()) {
061      parent.toFile().mkdirs();
062    }
063  }
064}