001package org.hl7.fhir.utilities.http;
002
003import java.io.IOException;
004import java.net.HttpURLConnection;
005import java.net.URL;
006import java.net.URLDecoder;
007import java.nio.charset.StandardCharsets;
008import java.util.ArrayList;
009import java.util.Base64;
010import java.util.HashMap;
011import java.util.List;
012import java.util.Map;
013
014import org.hl7.fhir.exceptions.FHIRException;
015import org.hl7.fhir.utilities.FileUtilities;
016import org.hl7.fhir.utilities.settings.FhirSettings;
017
018import lombok.Getter;
019import lombok.Setter;
020
021public class SimpleHTTPClient {
022
023  private static final int MAX_REDIRECTS = 5;
024  private static int counter = 1;
025
026  private List<HTTPHeader> headers = new ArrayList<>();
027
028  @Getter @Setter
029  private HTTPAuthenticationMode authenticationMode;
030
031  @Getter @Setter
032  private String username;
033
034  @Getter @Setter
035  private String password;
036
037  @Getter @Setter
038  private String token;
039  
040  @Getter @Setter
041  private String apiKey;
042  
043  public void addHeader(String name, String value) {
044    headers.add(new HTTPHeader(name, value));
045  }
046
047  public HTTPResult get(String url) throws IOException {
048    return get(url, null);    
049  }
050  
051  public HTTPResult get(String url, String accept) throws IOException {
052    if (FhirSettings.isProhibitNetworkAccess()) {
053      throw new FHIRException("Network Access is prohibited in this context");
054    }
055    
056    URL u = new URL(url);
057//    boolean isSSL = url.startsWith("https://");
058    
059    // handling redirects - setInstanceFollowRedirects(true) doesn't handle crossing http to https
060
061    Map<String, Integer> visited = new HashMap<>();
062    HttpURLConnection c = null;
063    boolean done = false;
064
065    while (!done) {
066      int times = visited.compute(url, (key, count) -> count == null ? 1 : count + 1);
067      if (times > MAX_REDIRECTS)
068        throw new IOException("Stuck in redirect loop");
069
070      u = new URL(url);
071      c = (HttpURLConnection) u.openConnection();
072      c.setRequestMethod("GET");
073      if (accept != null) {
074        c.setRequestProperty("Accept", accept);
075      }
076      setHeaders(c);
077      c.setInstanceFollowRedirects(false);
078
079      switch (c.getResponseCode()) {
080        case HttpURLConnection.HTTP_MOVED_PERM:
081        case HttpURLConnection.HTTP_MOVED_TEMP:
082        case 307:
083        case 308: // Same as HTTP_MOVED_PERM, but does not allow changing the request method from POST to GET
084          String location = c.getHeaderField("Location");
085          location = URLDecoder.decode(location, "UTF-8");
086          URL base = new URL(url);
087          URL next = new URL(base, location);  // Deal with relative URLs
088          url = next.toExternalForm();
089          continue;
090        default:
091          done = true;
092      }
093    }
094    
095    return new HTTPResult(url, c.getResponseCode(), c.getResponseMessage(),  c.getRequestProperty("Content-Type"), FileUtilities.streamToBytes(c.getResponseCode() >= 400 ? c.getErrorStream() : c.getInputStream()));
096  }
097
098  private void setHeaders(HttpURLConnection c) {
099    if (headers != null) {
100      for (HTTPHeader header : headers) {
101        c.setRequestProperty(header.getName(), header.getValue());
102      }
103    }
104    c.setConnectTimeout(15000);
105    c.setReadTimeout(15000);
106    setAuthenticationHeader(c);
107  }
108
109  private void setAuthenticationHeader(HttpURLConnection c) {
110    String authHeaderValue = null;
111    if (authenticationMode == HTTPAuthenticationMode.TOKEN) {
112      authHeaderValue = "Bearer " + token;
113    } else if (authenticationMode == HTTPAuthenticationMode.BASIC) {
114      String auth = username+":"+password;
115      byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(StandardCharsets.UTF_8));
116      authHeaderValue = "Basic " + new String(encodedAuth);
117    } else if (authenticationMode == HTTPAuthenticationMode.APIKEY) {
118      c.setRequestProperty("Api-Key", apiKey);
119    }
120
121    if (authHeaderValue != null) {
122      c.setRequestProperty("Authorization", authHeaderValue);
123    }
124  }
125
126  public HTTPResult post(String url, String contentType, byte[] content, String accept) throws IOException {
127    if (FhirSettings.isProhibitNetworkAccess()) {
128      throw new FHIRException("Network Access is prohibited in this context");
129    }
130    URL u = new URL(url);
131    HttpURLConnection c = (HttpURLConnection) u.openConnection();
132    c.setDoOutput(true);
133    c.setDoInput(true);
134    c.setRequestMethod("POST");
135    c.setRequestProperty("Content-Type", contentType);
136    if (accept != null) {
137      c.setRequestProperty("Accept", accept);
138    }
139    setHeaders(c);
140    c.getOutputStream().write(content);
141    c.getOutputStream().close();    
142    return new HTTPResult(url, c.getResponseCode(), c.getResponseMessage(), c.getRequestProperty("Content-Type"), FileUtilities.streamToBytes(c.getResponseCode() >= 400 ? c.getErrorStream() : c.getInputStream()));
143  }
144
145 
146  public HTTPResult put(String url, String contentType, byte[] content, String accept) throws IOException {
147    if (FhirSettings.isProhibitNetworkAccess()) {
148      throw new FHIRException("Network Access is prohibited in this context");
149    }
150    URL u = new URL(url);
151    HttpURLConnection c = (HttpURLConnection) u.openConnection();
152    c.setDoOutput(true);
153    c.setDoInput(true);
154    c.setRequestMethod("PUT");
155    c.setRequestProperty("Content-type", contentType);
156    if (accept != null) {
157      c.setRequestProperty("Accept", accept);
158    }
159    setHeaders(c);
160    c.getOutputStream().write(content);
161    c.getOutputStream().close();    
162    return new HTTPResult(url, c.getResponseCode(), c.getResponseMessage(), c.getRequestProperty("Content-Type"), FileUtilities.streamToBytes(c.getResponseCode() >= 400 ? c.getErrorStream() : c.getInputStream()));
163  }
164
165  public static int nextCounter() {
166    return ++counter;
167  }
168
169
170}