001package org.hl7.fhir.validation.cli.utils;
002
003import org.apache.commons.io.IOUtils;
004import org.hl7.fhir.exceptions.FHIRException;
005import org.hl7.fhir.utilities.SimpleHTTPClient;
006import org.hl7.fhir.utilities.SimpleHTTPClient.HTTPResult;
007import org.hl7.fhir.utilities.TextFile;
008import org.hl7.fhir.utilities.Utilities;
009
010import java.io.ByteArrayInputStream;
011import java.io.File;
012import java.io.IOException;
013
014public class ProfileLoader {
015  public static byte[] loadProfileSource(String src) throws FHIRException, IOException {
016    if (Utilities.noString(src)) {
017      throw new FHIRException("Profile Source '" + src + "' could not be processed");
018    } else if (Common.isNetworkPath(src)) {
019      return loadProfileFromUrl(src);
020    } else if (new File(src).exists()) {
021      return loadProfileFromFile(src);
022    } else {
023      throw new FHIRException("Definitions Source '" + src + "' could not be processed");
024    }
025  }
026
027  private static byte[] loadProfileFromUrl(String src) throws FHIRException {
028    try {
029      SimpleHTTPClient http = new SimpleHTTPClient();
030      HTTPResult res = http.get(src + "?nocache=" + System.currentTimeMillis());
031      res.checkThrowException();
032      return res.getContent();
033    } catch (Exception e) {
034      throw new FHIRException("Unable to find definitions at URL '" + src + "': " + e.getMessage(), e);
035    }
036  }
037
038  private static byte[] loadProfileFromFile(String src) throws IOException {
039    File f = new File(src);
040    if (f.isDirectory())
041      throw new IOException("You must provide a file name, not a directory name");
042    return TextFile.fileToBytes(src);
043  }
044
045}