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