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