001package org.hl7.fhir.utilities;
002
003import java.io.DataOutputStream;
004import java.io.IOException;
005import java.net.HttpURLConnection;
006import java.net.URL;
007import java.net.URLDecoder;
008import java.nio.charset.StandardCharsets;
009import java.util.ArrayList;
010import java.util.Base64;
011import java.util.HashMap;
012import java.util.List;
013import java.util.Map;
014
015import org.hl7.fhir.utilities.SimpleHTTPClient.HTTPResult;
016import org.hl7.fhir.utilities.SimpleHTTPClient.Header;
017import org.hl7.fhir.utilities.npm.SSLCertTruster;
018
019public class SimpleHTTPClient {
020  
021  public class Header {
022    private String name;
023    private String value;
024    public Header(String name, String value) {
025      super();
026      this.name = name;
027      this.value = value;
028    }
029    public String getName() {
030      return name;
031    }
032    public String getValue() {
033      return value;
034    }
035  }
036
037  private static final int MAX_REDIRECTS = 5;
038  private static int counter = 1;
039
040  public class HTTPResult {
041    private int code;
042    private String contentType;
043    private byte[] content;
044    private String source;
045    private String message;
046    
047    
048    public HTTPResult(String source, int code, String message, String contentType, byte[] content) {
049      super();
050      this.source = source;
051      this.code = code;
052      this.contentType = contentType;
053      this.content = content;
054      this.message = message;
055    }
056    
057    public int getCode() {
058      return code;
059    }
060    public String getContentType() {
061      return contentType;
062    }
063    public byte[] getContent() {
064      return content;
065    }
066
067    public String getSource() {
068      return source;
069    }
070
071    public void checkThrowException() throws IOException {
072      if (code >= 300) {
073        String filename = Utilities.path("[tmp]", "fhir-http-"+(++counter)+".log");
074        TextFile.bytesToFile(content, filename);
075        throw new IOException("Invalid HTTP response "+code+" from "+source+" ("+message+") (content in "+filename+")");
076      }      
077    }    
078  }
079
080  private List<Header> headers = new ArrayList<>();
081  private String username;
082  private String password;
083  
084  public void addHeader(String name, String value) {
085    headers.add(new Header(name, value));
086  }
087
088  public String getUsername() {
089    return username;
090  }
091
092  public void setUsername(String username) {
093    this.username = username;
094  }
095
096  public String getPassword() {
097    return password;
098  }
099
100  public void setPassword(String password) {
101    this.password = password;
102  }
103
104
105  private boolean trustAll = false;
106  
107  public void trustAllhosts() {
108    trustAll  = true;
109    SSLCertTruster.trustAllHosts();    
110  }
111 
112  public HTTPResult get(String url) throws IOException {
113    return get(url, null);    
114  }
115  
116  public HTTPResult get(String url, String accept) throws IOException {
117    URL u = new URL(url);
118//    boolean isSSL = url.startsWith("https://");
119    
120    // handling redirects - setInstanceFollowRedirects(true) doesn't handle crossing http to https
121
122    Map<String, Integer> visited = new HashMap<>();
123    HttpURLConnection c = null;
124    boolean done = false;
125
126    while (!done) {
127      int times = visited.compute(url, (key, count) -> count == null ? 1 : count + 1);
128      if (times > MAX_REDIRECTS)
129        throw new IOException("Stuck in redirect loop");
130
131      u = new URL(url);
132      c = (HttpURLConnection) u.openConnection();
133      c.setRequestMethod("GET");
134      c.setRequestProperty("Accept", accept);
135      setHeaders(c);
136      c.setInstanceFollowRedirects(false); 
137      if (trustAll && url.startsWith("https://")) {
138        ((javax.net.ssl.HttpsURLConnection) c).setHostnameVerifier(SSLCertTruster.DO_NOT_VERIFY);
139      }
140
141      switch (c.getResponseCode()) {
142      case HttpURLConnection.HTTP_MOVED_PERM:
143      case HttpURLConnection.HTTP_MOVED_TEMP:
144        String location = c.getHeaderField("Location");
145        location = URLDecoder.decode(location, "UTF-8");
146        URL base = new URL(url);               
147        URL next = new URL(base, location);  // Deal with relative URLs
148        url      = next.toExternalForm();
149        continue;
150      default:
151        done = true;
152      }
153    }
154    
155    return new HTTPResult(url, c.getResponseCode(), c.getResponseMessage(),  c.getRequestProperty("Content-Type"), TextFile.streamToBytes(c.getResponseCode() >= 400 ? c.getErrorStream() : c.getInputStream()));
156  }
157
158  private void setHeaders(HttpURLConnection c) {
159    for (Header h : headers) {
160      c.setRequestProperty(h.getName(), h.getValue());        
161    }
162    c.setConnectTimeout(15000);
163    c.setReadTimeout(15000);
164    if (username != null) {
165      String auth = username+":"+password;
166      byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(StandardCharsets.UTF_8));
167      String authHeaderValue = "Basic " + new String(encodedAuth);
168      c.setRequestProperty("Authorization", authHeaderValue);
169    }
170  }
171
172  public HTTPResult post(String url, String contentType, byte[] content, String accept) throws IOException {
173    URL u = new URL(url);
174    HttpURLConnection c = (HttpURLConnection) u.openConnection();
175    c.setDoOutput(true);
176    c.setDoInput(true);
177    c.setRequestMethod("POST");
178    c.setRequestProperty("Content-type", contentType);
179    if (accept != null) {
180      c.setRequestProperty("Accept", accept);
181    }
182    setHeaders(c);
183    c.getOutputStream().write(content);
184    c.getOutputStream().close();    
185    return new HTTPResult(url, c.getResponseCode(), c.getResponseMessage(), c.getRequestProperty("Content-Type"), TextFile.streamToBytes(c.getResponseCode() >= 400 ? c.getErrorStream() : c.getInputStream()));
186  }
187
188 
189  public HTTPResult put(String url, String contentType, byte[] content, String accept) throws IOException {
190    URL u = new URL(url);
191    HttpURLConnection c = (HttpURLConnection) u.openConnection();
192    c.setDoOutput(true);
193    c.setDoInput(true);
194    c.setRequestMethod("PUT");
195    c.setRequestProperty("Content-type", contentType);
196    if (accept != null) {
197      c.setRequestProperty("Accept", accept);
198    }
199    setHeaders(c);
200    c.getOutputStream().write(content);
201    c.getOutputStream().close();    
202    return new HTTPResult(url, c.getResponseCode(), c.getResponseMessage(), c.getRequestProperty("Content-Type"), TextFile.streamToBytes(c.getResponseCode() >= 400 ? c.getErrorStream() : c.getInputStream()));
203  }
204
205
206}