<commit_before>package org.openmole.web

import _root_.akka.actor.ActorSystem
import org.scalatra._
import scalate.ScalateSupport
import servlet.{ FileItem, FileUploadSupport }
import java.io.{ PrintStream, File, InputStream }
import javax.servlet.annotation.MultipartConfig

import org.openmole.core.serializer._
import org.openmole.core.model.mole.{ IPartialMoleExecution, IMoleExecution, ExecutionContext }
import org.openmole.core.model.data.{ Context, Prototype, Variable }
import com.thoughtworks.xstream.mapper.CannotResolveClassException
import concurrent.Future

import slick.driver.H2Driver.simple._
import slick.jdbc.meta.MTable

import org.openmole.misc.tools.io.FromString

import org.openmole.misc.eventdispatcher.EventDispatcher

import Database.threadLocalSession

import javax.sql.rowset.serial.SerialClob
import reflect.ClassTag
import json.JacksonJsonSupport
import org.json4s._
import org.json4s.JsonDSL._
import scala.None
import org.json4s.{ Formats, DefaultFormats }
import org.openmole.core.implementation.validation.Validation
import org.openmole.core.implementation.validation.DataflowProblem.{ MissingSourceInput, MissingInput, WrongType }
import scala.io.Source
import org.openmole.core.model.mole.IMoleExecution.JobStatusChanged
import org.openmole.misc.eventdispatcher.{ Event, EventListener }

@MultipartConfig(maxFileSize = 3145728 /*max file size of 3 MiB*/ ) //research scala multipart config
class MoleRunner(val system: ActorSystem) extends ScalatraServlet with SlickSupport with ScalateSupport
    with FileUploadSupport with FlashMapSupport with FutureSupport with JacksonJsonSupport with MoleHandling with Authentication {

  protected implicit val jsonFormats: Formats = DefaultFormats.withBigDecimal

  /*val cachedMoles = new DataHandler[String, IMoleExecution](system)
  val moleStats = new DataHandler[String, Stats.Stats](system)

  val listener: EventListener[IMoleExecution] = new JobEventListener(moleStats)*/

  get("/index.html") {
    contentType = "text/html"

    new AsyncResult() {
      val is = Future {
        ssp("/index.ssp")
      }
    }
  }

  get("/") {
    new AsyncResult() {
      val is = Future { redirect(url("index.html")) }
    }
  }

  get("/createMole") {
    contentType = "text/html"
    new AsyncResult() {
      val is = Future {
        requireAuth(cookies get "apiKey") {
          ssp("/createMole", "body" -> "Please upload a serialized mole execution below!")
        } {
          ssp("/authenticate.ssp", "goTo" -> "/createMole")
        }
      }
    }
  }

  post("/createMole") {

    val data = fileParams.get("file")

    val inS = data.map(_.getInputStream)

    val csv = fileParams.get("csv")

    val molePack = params get "pack" match {
      case Some("on") ⇒ true
      case _          ⇒ false
    }

    val cnS = csv.map(_.getInputStream)

    val encapsulate = params get "encapsulate" match {
      case Some("on") ⇒ true
      case _          ⇒ false
    }

    //TODO: make sure this is released

    new AsyncResult {
      val is = Future {
        requireAuth(cookies get "apiKey" orElse (request.headers get "apiKey")) {
          contentType = "text/html"

          createMole(inS, cnS, encapsulate, pack = molePack) match {
            case Left(error) ⇒ ssp("/createMole", "body" -> "Please upload a serialized mole execution below!", "errors" -> List(error))
            case _           ⇒ redirect(url("execs"))
          }
        } {
          halt(status = 401, headers = Map("WWW-Authenticate" -> "apiKey"))
        }
      }
    }
  }

  post("/getApiKey") {
    contentType = "text/plain"
    new AsyncResult() {
      val is = Future {
        logger.info("received apiKey request")
        try {
          request.headers get "pass" map (issueKey(_, request.getRemoteHost)) foreach (cookies("apiKey") = _)
          cookies get "apiKey" foreach (k ⇒ logger.info(s"created api key: $k"))
          ""
        }
        catch {
          case e: InvalidPasswordException ⇒ "Invalid password entered"
        }
      }
    }
  }

  post("/json/getApiKey") {
    contentType = formats("json")

    new AsyncResult {
      val is = Future { request.headers get "pass" map (issueKey(_, request.getRemoteHost)) map (render("apiKey", _)) getOrElse render("error", "no password or incorrect password") }
    }
  }

  post("/xml/getApiKey") {
    contentType = "application/xml"

    new AsyncResult() {
      val is = Future(request.headers get "pass" map (issueKey(_, request.getRemoteHost)) map (k ⇒ <apiKey>${ k }</apiKey>) getOrElse <error>"no password or incorrect password"</error>)
    }
  }

  post("/xml/createMole") {
    contentType = "application/xml"

    requireAuth(request.headers get "apiKey") {
      println("starting the create operation")
      val encapsulate = params get "encapsulate" match {
        case Some("on") ⇒ true<commit_msg>Authentication now works for the most part. I still need to add an http page for authentication failure and for logging in.<commit_after>package org.openmole.web

import _root_.akka.actor.ActorSystem
import org.scalatra._
import scalate.ScalateSupport
import servlet.{ FileItem, FileUploadSupport }
import java.io.{ PrintStream, File, InputStream }
import javax.servlet.annotation.MultipartConfig

import org.openmole.core.serializer._
import org.openmole.core.model.mole.{ IPartialMoleExecution, IMoleExecution, ExecutionContext }
import org.openmole.core.model.data.{ Context, Prototype, Variable }
import com.thoughtworks.xstream.mapper.CannotResolveClassException
import concurrent.Future

import slick.driver.H2Driver.simple._
import slick.jdbc.meta.MTable

import org.openmole.misc.tools.io.FromString

import org.openmole.misc.eventdispatcher.EventDispatcher

import Database.threadLocalSession

import javax.sql.rowset.serial.SerialClob
import reflect.ClassTag
import json.JacksonJsonSupport
import org.json4s._
import org.json4s.JsonDSL._
import scala.None
import org.json4s.{ Formats, DefaultFormats }
import org.openmole.core.implementation.validation.Validation
import org.openmole.core.implementation.validation.DataflowProblem.{ MissingSourceInput, MissingInput, WrongType }
import scala.io.Source
import org.openmole.core.model.mole.IMoleExecution.JobStatusChanged
import org.openmole.misc.eventdispatcher.{ Event, EventListener }

@MultipartConfig(maxFileSize = 3145728 /*max file size of 3 MiB*/ ) //research scala multipart config
class MoleRunner(val system: ActorSystem) extends ScalatraServlet with SlickSupport with ScalateSupport
    with FileUploadSupport with FlashMapSupport with FutureSupport with JacksonJsonSupport with MoleHandling with Authentication {

  protected implicit val jsonFormats: Formats = DefaultFormats.withBigDecimal

  /*val cachedMoles = new DataHandler[String, IMoleExecution](system)
  val moleStats = new DataHandler[String, Stats.Stats](system)

  val listener: EventListener[IMoleExecution] = new JobEventListener(moleStats)*/

  get("/index.html") {
    contentType = "text/html"

    new AsyncResult() {
      val is = Future {
        ssp("/index.ssp")
      }
    }
  }

  get("/") {
    new AsyncResult() {
      val is = Future { redirect(url("index.html")) }
    }
  }

  get("/createMole") {
    contentType = "text/html"
    new AsyncResult() {
      val is = Future {
        requireAuth(cookies get "apiKey") {
          ssp("/createMole", "body" -> "Please upload a serialized mole execution below!")
        } {
          ssp("/authenticate.ssp", "goTo" -> "/createMole")
        }
      }
    }
  }

  post("/createMole") {

    val data = fileParams.get("file")

    val inS = data.map(_.getInputStream)

    val csv = fileParams.get("csv")

    val molePack = params get "pack" match {
      case Some("on") ⇒ true
      case _          ⇒ false
    }

    val cnS = csv.map(_.getInputStream)

    val encapsulate = params get "encapsulate" match {
      case Some("on") ⇒ true
      case _          ⇒ false
    }

    //TODO: make sure this is released

    new AsyncResult {
      val is = Future {
        requireAuth(cookies get "apiKey" orElse (request.headers get "apiKey")) {
          contentType = "text/html"

          createMole(inS, cnS, encapsulate, pack = molePack) match {
            case Left(error) ⇒ ssp("/createMole", "body" -> "Please upload a serialized mole execution below!", "errors" -> List(error))
            case _           ⇒ redirect(url("execs"))
          }
        } {
          halt(status = 401, headers = Map("WWW-Authenticate" -> "apiKey"))
        }
      }
    }
  }

  post("/getApiKey") {
    contentType = "text/plain"
    new AsyncResult() {
      val is = Future {
        logger.info("received apiKey request")
        try {
          request.headers get "pass" map issueKey foreach (cookies("apiKey") = _)
          cookies get "apiKey" foreach (k ⇒ logger.info(s"created api key: $k"))
          ""
        }
        catch {
          case e: InvalidPasswordException ⇒ "Invalid password entered"
        }
      }
    }
  }

  post("/json/getApiKey") {
    contentType = formats("json")

    new AsyncResult {
      val is = Future { request.headers get "pass" map issueKey map (render("apiKey", _)) getOrElse render("error", "no password or incorrect password") }
    }
  }

  post("/xml/getApiKey") {
    contentType = "application/xml"

    new AsyncResult() {
      val is = Future(request.headers get "pass" map issueKey map (k ⇒ <apiKey>${ k }</apiKey>) getOrElse <error>"no password or incorrect password"</error>)
    }
  }

  post("/xml/createMole") {
    contentType = "application/xml"

    requireAuth(request.headers get "apiKey") {
      println("starting the create operation")
      val encapsulate = params get "encapsulate" match {
        case Some("on") ⇒ true
{'fraction_non_alphanumeric': 0.11299897645854658, 'fraction_numerical': 0.0030706243602865915, 'mean_word_length': 3.1367485182049113, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 8}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7059624', 'n_tokens_mistral': 3012, 'n_tokens_neox': 2907, 'n_words': 743}