/**
 * @license
 * Copyright 2018 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package foam.dao;

import foam.core.Detachable;
import foam.core.FObject;
import foam.lib.Outputter;
import foam.lib.json.OutputterMode;
import foam.lib.NetworkPropertyPredicate;
import foam.nanos.http.Format;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class HTTPSink
    extends AbstractSink
{
  protected String url_;
  protected Format format_;

  public HTTPSink(String url, Format format) throws IOException {
    url_ = url;
    format_ = format;
  }

  @Override
  public void put(Object obj, Detachable sub) {
    HttpURLConnection conn = null;
    OutputStream os = null;
    BufferedWriter writer = null;

    try {
      Outputter outputter = null;
      conn = (HttpURLConnection) new URL(url_).openConnection();
      conn.setRequestMethod("POST");
      conn.setDoInput(true);
      conn.setDoOutput(true);
      if ( format_ == Format.JSON ) {
        outputter = new foam.lib.json.Outputter(getX()).setPropertyPredicate(new NetworkPropertyPredicate());
        conn.addRequestProperty("Accept", "application/json");
        conn.addRequestProperty("Content-Type", "application/json");
      } else if ( format_ == Format.XML ) {
        outputter = new foam.lib.xml.Outputter(OutputterMode.NETWORK);
        conn.addRequestProperty("Accept", "application/xml");
        conn.addRequestProperty("Content-Type", "application/xml");
      }
      conn.connect();

      os = conn.getOutputStream();
      writer = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
      writer.write(outputter.stringify((FObject)obj));
      writer.flush();
      writer.close();
      os.close();

      // check response code
      int code = conn.getResponseCode();
      if ( code != HttpServletResponse.SC_OK ) {
        throw new RuntimeException("Http server did not return 200.");
      }
    } catch (Throwable t) {
      throw new RuntimeException(t);
    } finally {
      IOUtils.closeQuietly(writer);
      IOUtils.closeQuietly(os);
      if ( conn != null ) {
        conn.disconnect();
      }
    }
  }
}

@@ -327,16 +327,45 @@
 Format;%0A
+import foam.util.SafetyUtil;%0A
 import o
@@ -633,16 +633,49 @@
 g url_;%0A
+  protected String bearerToken_;%0A
   protec
@@ -744,43 +744,155 @@
 at) 
-throws IOException %7B%0A    url_ = url
+%7B%0A    this(url, %22%22, format);%0A  %7D%0A%0A  public HTTPSink(String url, String bearerToken, Format format) %7B%0A    url_ = url;%0A    bearerToken_ = bearerToken
 ;%0A  
@@ -1216,24 +1216,158 @@
 od(%22POST%22);%0A
+      if ( ! SafetyUtil.isEmpty(bearerToken_) ) %7B%0A        conn.setRequestProperty(%22Authorization%22, %22Bearer %22 + bearerToken_);%0A      %7D%0A
       conn.s

Add bearer token support to HTTPSink