/**
 * @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.nanos.dig.Format;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpException;

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(FObject 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(OutputterMode.NETWORK);
        conn.addRequestProperty("Accept", "application/json");
        conn.addRequestProperty("Content-Type", "application/json");
      } else if ( format_ == Format.XML ) {
        // TODO: make XML Outputter
        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(obj));
      writer.flush();
      writer.close();
      os.close();

      // check response code
      int code = conn.getResponseCode();
      if ( code != HttpServletResponse.SC_OK ) {
        throw new HttpException();
      }
    } catch (Throwable t) {
      throw new RuntimeException(t);
    } finally {
      IOUtils.closeQuietly(writer);
      IOUtils.closeQuietly(os);
      if ( conn != null ) {
        conn.disconnect();
      }
    }
  }
}
@@ -325,46 +325,8 @@
 ils;
-%0Aimport org.apache.http.HttpException;
 %0A%0Aim
@@ -1914,20 +1914,23 @@
 row new 
-Http
+Runtime
 Exceptio
@@ -1927,24 +1927,57 @@
 meException(
+%22Http server did not return 200.%22
 );%0A      %7D%0A 
@@ -2198,8 +2198,9 @@
  %7D%0A  %7D%0A%7D
+%0A

Remove dependency on org.apache.http.HttpException for HTTPSink