<commit_before>package org.mbari.odss.services.timeline

import org.scalatra.swagger._

import com.mongodb.casbah.Imports._
import scala.Some
import org.json4s.JsonAST.JString
import com.typesafe.scalalogging.slf4j.Logging


/**
 * Controller for the tokens route.
 *
 * @param app
 * @param swagger
 */
class TokensController(implicit val app: App,
                       implicit val swagger: Swagger) extends OdssPlatformTimelineStack with Logging {

  val platformColl = app.platformColl
  val tokenColl = app.tokenColl
  val periodColl = app.periodColl


  override protected val applicationName = Some("tokens")
  protected val applicationDescription = "Tokens REST API"


  val apiGet =
    (apiOperation[List[Token]]("getTokens")
      summary "Gets tokens"
      notes "Gets the tokens intersecting a time period as indicated by optional parameters."
      parameters(
      queryParam[Option[String]]("from").description("Lower date-time limit"),
      queryParam[Option[String]]("to").  description("Upper date-time limit")))

  get("/", operation(apiGet)) {
    logger.info("GET /tokens  params=" + params)

    val query = MongoDBObject()
    params.get("from") foreach {from => query.putAll("start" $gte from)}
    params.get("to")   foreach {to   => query.putAll("end"   $lte to)}
    logger.info("query = " + query)

    val found = tokenColl.find(query)
    val res = found map {e =>
      for {
        id           <- e.getAs[ObjectId]("_id")
        platform_id  <- e.getAs[String]("platform_id")
        start        <- e.getAs[String]("start")
        end          <- e.getAs[String]("end")
        state        <- e.getAs[String]("state")
      } yield Token(Some(id.toString), platform_id, start, end, state)
    }
    // sort by start date (mainly for debugging purposes)
    res.toList.filter(_ != None) sortWith (_.get.start < _.get.start)
  }

  val apiFindById =
    (apiOperation[Token]("findById")
      summary "Finds a token by its id"
      parameter pathParam[String]("id").description("ID of desired token"))

  get("/:id", operation(apiFindById)) {
    val id = params("id")
    logger.info("GET /tokens/" + id)
    val query = MongoDBObject("_id" -> new ObjectId(id))
    val found = tokenColl.find(query)
    val res = found map {e =>
      for {
        platform <- e.getAs[String]("platform_id")
        start    <- e.getAs[String]("start")
        end      <- e.getAs[String]("end")
        state    <- e.getAs[String]("state")
      } yield Token(Some(id), platform, start, end, state)
    }
    res.toSet
  }

  val apiAdd =
    (apiOperation[Token]("addToken")
      summary "Add a new token"
      notes dateTimeNotes
      parameters(
        queryParam[String]("platform_id").description("ID of associated platform"),
        queryParam[String]("start").      description("Start date for the token"),
        queryParam[String]("end").        description("End date for the token"),
        queryParam[String]("state").      description("State or activity")))

  post("/", operation(apiAdd)) {
    logger.debug("POST token body = " + request.body)

//    val token = parsedBody.extract[Token]
//    logger.debug("POST token = " + token)
//
//    val newObj = MongoDBObject("platform_id" -> token.platform_id,
//                               "start"       -> token.start,
//                               "end"         -> token.end,
//                               "state"       -> token.state)

    val platform_id  = params.get("platform_id").get
    val start        = params.get("start").get
    val end          = params.get("end").get
    val state        = params.get("state").get

    val newObj = MongoDBObject("platform_id" -> platform_id,
                               "start"       -> start,
                               "end"         -> end,
                               "state"       -> state)
    logger.debug("POST token = " + newObj)

    tokenColl += newObj

    val id = for (x <- newObj.getAs[ObjectId]("_id")) yield x.toString

    logger.info("Token posted: " + newObj + "   id = " + id)

    //token.copy(id=id)
    Token(id, platform_id, start, end, state)
  }


  val apiUpdate =
    (apiOperation[Token]("updateToken")
      summary "Updates a token"
      notes dateTimeNotes +
         "<br /> TODO: all parameters are required at the moment but they should be optional (except for the id)."
      parameters(
        pathParam[String]("id").            description("ID of the token to be updated"),
        queryParam[String]("platform_id").  description("ID of associated platform"),
        queryParam[String]("start").        description("Start date for the token"),
        queryParam[String]("end").          description("End date for the token"),
        queryParam[String]("state").        description("State or activity")))

  put("/:id", operation(apiUpdate)) {
    logger.info("PUT: " + params)
    val id = params("id")
    val obj = MongoDBObject("_id" -> new ObjectId(id))<commit_msg>logging to explore weird behavior in deployment on odss-test when updating a token<commit_after>package org.mbari.odss.services.timeline

import org.scalatra.swagger._

import com.mongodb.casbah.Imports._
import scala.Some
import org.json4s.JsonAST.JString
import com.typesafe.scalalogging.slf4j.Logging


/**
 * Controller for the tokens route.
 *
 * @param app
 * @param swagger
 */
class TokensController(implicit val app: App,
                       implicit val swagger: Swagger) extends OdssPlatformTimelineStack with Logging {

  val platformColl = app.platformColl
  val tokenColl = app.tokenColl
  val periodColl = app.periodColl


  override protected val applicationName = Some("tokens")
  protected val applicationDescription = "Tokens REST API"


  val apiGet =
    (apiOperation[List[Token]]("getTokens")
      summary "Gets tokens"
      notes "Gets the tokens intersecting a time period as indicated by optional parameters."
      parameters(
      queryParam[Option[String]]("from").description("Lower date-time limit"),
      queryParam[Option[String]]("to").  description("Upper date-time limit")))

  get("/", operation(apiGet)) {
    logger.info("GET /tokens  params=" + params)

    val query = MongoDBObject()
    params.get("from") foreach {from => query.putAll("start" $gte from)}
    params.get("to")   foreach {to   => query.putAll("end"   $lte to)}
    logger.info("query = " + query)

    val found = tokenColl.find(query)
    val res = found map {e =>
      for {
        id           <- e.getAs[ObjectId]("_id")
        platform_id  <- e.getAs[String]("platform_id")
        start        <- e.getAs[String]("start")
        end          <- e.getAs[String]("end")
        state        <- e.getAs[String]("state")
      } yield Token(Some(id.toString), platform_id, start, end, state)
    }
    // sort by start date (mainly for debugging purposes)
    res.toList.filter(_ != None) sortWith (_.get.start < _.get.start)
  }

  val apiFindById =
    (apiOperation[Token]("findById")
      summary "Finds a token by its id"
      parameter pathParam[String]("id").description("ID of desired token"))

  get("/:id", operation(apiFindById)) {
    val id = params("id")
    logger.info("GET /tokens/" + id)
    val query = MongoDBObject("_id" -> new ObjectId(id))
    val found = tokenColl.find(query)
    val res = found map {e =>
      for {
        platform <- e.getAs[String]("platform_id")
        start    <- e.getAs[String]("start")
        end      <- e.getAs[String]("end")
        state    <- e.getAs[String]("state")
      } yield Token(Some(id), platform, start, end, state)
    }
    res.toSet
  }

  val apiAdd =
    (apiOperation[Token]("addToken")
      summary "Add a new token"
      notes dateTimeNotes
      parameters(
        queryParam[String]("platform_id").description("ID of associated platform"),
        queryParam[String]("start").      description("Start date for the token"),
        queryParam[String]("end").        description("End date for the token"),
        queryParam[String]("state").      description("State or activity")))

  post("/", operation(apiAdd)) {
    logger.debug("POST token body = " + request.body)

//    val token = parsedBody.extract[Token]
//    logger.debug("POST token = " + token)
//
//    val newObj = MongoDBObject("platform_id" -> token.platform_id,
//                               "start"       -> token.start,
//                               "end"         -> token.end,
//                               "state"       -> token.state)

    val platform_id  = params.get("platform_id").get
    val start        = params.get("start").get
    val end          = params.get("end").get
    val state        = params.get("state").get

    val newObj = MongoDBObject("platform_id" -> platform_id,
                               "start"       -> start,
                               "end"         -> end,
                               "state"       -> state)
    logger.debug("POST token = " + newObj)

    tokenColl += newObj

    val id = for (x <- newObj.getAs[ObjectId]("_id")) yield x.toString

    logger.info("Token posted: " + newObj + "   id = " + id)

    //token.copy(id=id)
    Token(id, platform_id, start, end, state)
  }


  val apiUpdate =
    (apiOperation[Token]("updateToken")
      summary "Updates a token"
      notes dateTimeNotes +
         "<br /> TODO: all parameters are required at the moment but they should be optional (except for the id)."
      parameters(
        pathParam[String]("id").            description("ID of the token to be updated"),
        queryParam[String]("platform_id").  description("ID of associated platform"),
        queryParam[String]("start").        description("Start date for the token"),
        queryParam[String]("end").          description("End date for the token"),
        queryParam[String]("state").        description("State or activity")))

  put("/:id", operation(apiUpdate)) {
    logger.info("PUT params=" + params)
    logger.info("PUT multiParams=" + multiParams)
    val id = params("id")
    val obj = MongoDBObject("_id" -> new ObjectId(id))
{'fraction_non_alphanumeric': 0.13765744322126353, 'fraction_numerical': 0.00039670732916790636, 'mean_word_length': 2.452242382745635, 'pattern_counts': {'":': 0, '<': 27, '<?xml version=': 0, '>': 33, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, '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': '5326795', 'n_tokens_mistral': 2984, 'n_tokens_neox': 2903, 'n_words': 737}