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

package foam.nanos.http;

import com.sun.net.httpserver.*;
import foam.core.*;
import foam.nanos.*;
import java.io.IOException;
import java.net.URI;
import javax.servlet.http.HttpServlet;

public class NanoHttpHandler
  implements HttpHandler
{
  protected X x_;

  public NanoHttpHandler(X x) {
    x_ = x;
  }

  @Override
  public void handle(HttpExchange exchange) throws IOException {
    URI    requestURI = exchange.getRequestURI();
    String path       = requestURI.getPath();
    String query      = requestURI.getQuery();

    // AuthService auth = this.X.get(AuthService);

    String[] urlParams = path.split("/");

    /*
     * Get the item right after the first slash
     * E.g.: /foo/bar => ['', 'foo', 'bar']
    */
    String serviceKey = urlParams[1];
    Object service    = x_.get(serviceKey);

    System.out.println("HTTP Request: " + path + ", " + serviceKey);

    if ( service instanceof HttpHandler ) {
      // if ( auth.checkPermission(...) ) {}

      ((HttpHandler) service).handle(exchange);
    } if ( service instanceof HttpServlet ) {
      // if ( auth.checkPermission(...) ) {}

      new ServletHandler((HttpServlet) service).handle(exchange);
    } else {
      String errorMsg = "Service " + serviceKey + " does not have a HttpHandler";

      throw new RuntimeException(errorMsg);
    }
  }
}

@@ -192,24 +192,45 @@
 oam.core.*;%0A
+import foam.dao.DAO;%0A
 import foam.
@@ -356,16 +356,49 @@
 Handler%0A
+  extends    ContextAwareSupport%0A
   implem
@@ -419,26 +419,8 @@
 er%0A%7B
-%0A  protected X x_;
 %0A%0A  
@@ -1281,26 +1281,26 @@
     
-new ServletHandler
+this.handleServlet
 ((Ht
@@ -1313,33 +1313,175 @@
 let) service
-).handle(
+, exchange);%0A    %7D if ( service instanceof DAO ) %7B%0A      // todo auth check, server==true check%0A%0A      this.handleServlet(new ServiceServlet(service), 
 exchange);%0A 
@@ -1628,11 +1628,223 @@
    %7D%0A  %7D
+%0A%0A  public void handleServlet(HttpServlet s, HttpExchange exchange) throws IOException %7B%0A    if ( s instanceof ContextAware ) ((ContextAware) s).setX(this.getX());%0A%0A    new ServletHandler(s).handle(exchange);%0A  %7D
 %0A%7D%0A

Add support for serving DAO's.