org.joda.time.DateTime Scala Examples

The following examples show how to use org.joda.time.DateTime. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: DateTimeTools.scala    From pertax-frontend   with Apache License 2.0 9 votes vote down vote up
package util

import com.google.inject.{Inject, Singleton}
import org.joda.time.format.{DateTimeFormat, DateTimeFormatter}
import org.joda.time.{DateTime, _}
import play.api.Logger
import uk.gov.hmrc.time.CurrentTaxYear

import scala.util.{Failure, Success, Try}

import java.time.{LocalDateTime => JavaLDT}

object DateTimeTools extends CurrentTaxYear {

  //Timezone causing problem on dev server
  val defaultTZ = DateTimeZone.forID("Europe/London")
  val unixDateFormat = "yyyy-MM-dd"
  val unixDateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss"
  val humanDateFormat = "dd MMMMM yyyy"

  //Returns for example 1516 in March 2016
  def previousAndCurrentTaxYear = previousAndCurrentTaxYearFromGivenYear(current.currentYear)

  def previousAndCurrentTaxYearFromGivenYear(year: Int) = {
    def y = year

    (y - 1).toString.takeRight(2) + (y).toString.takeRight(2)
  }

  private def formatter(pattern: String): DateTimeFormatter = DateTimeFormat.forPattern(pattern).withZone(defaultTZ)

  def short(dateTime: LocalDate) = formatter("dd/MM/yyy").print(dateTime)

  def asHumanDateFromUnixDate(unixDate: String): String =
    Try(DateTimeFormat.forPattern(humanDateFormat).print(DateTime.parse(unixDate))) match {
      case Success(v) => v
      case Failure(e) => {
        Logger.warn("Invalid date parse in DateTimeTools.asHumanDateFromUnixDate: " + e)
        unixDate
      }
    }

  def toPaymentDate(dateTime: JavaLDT): LocalDate =
    new LocalDate(dateTime.getYear, dateTime.getMonthValue, dateTime.getDayOfMonth)

  override def now: () => DateTime = DateTime.now
}

@Singleton
class DateTimeTools @Inject()() {

  def showSendTaxReturnByPost = {

    val start = new DateTime(s"${DateTime.now().getYear}-11-01T00:00:00Z")
    val end = new DateTime(s"${DateTime.now().getYear + 1}-01-31T23:59:59Z")
    !DateTime.now().isAfter(start) && DateTime.now().isBefore(end)
  }
} 
Example 2
Source File: DateTimeNoMillisSerializer.scala    From avoin-voitto   with MIT License 6 votes vote down vote up
package liigavoitto.util

import org.joda.time.{ DateTime, DateTimeZone }
import org.joda.time.format.ISODateTimeFormat
import org.json4s.CustomSerializer
import org.json4s.JsonAST.{ JNull, JString }

case object DateTimeNoMillisSerializer extends CustomSerializer[DateTime](format => (
  {
    case JString(s) => ISODateTimeFormat.dateTimeNoMillis().withZone(Time.zone).parseDateTime(s)
    case JNull => null
  },
  {
    case d: DateTime => JString(ISODateTimeFormat.dateTimeNoMillis().withZone(Time.zone).print(d))
  }
))

object Time {
  val zone = DateTimeZone.forID("Europe/Helsinki")
} 
Example 3
Source File: WorkflowAccess.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime


case class WorkflowAccess(workflowId: Int,
                          roleId: Int,
                          tenantId: Int,
                          organizationId : Int ,
                          isActive: Boolean = true,
                          created: DateTime = DateTime.now,
                          createdBy: Int,
                          updated: DateTime = DateTime.now,
                          updatedBy: Int,
                          isReadWrite: Boolean = true,
                          uuid: String
                          ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = workflowId

  override val entityName: String = "AD_Workflow_Access"
  override val identifier: String = null

}

object WorkflowAccess {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[WorkflowAccess]
  def create(workflowId: Int,
             roleId: Int,
             tenantId: Int,
             organizationId : Int ,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             isReadWrite: Boolean,
             uuid: String) = WorkflowAccess(workflowId, roleId, tenantId, organizationId, isActive, created, createdBy,
    updated, updatedBy, isReadWrite, uuid)
} 
Example 4
Source File: TreeFavorite.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class TreeFavorite(treeFavoriteId: Int,
                        tenantId: Int,
                        organizationId: Int,
                        roleId: Int,
                        userId: Int,
                        created: DateTime = DateTime.now,
                        createdBy: Int,
                        isActive: Boolean = true,
                        updated: DateTime = DateTime.now,
                        updatedBy: Int,
                        uuid: String
                       ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = treeFavoriteId

  override val entityName: String = "AD_Tree_Favorite"
  override val identifier: String = "AD_Tree_Favorite_ID"
}


object TreeFavorite  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[TreeFavorite]
  def create(treeFavoriteId: Int,
             tenantId: Int,
             organizationId: Int,
             roleId: Int,
             userId: Int,
             created: DateTime,
             createdBy: Int,
             isActive: Boolean,
             updated: DateTime,
             updatedBy: Int,
             uuid: String) = TreeFavorite(treeFavoriteId, tenantId, organizationId, roleId, userId, created,
    createdBy, isActive, updated, updatedBy, uuid)
} 
Example 5
Source File: TreeNodeU1.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class TreeNodeU1(treeId: Int,
                      nodeId: Int,
                      tenantId: Int,
                      organizationId: Int,
                      isActive: Boolean = true,
                      created: DateTime = DateTime.now,
                      createdBy: Int,
                      updatedBy: Int,
                      updated: DateTime = DateTime.now,
                      parentId: Option[Int],
                      seqNo: Option[Int],
                      uuid: String
                     ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = treeId

  override val entityName: String = "AD_TreeNodeU1"
  override val identifier: String = null
}

object TreeNodeU1  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[TreeNodeU1]
  def create(treeId: Int,
             nodeId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updatedBy: Int,
             updated: DateTime,
             parentId: Int,
             seqNo: Int,
             uuid: String) = TreeNodeU1(treeId, nodeId, tenantId, organizationId, isActive, created, createdBy,
    updatedBy, updated, None, None, uuid)
} 
Example 6
Source File: WorkflowNodeNext.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class WorkflowNodeNext(workflowNodeNextId: Int,
                            tenantId: Int,
                            organizationId : Int ,
                            isActive: Boolean = true,
                            created: DateTime = DateTime.now,
                            createdBy: Int,
                            updated: DateTime = DateTime.now,
                            updatedBy: Int,
                            workflowNodeId: Int,
                            workflowNextId: Int,
                            description: Option[String],
                            seqNo: Int,
                            entityType: String = "D",
                            transitionCode: Option[String],
                            isStdUserWorkflow: Boolean = false,
                            uuid: String
                     ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = workflowNodeNextId

  override val entityName: String = "AD_Wf_NodeNext"
  override val identifier: String = "AD_Wf_NodeNext_ID"
}

object WorkflowNodeNext {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[WorkflowNodeNext]
  def create(workflowNodeNextId: Int,
             tenantId: Int,
             organizationId : Int ,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             workflowNodeId: Int,
             workflowNextId: Int,
             description: String,
             seqNo: Int,
             entityType: String,
             transitionCode: String,
             isStdUserWorkflow: Boolean,
             uuid: String) = WorkflowNodeNext(workflowNodeNextId, tenantId, organizationId, isActive, created,
    createdBy, updated, updatedBy, workflowNodeId, workflowNextId, None, seqNo, entityType,
    None, isStdUserWorkflow, uuid)

} 
Example 7
Source File: WorkflowTrl.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime


case class WorkflowTrl(workflowId: Int,
                       language: String,
                       tenantId: Int,
                       organizationId: Int,
                       isActive: Boolean = true,
                       created: DateTime = DateTime.now,
                       createdBy: Int,
                       updated: DateTime = DateTime.now,
                       updatedBy: Int,
                       name: String,
                       description: Option[String],
                       help: Option[String],
                       isTranslated: Boolean = false,
                       uuid: String
                       ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = workflowId

  override val entityName: String = "AD_Workflow_Trl"
  override val identifier: String = null
}

object WorkflowTrl {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[WorkflowTrl]
  def create(workflowId: Int,
             language: String,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             name: String,
             description: String,
             help: String,
             isTranslated: Boolean,
             uuid: String) = WorkflowTrl(workflowId, language, tenantId, organizationId, isActive, created, createdBy,
    updated, updatedBy, name, None, None, isTranslated, uuid)
} 
Example 8
Source File: AccessLog.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class AccessLog(accessLogId: Int,
                     tenantId: Int,
                     organizationId: Int,
                     isActive: Boolean = true,
                     created: DateTime =  DateTime.now,
                     createdBy: Int,
                     updated: DateTime =  DateTime.now,
                     updatedBy: Int,
                     entityId: Option[Int],
                     attributeId: Option[Int],
                     recordId: Option[Int],
                     remoteAddress: Option[String],
                     remoteHost: Option[String],
                     description:Option [String],
                     textMsg: Option[String],
                     reply: Option[String],
                     uuid: String
                    ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = accessLogId

  override val entityName: String = "AD_AccessLog"
  override val identifier: String = "AD_AccessLog_ID"
}

object AccessLog  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[AccessLog]
  def create(accessLogId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             entityId: Int,
             attributeId: Int,
             recordId: Int,
             remoteAddress: String,
             remoteHost: String,
             description: String,
             textMsg: String,
             reply: String,
             uuid: String) = AccessLog(accessLogId, tenantId , organizationId, isActive, created, createdBy, updated,
    updatedBy, None, None, None, None, None, None, None, None, uuid)
} 
Example 9
Source File: ReplicationRun.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime


case class ReplicationRun(replicationRunId: Int,
                          tenantId: Int,
                          organizationId: Int,
                          isActive : Boolean = true,
                          created : DateTime = DateTime.now,
                          createdBy : Int ,
                          updated : DateTime = DateTime.now,
                          updatedBy : Int,
                          name : String,
                          replicationId: Int,
                          isReplicated: Boolean = false,
                          description: Option[String],
                          uuid: String
                         ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = replicationRunId

  override val entityName: String = "AD_Replication_Run"
  override val identifier: String = "AD_Replication_Run_ID"
}

object ReplicationRun  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[ReplicationRun]
  def create(replicationRunId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive : Boolean,
             created : DateTime,
             createdBy : Int ,
             updated : DateTime,
             updatedBy : Int,
             name : String,
             replicationId: Int,
             isReplicated: Boolean,
             description: String,
             uuid: String) = ReplicationRun(replicationRunId, tenantId, organizationId, isActive, created,
    createdBy, updated, updatedBy, name, replicationId, isReplicated, None, uuid)
} 
Example 10
Source File: TaskTrl.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime


case class TaskTrl (taskId: Int,
                    language: String,
                    tenantId: Int,
                    organizationId: Int,
                    isActive: Boolean = true,
                    created: DateTime = DateTime.now,
                    createdBy: Int,
                    updated: DateTime = DateTime.now,
                    updatedBy: Int,
                    name: String,
                    description: Option[String],
                    help: Option[String],
                    isTranslated: Boolean = false,
                    uuid: String
                   ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = taskId

  override val entityName: String = "AD_Task_Trl"
  override val identifier: String = null

}

object TaskTrl {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[TaskTrl]

  def create(taskId: Int,
             language: String,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             name: String,
             description: String,
             help: String,
             isTranslated: Boolean,
             uuid: String) = TaskTrl(taskId, language, tenantId, organizationId, isActive, created, createdBy,
    updated, updatedBy, name, None, None, isTranslated, uuid)
} 
Example 11
Source File: TreeBar.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class TreeBar(treeId: Int,
                   tenantId: Int,
                   organizationId: Int,
                   userId: Int,
                   nodeId: Int,
                   isActive: Boolean = true,
                   created: DateTime = DateTime.now,
                   createdBy: Int,
                   updated: DateTime = DateTime.now,
                   updatedBy: Int,
                   uuid: String
                  ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = treeId

  override val entityName: String = "AD_TreeBar"
  override val identifier: String = null
}

object TreeBar  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[TreeBar]
  def create(treeId: Int,
             tenantId: Int,
             organizationId: Int,
             userId: Int,
             nodeId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             uuid: String) = TreeBar(treeId, userId, tenantId, organizationId, nodeId, isActive, created,
    createdBy, updated, updatedBy, uuid)
} 
Example 12
Source File: ImportFormat.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime


case class ImportFormat(importFormatId: Int,
                        tenantId: Int,
                        organizationId: Int,
                        isActive: Boolean = true,
                        created: DateTime = DateTime.now,
                        createdBy: Int,
                        updated: DateTime = DateTime.now,
                        updatedBy: Int,
                        name: String,
                        description: Option[String],
                        entityId: Int,
                        formatType: Boolean,
                        processing: Boolean,
                        separatorCharacter: Option[String],
                        uuid: String
                    ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type
  override def Id: Int = importFormatId

  override val entityName: String = "AD_ImpFormat"
  override val identifier: String = "AD_ImpFormat_ID"

}

object ImportFormat {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[ImportFormat]
  def create(importFormatId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             name: String,
             description: String,
             entityId: Int,
             formatType: Boolean,
             processing: Boolean,
             separatorCharacter: String,
             uuid: String) = ImportFormat(importFormatId, tenantId, organizationId, isActive, created, createdBy,
    updated, updatedBy, name, None, entityId, formatType, processing, None, uuid)
} 
Example 13
Source File: UserRoles.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class UserRoles(userId : Int ,
                     roleId: Int,
                     tenantId: Int,
                     organizationId : Int,
                     isActive : Boolean = true,
                     created : DateTime = DateTime.now,
                     createdBy : Int ,
                     updated : DateTime = DateTime.now,
                     updatedBy : Int ,
                     uuid: String
                    ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = userId

  override val entityName: String = "AD_User_Roles"
  override val identifier: String = null
}

object UserRoles  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[UserRoles]
  def create(userId : Int ,
             roleId: Int,
             tenantId: Int,
             organizationId : Int,
             isActive : Boolean,
             created : DateTime,
             createdBy : Int ,
             updated : DateTime ,
             updatedBy : Int,
             uuid: String) = UserRoles(userId, roleId, tenantId, organizationId, isActive, created, createdBy,
    updated, updatedBy, uuid)
} 
Example 14
Source File: DynamicValidationRule.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime


case class DynamicValidationRule(dynamicValidationRuleId: Int,
                                 tenantId: Int,
                                 organizationId: Int,
                                 isActive: Boolean = true,
                                 created: DateTime = DateTime.now,
                                 createdBy: Int,
                                 updated: DateTime = DateTime.now,
                                 updatedBy: Int,
                                 name: String,
                                 description: Option[String],
                                 typePackage: Option[Boolean],
                                 code: Option[String],
                                 entityType: String = "D",
                                 uuid: String
                  ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = dynamicValidationRuleId

  override val entityName: String = "AD_Val_Rule"
  override val identifier: String = "AD_Val_Rule_ID"
}

object DynamicValidationRule  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[DynamicValidationRule]
  def create(dynamicValidationRuleId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             name: String,
             description: String,
             typePackage: Boolean,
             code: String,
             entityType: String,
             uuid: String) = DynamicValidationRule(dynamicValidationRuleId, tenantId, organizationId, isActive, created,
    createdBy, updated, updatedBy, name, None, None, None, entityType, uuid)
} 
Example 15
Source File: Attachment.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class Attachment(attachmentId: Int,
                      tenantId: Int,
                      organizationId: Int,
                      isActive: Boolean = true,
                      created: DateTime = DateTime.now,
                      createdBy: Int,
                      updated: DateTime = DateTime.now,
                      updatedBy: Int,
                      entityId: Int,
                      recordId: Int,
                      title: String,
                      binaryData: String,
                      textMsg: Option[String],
                      uuid: String
                     ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = attachmentId

  override val entityName: String = "AD_Attachment"
  override val identifier: String = "AD_Attachment_ID"
}

object Attachment {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[Attachment]
  def create(attachmentId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             entityId: Int,
             recordId: Int,
             title: String,
             binaryData: String,
             textMsg: String,
             uuid: String) = Attachment(attachmentId, tenantId, organizationId,  isActive,created, createdBy, updated,
    updatedBy,entityId, recordId, title, binaryData, None, uuid)

} 
Example 16
Source File: PinStanceLog.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class PinStanceLog(pinStanceLogId: Int,
                        pinStanceId: Int,
                        date: DateTime = DateTime.now,
                        id: Option[Int],
                        number: Option[Int],
                        msg: Option[String],
                        createdBy: Int,
                        created: DateTime = DateTime.now,
                        updatedBy: Int,
                        updated: DateTime = DateTime.now,
                        isActive: Boolean = true,
                        uuid: String
                       ) extends DomainModel


  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = pinStanceLogId

  override val entityName: String = "AD_PinStance_Log"
  override val identifier: String = "AD_PinStance_Log_ID"
}

object PinStanceLog  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[PinStanceLog]
  def create(pinStanceLogId: Int,
             pinStanceId: Int,
             date: DateTime,
             id: Int,
             number: Int,
             msg: String,
             createdBy: Int,
             created: DateTime,
             updatedBy: Int,
             updated: DateTime,
             isActive: Boolean,
             uuid: String) = PinStanceLog(pinStanceLogId, pinStanceId, date, None, None, None, createdBy,
    created, updatedBy, updated, isActive, uuid)
} 
Example 17
Source File: AttributeTrl.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class AttributeTrl(attributeId: Int,
                        language: String,
                        tenantId: Int,
                        organizationId: Int,
                        isActive: Boolean = true,
                        created: DateTime =  DateTime.now,
                        createdBy: Int,
                        updated: DateTime =  DateTime.now,
                        updatedBy: Int,
                        name: String,
                        isTranslated: Boolean = false,
                        uuid: String
                    ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = attributeId

  override val entityName: String = "AD_Column_Trl"
  override val identifier: String = null
}

object AttributeTrl  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[AttributeTrl]
  def create(attributeId: Int,
             language: String,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             name: String,
             isTranslated: Boolean,
             uuid: String) = AttributeTrl(attributeId, language, tenantId, organizationId, isActive, created,
    createdBy, updated, updatedBy, name, isTranslated, uuid)
} 
Example 18
Source File: PrintLabelLineTrl.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime


case class PrintLabelLineTrl (printLabelLineId: Int,
                              language: String,
                              tenantId: Int,
                              organizationId: Int,
                              isActive: Boolean = true,
                              created: DateTime = DateTime.now,
                              createdBy: Int,
                              updated: DateTime = DateTime.now,
                              updatedBy: Int,
                              printName: Option[String],
                              isTranslated: Boolean = false,
                              uuid: String
                             ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = printLabelLineId

  override val entityName: String = "AD_PrintLabelLine_Trl"
  override val identifier: String = null

}

object PrintLabelLineTrl {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[PrintLabelLineTrl]
  def create(printLabelLineId: Int,
             language: String,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             printName: String,
             isTranslated: Boolean,
             uuid: String) = PrintLabelLineTrl(printLabelLineId, language, tenantId, organizationId, isActive,
    created, createdBy, updated, updatedBy, None, isTranslated, uuid)
} 
Example 19
Source File: OrganizationInfo.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class OrganizationInfo(organizationId: Int,
                            tenantId : Int ,
                            isActive : Boolean = true,
                            created : DateTime =  DateTime.now,
                            createdBy : Int ,
                            updated : DateTime =  DateTime.now,
                            updatedBy : Int ,
                            locationId: Option[Int],
                            duns: String,
                            taxId: String,
                            goalId: Option[Int],
                            supervisorId: Option[Int],
                            parentOrgId: Option[Int],
                            orgTypeId: Option[Int],
                            warehouseId: Option[Int],
                            transferBankId: Option[Int],
                            transferCashBookId: Option[Int],
                            receiptFooterMsg: Option[String],
                            dropShipWarehouseId: Option[Int],
                            calendarId: Option[Int],
                            logoId: Option[Int],
                            phone: Option[String],
                            phone2: Option[String],
                            fax: Option[String],
                            email: Option[String],
                            uuid: String
                           ) extends DomainModel
  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = organizationId

  override val entityName: String = "AD_OrgInfo"
  override val identifier: String = "AD_Org_ID"
}

object OrganizationInfo{
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[OrganizationInfo]
  def create(organizationId: Int,
             tenantId : Int ,
             isActive : Boolean ,
             created : DateTime ,
             createdBy : Int ,
             updated : DateTime ,
             updatedBy : Int ,
             locationId: Int,
             duns: String,
             taxId: String,
             goalId: Int,
             supervisorId: Int,
             parentOrgId: Int,
             orgTypeId: Int,
             warehouseId: Int,
             transferBankId:Int,
             transferCashBookId: Int,
             receiptFooterMsg: String,
             dropShipWarehouseId: Int,
             calendarId: Int,
             logoId: Int,
             phone: String,
             phone2: String,
             fax: String,
             email: String,
             uuid: String) = OrganizationInfo(organizationId, tenantId, isActive, created, createdBy,
    updated, updatedBy, None, duns, taxId, None, None, None, None, None, None, None, None, None, None,
    None, None, None, None, None, uuid)
} 
Example 20
Source File: WorkflowProcessData.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class WorkflowProcessData(workflowProcessDataId: Int,
                               tenantId: Int,
                               organizationId : Int ,
                               isActive: Boolean = true,
                               created: DateTime = DateTime.now,
                               createdBy: Int,
                               updated: DateTime = DateTime.now,
                               updatedBy: Int,
                               workflowProcessId: Int,
                               attributeName: String,
                               attributeValue: Option[String],
                               uuid: String
                        ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = workflowProcessDataId

  override val entityName: String = "AD_Wf_ProcessData"
  override val identifier: String = "AD_Wf_ProcessData_ID"
}

object WorkflowProcessData {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[WorkflowProcessData]
  def create(workflowProcessDataId: Int,
             tenantId: Int,
             organizationId : Int ,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             workflowProcessId: Int,
             attributeName: String,
             attributeValue: String,
             uuid: String) = WorkflowProcessData(workflowProcessDataId, tenantId, organizationId, isActive, created,
    createdBy, updated, updatedBy, workflowProcessId, attributeName, None, uuid)

} 
Example 21
Source File: Color.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class Color(colorId: Int,
                 tenantId: Int,
                 organizationId: Int,
                 isActive: Boolean = true,
                 created: DateTime =  DateTime.now,
                 createdBy: Int,
                 updated: DateTime =  DateTime.now,
                 updatedBy: Int,
                 name: String,
                 isDefault: Boolean=false,
                 colorType: Boolean,
                 red: Int,
                 green: Int,
                 blue: Int,
                 alpha: Int,
                 imageId: Option[Int],
                 imageAlpha:Int,
                 red1: Option[Int],
                 green1: Option[Int],
                 blue1: Option[Int],
                 alpha1: Option[Int],
                 lineWidth: Option[Int],
                 lineDistance: Option[Int],
                 startPoint: Option[Int],
                 repeatDistance: Option[Int],
                 uuid: String
                ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable{
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int =colorId

  override val entityName: String = "AD_Color"
  override val identifier: String = "AD_Color_ID"

}

object Color {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[Color]
  def create(colorId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             name: String,
             isDefault: Boolean,
             colorType: Boolean,
             red: Int,
             green: Int,
             blue: Int,
             alpha: Int,
             imageId: Int,
             imageAlpha:Int,
             red1: Int,
             green1: Int,
             blue1: Int,
             alpha1: Int,
             lineWidth: Int,
             lineDistance: Int,
             startPoint: Int,
             repeatDistance: Int,
             uuid: String) = Color(colorId, tenantId, organizationId, isActive, created, createdBy, updated,
    updatedBy, name, isDefault, colorType, red, green, blue, alpha, None, imageAlpha, None,
    None, None, None, None, None, None, None, uuid)
} 
Example 22
Source File: Form.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class Form (formId: Int,
                 tenantId: Int,
                 organizationId: Int,
                 isActive : Boolean = true,
                 created : DateTime = DateTime.now,
                 createdBy : Int ,
                 updated : DateTime = DateTime.now,
                 updatedBy : Int,
                 name : String,
                 description: Option[String],
                 help: Option[String],
                 accessLevel : String,
                 className : Option[String] ,
                 entityType: String = EntityType.Dictionary,
                 isBetaFunctionality : Boolean = false ,
                 jspURL : Option[String],
                 uuid: String
                 ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type
  override def Id: Int = formId

  override val entityName: String = "AD_Form"
  override val identifier: String = "AD_Form_ID"
}

object Form  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[Form]
  def create(formId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive : Boolean ,
             created : DateTime ,
             createdBy : Int ,
             updated :DateTime ,
             updatedBy : Int ,
             name : String,
             description: String,
             help: String,
             accessLevel : String,
             className : String ,
             entityType: String,
             isBetaFunctionality : Boolean ,
             jspURL : String,
             uuid: String) = Form(formId, tenantId, organizationId, isActive, created, createdBy, updated, updatedBy,
    name, None, None, accessLevel, None, entityType, isBetaFunctionality, None, uuid)
} 
Example 23
Source File: TaskAccess.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime


case class TaskAccess (taskId: Int,
                       roleId: Int,
                       tenantId: Int,
                       organizationId: Int,
                       isActive: Boolean = true,
                       created: DateTime = DateTime.now,
                       createdBy: Int,
                       updated: DateTime = DateTime.now,
                       updatedBy: Int,
                       isReadWrite: Boolean = true,
                       uuid: String
                      ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = taskId

  override val entityName: String = "AD_Task_Access"
  override val identifier: String = null

}

object TaskAccess {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[TaskAccess]
  def create(taskId: Int,
             roleId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             isReadWrite: Boolean,
             uuid: String) = TaskAccess(taskId, roleId, tenantId, organizationId, isActive, created,
    createdBy, updated, updatedBy, isReadWrite, uuid)
} 
Example 24
Source File: Language.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model


import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class Language(languageId: Int,
                    tenantId : Int ,
                    organizationId : Int,
                    isActive: Boolean = true,
                    created: DateTime =  DateTime.now,
                    createdBy: Int,
                    updated: DateTime =  DateTime.now,
                    updatedBy: Int,
                    name: String,
                    languageISO: Option[String],
                    countryCode: Option[String],
                    isBaseLanguage: Boolean = false,
                    isSystemLanguage: Boolean = false,
                    processing: Option[Boolean],
                    language: String,
                    isDecimalPoint: Boolean = true,
                    datePattern: Option[String],
                    timePattern: Option[String],
                    uuid: String
                   ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
    override type ActiveEnabled = this.type
    override type Identifiable = this.type
    override type Traceable = this.type

    override def Id: Int = languageId

    override val entityName: String = "AD_Language"
    override val identifier: String = "AD_Language_ID"
}

object Language {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[Language]
  def create(languageId: Int,
             tenantId : Int ,
             organizationId : Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             name: String,
             languageISO: String,
             countryCode: String,
             isBaseLanguage: Boolean,
             isSystemLanguage: Boolean,
             processing: Boolean,
             language: String,
             isDecimalPoint: Boolean,
             datePattern: String,
             timePattern: String,
             uuid: String) = Language(languageId, tenantId, organizationId, isActive, created, createdBy, updated,
    updatedBy, name, None, None, isBaseLanguage, isSystemLanguage, None, language, isDecimalPoint, None, None, uuid)
} 
Example 25
Source File: AttachmentNote.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class AttachmentNote(attachmentNoteId: Int,
                          tenantId: Int,
                          organizationId: Int,
                          isActive: Boolean = true,
                          created: DateTime = DateTime.now,
                          createdBy: Int,
                          updated: DateTime = DateTime.now,
                          updatedBy: Int,
                          attachmentId: Int,
                          userId: Int,
                          title: String,
                          textMsg: String,
                          uuid: String
                         ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = attachmentNoteId

  override val entityName: String = "AD_AttachmentNote"
  override val identifier: String = "AD_AttachmentNote_ID"
}

object AttachmentNote {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[AttachmentNote]
  def create(attachmentNoteId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             attachmentId: Int,
             userId: Int,
             title: String,
             textMsg: String,
             uuid: String) = AttachmentNote(attachmentNoteId, tenantId, organizationId, isActive,created,
    createdBy, updated, updatedBy,attachmentId, userId, title, textMsg, uuid)

} 
Example 26
Source File: FieldTrl.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime


case class FieldTrl (fieldId: Int,
                     language: String,
                     tenantId: Int,
                     organizationId: Int,
                     isActive: Boolean = true,
                     created: DateTime = DateTime.now,
                     createdBy: Int,
                     updated: DateTime = DateTime.now,
                     updatedBy: Int,
                     name: String,
                     description: Option[String],
                     help: Option[String],
                     isTranslated: Boolean = false,
                     uuid: String
                    ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type
  override def Id: Int = fieldId

  override val entityName: String = "AD_Field_Trl"
  override val identifier: String = null

}

object FieldTrl {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[FieldTrl]

  def create(fieldId: Int,
             language: String,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             name: String,
             description: String,
             help: String,
             isTranslated: Boolean,
             uuid: String) = FieldTrl(fieldId, language, tenantId, organizationId, isActive, created, createdBy,
    updated, updatedBy, name, None, None, isTranslated, uuid)
} 
Example 27
Source File: WorkflowNodePara.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class WorkflowNodePara(workflowNodeParaId: Int,
                            tenantId: Int,
                            organizationId : Int ,
                            isActive: Boolean = true,
                            created: DateTime = DateTime.now,
                            createdBy: Int,
                            updated: DateTime = DateTime.now,
                            updatedBy: Int,
                            workflowNodeId: Int,
                            attributeName: Option[String],
                            processParaId: Option[Int],
                            description: Option[String],
                            attributeValue: Option[String],
                            entityType: String ="D",
                            uuid: String
                     ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = workflowNodeParaId

  override val entityName: String = "AD_Wf_Node_Para"
  override val identifier: String = "AD_Wf_Node_Para_ID"
}


object WorkflowNodePara {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[WorkflowNodePara]
  def create(workflowNodeParaId: Int,
             tenantId: Int,
             organizationId : Int ,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             workflowNodeId: Int,
             attributeName: String,
             processParaId: Int,
             description: String,
             attributeValue: String,
             entityType: String,
             uuid: String) = WorkflowNodePara(workflowNodeParaId, tenantId, organizationId, isActive, created,
    createdBy, updated, updatedBy, workflowNodeId, None, None, None, None, entityType, uuid)

} 
Example 28
Source File: ImportFormatRow.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime


case class ImportFormatRow(importFormatRowId: Int,
                           tenantId: Int,
                           organizationId: Int,
                           isActive: Boolean = true,
                           created: DateTime = DateTime.now,
                           createdBy: Int,
                           updated: DateTime = DateTime.now,
                           updatedBy: Int,
                           importFormatId: Int,
                           seqNo: Int,
                           name: String,
                           attributeId: String,
                           startNo: Option[Int],
                           endNo: Option[Int],
                           dataType: Boolean,
                           dataFormat: Option[String],
                           decimalPoint: Boolean,
                           divideBy100: Boolean = false,
                           constantValue: Option[String],
                           callout: Option[String],
                           script: Option[String],
                           defaultValue: Option[String],
                           uuid: String
                        ) extends DomainModel


  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type
  override def Id: Int = importFormatRowId

  override val entityName: String = "AD_ImpFormat_Row"
  override val identifier: String = "AD_ImpFormat_Row_ID"

}

object ImportFormatRow {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[ImportFormatRow]

  def create(importFormatRowId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             importFormatId: Int,
             seqNo: Int,
             name: String,
             attributeId: String,
             startNo: Int,
             endNo: Int,
             dataType: Boolean,
             dataFormat: String,
             decimalPoint: Boolean,
             divideBy100: Boolean,
             constantValue: String,
             callout: String,
             script: String,
             defaultValue: String,
             uuid: String) = ImportFormatRow(importFormatRowId, tenantId, organizationId, isActive, created, createdBy,
    updated, updatedBy, importFormatId, seqNo, name, attributeId, None, None, dataType, None, decimalPoint, divideBy100,
    None, None, None, None, uuid)
} 
Example 29
Source File: DesktopTrl.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class DesktopTrl(desktopId: Int,
                      language: String,
                      tenantId: Int,
                      organizationId: Int,
                      isActive:Boolean=true,
                      created:DateTime = DateTime.now,
                      createdBy: Int,
                      updated: DateTime = DateTime.now,
                      updatedBy: Int,
                      name: String,
                      description: Option[String],
                      help: Option[String],
                      isTranslated: Boolean = false,
                      uuid: String
                     )  extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = desktopId

  override val entityName: String = "AD_Desktop_Trl"
  override val identifier: String = null
}

object DesktopTrl {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[DesktopTrl]
  def create(desktopId: Int,
             language: String,
             tenantId: Int,
             organizationId: Int,
             isActive:Boolean,
             created:DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             name: String,
             description:String,
             help: String,
             isTranslated: Boolean,
             uuid:String) = DesktopTrl(desktopId, language, tenantId, organizationId, isActive,created, createdBy,
    updated, updatedBy, name, None, None, isTranslated, uuid)
} 
Example 30
Source File: WorkflowEventAudit.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class WorkflowEventAudit(workflowEventAuditId: Int,
                              tenantId: Int,
                              organizationId : Int ,
                              isActive: Boolean = true,
                              created: DateTime = DateTime.now,
                              createdBy: Int,
                              updated: DateTime = DateTime.now,
                              updatedBy: Int,
                              eventType: String,
                              workflowState: String,
                              workflowProcessId: Int,
                              nodeId: Int,
                              entityId: Int,
                              recordId: Int,
                              workflowResponsibleId: Int,
                              userId: Option[Int],
                              elapsedTimeMs: Int,
                              attributeName: Option[String],
                              oldValue: Option[String],
                              newValue: Option[String],
                              description: Option[String],
                              textMsg: Option[String],
                              uuid: String
                       ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = workflowEventAuditId

  override val entityName: String = "AD_Wf_EventAudit"
  override val identifier: String = "AD_Wf_EventAudit_ID"
}

object WorkflowEventAudit  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[WorkflowEventAudit]
  def create(workflowEventAuditId: Int,
             tenantId: Int,
             organizationId : Int ,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             eventType: String,
             workflowState: String,
             workflowProcessId: Int,
             nodeId: Int,
             entityId: Int,
             recordId: Int,
             workflowResponsibleId: Int,
             userId: Int,
             elapsedTimeMs: Int,
             attributeName: String,
             oldValue: String,
             newValue: String,
             description: String,
             textMsg: String,
             uuid: String) = WorkflowEventAudit(workflowEventAuditId, tenantId, organizationId, isActive, created,
    createdBy, updated, updatedBy, eventType, workflowState, workflowProcessId, nodeId, entityId, recordId,
    workflowResponsibleId, None, elapsedTimeMs, None, None, None, None, None, uuid)
} 
Example 31
Source File: WorkflowNodeTrl.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class WorkflowNodeTrl(workflowNodeId: Int,
                           language: String,
                           tenantId: Int,
                           organizationId : Int ,
                           isActive: Boolean = true,
                           created: DateTime = DateTime.now,
                           createdBy: Int,
                           updated: DateTime = DateTime.now,
                           updatedBy: Int,
                           name: String,
                           description: Option[String],
                           help: Option[String],
                           isTranslated: Boolean =false,
                           uuid: String
                    ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = workflowNodeId

  override val entityName: String = "AD_Wf_Node_Trl"
  override val identifier: String = null
}


object WorkflowNodeTrl {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[WorkflowNodeTrl]
  def create(workflowNodeId: Int,
             language: String,
             tenantId: Int,
             organizationId : Int ,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             name: String,
             description: String,
             help: String,
             isTranslated: Boolean,
             uuid: String) = WorkflowNodeTrl(workflowNodeId, language, tenantId, organizationId, isActive, created, createdBy,
    updated, updatedBy, name, None, None, isTranslated, uuid)

} 
Example 32
Source File: Task.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime


case class Task (taskId: Int,
                 tenantId: Int,
                 organizationId: Int,
                 isActive: Boolean = true,
                 created: DateTime = DateTime.now,
                 createdBy: Int,
                 updated: DateTime = DateTime.now,
                 updatedBy: Int,
                 name: String,
                 description: Option[String],
                 help: Option[String],
                 accessLevel: Boolean,
                 osCommand: String,
                 entityType: String = "D",
                 isServerProcess: Boolean = false,
                 uuid: String
                ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type
  override def Id: Int = taskId

  override val entityName: String = "AD_Package_Imp_Detail"
  override val identifier: String = "AD_Package_Imp_Detail_ID"

}

object Task {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[Task]
  def create(taskId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             name: String,
             description: String,
             help: String,
             accessLevel: Boolean,
             osCommand: String,
             entityType: String,
             isServerProcess: Boolean,
             uuid: String) = Task(taskId, tenantId, organizationId, isActive, created, createdBy, updated,
    updatedBy, name, None, None, accessLevel, osCommand, entityType, isServerProcess, uuid)
} 
Example 33
Source File: ProcessParameterTrl.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class ProcessParameterTrl(processParameterId: Int,
                               language: String,
                               tenantId: Int,
                               organizationId: Int,
                               isActive : Boolean = true,
                               created : DateTime = DateTime.now,
                               createdBy : Int ,
                               updated : DateTime = DateTime.now,
                               updatedBy : Int,
                               name : String,
                               description: Option[String],
                               help: Option[String],
                               isTranslated: Boolean = false,
                               uuid: String
                              ) extends DomainModel
  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = processParameterId

  override val entityName: String = "AD_Process_Para_Trl"
  override val identifier: String = null
}

object ProcessParameterTrl  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[ProcessParameterTrl]
  def create(processParameterId: Int,
             language: String,
             tenantId: Int,
             organizationId: Int,
             isActive : Boolean,
             created : DateTime,
             createdBy : Int ,
             updated : DateTime,
             updatedBy : Int,
             name : String,
             description: String,
             help: String,
             isTranslated: Boolean,
             uuid: String) = ProcessParameterTrl(processParameterId, language, tenantId, organizationId,
    isActive, created, createdBy, updated, updatedBy, name, None, None, isTranslated, uuid)
} 
Example 34
Source File: AttributeProcessPara.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class AttributeProcessPara(attributeProcessParaId: Int,
                                tenantId: Int,
                                organizationId: Int,
                                attributeProcessId: Option[Int],
                                processParaId: Option[Int],
                                created: DateTime = DateTime.now,
                                createdBy: Int,
                                defaultValue: Option[String],
                                isActive: Boolean,
                                updated: DateTime = DateTime.now,
                                updatedBy: Int,
                                uuid: String
                            ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = attributeProcessParaId

  override val entityName: String = "AD_ColumnProcessPara"
  override val identifier: String = "AD_ColumnProcessPara_ID"
}

object AttributeProcessPara {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[AttributeProcessPara]
  def create(attributeProcessParaId: Int,
             tenantId: Int,
             organizationId: Int,
             attributeProcessId: Int,
             processParaId: Int,
             created: DateTime,
             createdBy: Int,
             defaultValue: String,
             isActive: Boolean,
             updated: DateTime,
             updatedBy: Int,
             uuid: String) = AttributeProcessPara(attributeProcessParaId, tenantId, organizationId, None, None,
    created, createdBy, None, isActive, updated, updatedBy, uuid)
} 
Example 35
Source File: SchedulerParameter.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime


case class SchedulerParameter(schedulerId: Int,
                              processParameterId: Int,
                              tenantId: Int,
                              organizationId: Int,
                              isActive: Boolean = true,
                              created: DateTime = DateTime.now,
                              createdBy: Int,
                              updated: DateTime = DateTime.now,
                              updatedBy: Int,
                              parameterDefault: Option[String],
                              description: Option[String],
                              uuid: String
                         )extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = schedulerId

  override val entityName: String = "AD_Scheduler_Para"
  override val identifier: String = null

}

object SchedulerParameter {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[SchedulerParameter]
  def create(schedulerId: Int,
             processParameterId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             parameterDefault: String,
             description: String,
             uuid: String) = SchedulerParameter(schedulerId, processParameterId, tenantId, organizationId, isActive, created,
    createdBy, updated, updatedBy, None, None, uuid)
} 
Example 36
Source File: PrintFormatItemTrl.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime

case class PrintFormatItemTrl (printFormatItemId: Int,
                               language: String,
                               tenantId: Int,
                               organizationId: Int,
                               isActive: Boolean = true,
                               created: DateTime = DateTime.now,
                               createdBy: Int,
                               updated: DateTime = DateTime.now,
                               updatedBy: Int,
                               printName: Option[String],
                               isTranslated : Boolean = false,
                               printNameSuffix: Option[String],
                               uuid: String
                              ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = printFormatItemId

  override val entityName: String = "AD_PrintFormatItem_Trl"
  override val identifier: String = null

}

object PrintFormatItemTrl {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[PrintFormatItemTrl]
  def create(printFormatItemId: Int,
             language: String,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             printName: String,
             isTranslated : Boolean,
             printNameSuffix: String,
             uuid: String) = PrintFormatItemTrl(printFormatItemId, language, tenantId, organizationId, isActive,
    created, createdBy, updated, updatedBy, None, isTranslated, None, uuid)
} 
Example 37
Source File: WorkflowProcessor.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime


case class WorkflowProcessor(workflowProcessorId: Int,
                             tenantId: Int,
                             organizationId : Int ,
                             isActive: Boolean = true,
                             created: DateTime = DateTime.now,
                             createdBy: Int,
                             updated: DateTime = DateTime.now,
                             updatedBy: Int,
                             name: String,
                             description: Option[String],
                             frequencyType: Boolean,
                             frequency: Int,
                             dateLastRun: Option[DateTime],
                             dateNextRun: Option[DateTime],
                             supervisorId: Int,
                             keepLogDays: Int,
                             processing: Option[Boolean],
                             inactivityAlertDays: Option[Int],
                             remindDays: Option[Int],
                             alertOverPriority: Option[Int],
                             uuid: String
                             ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type
  override def Id: Int = workflowProcessorId

  override val entityName: String = "AD_WorkflowProcessor"
  override val identifier: String = "AD_WorkflowProcessor_ID"

}

object WorkflowProcessor {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[WorkflowProcessor]
  def create(workflowProcessorId: Int,
             tenantId: Int,
             organizationId : Int ,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             name: String,
             description: String,
             frequencyType: Boolean,
             frequency: Int,
             dateLastRun: DateTime,
             dateNextRun: DateTime,
             supervisorId: Int,
             keepLogDays: Int,
             processing: Boolean,
             inactivityAlertDays: Int,
             remindDays: Int,
             alertOverPriority: Int,
             uuid: String) = WorkflowProcessor(workflowProcessorId, tenantId, organizationId, isActive, created,
    createdBy, updated, updatedBy, name, None, frequencyType, frequency, None, None, supervisorId, keepLogDays,
    None, None, None, None, uuid)
} 
Example 38
Source File: PrintLabel.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime


case class PrintLabel (printLabelId: Int,
                       tenantId: Int,
                       organizationId: Int,
                       isActive: Boolean = true,
                       created: DateTime = DateTime.now,
                       createdBy: Int,
                       updated: DateTime = DateTime.now,
                       updatedBy: Int,
                       name: String,
                       description: Option[String],
                       entityId: Int,
                       printerName: Option[String],
                       isLandscape: Boolean = true,
                       labelHeight: Int,
                       labelWidth: Int,
                       labelPrinterId: Int,
                       uuid: String
                      ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type
  override def Id: Int = printLabelId

  override val entityName: String = "AD_PrintLabel"
  override val identifier: String = "AD_PrintLabel_ID"

}

object PrintLabel {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[PrintLabel]
  def create(printLabelId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             name: String,
             description: String,
             entityId: Int,
             printerName: String,
             isLandscape: Boolean,
             labelHeight: Int,
             labelWidth: Int,
             labelPrinterId: Int,
             uuid: String) = PrintLabel(printLabelId, tenantId, organizationId, isActive, created, createdBy, updated,
    updatedBy, name, None, entityId, None, isLandscape, labelHeight, labelWidth, labelPrinterId, uuid)
} 
Example 39
Source File: WorkflowProcess.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class WorkflowProcess(workflowProcessId: Int,
                           tenantId: Int,
                           organizationId : Int ,
                           isActive: Boolean = true,
                           created: DateTime = DateTime.now,
                           createdBy: Int,
                           updated: DateTime = DateTime.now,
                           updatedBy: Int,
                           workFlowId: Int,
                           workflowResponsiveId: Int,
                           userId: Option[Int],
                           workflowState: String,
                           messageId: Option[Int],
                           processing: Option[Boolean],
                           processed: Boolean = false,
                           textMsg: Option[String],
                           entityId: Int,
                           recordId: Int,
                           priority: Option[Int],
                           uuid: String
                    ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = workflowProcessId

  override val entityName: String = "AD_Wf_Process"
  override val identifier: String = "AD_Wf_Process_ID"
}


object WorkflowProcess {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[WorkflowProcess]
  def create(workflowProcessId: Int,
             tenantId: Int,
             organizationId : Int ,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             workFlowId: Int,
             workflowResponsiveId: Int,
             userId: Int,
             workflowState: String,
             messageId: Int,
             processing: Boolean,
             processed: Boolean,
             textMsg: String,
             entityId: Int,
             recordId: Int,
             priority: Int,
             uuid: String) = WorkflowProcess(workflowProcessId, tenantId, organizationId, isActive, created,
    createdBy, updated, updatedBy, workFlowId, workflowResponsiveId, None, workflowState, None, None,
    processed, None, entityId, recordId, None, uuid)

} 
Example 40
Source File: SearchDefinition.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime


case class SearchDefinition (searchDefinitionId: Int,
                             tenantId: Int,
                             attributeId: Option[Int],
                             organizationId: Int,
                             entityId: Int,
                             windowId: Int,
                             created: DateTime = DateTime.now,
                             createdBy: Int,
                             dataType: Boolean,
                             description: Option[String],
                             isActive: Boolean = true,
                             name: Option[String],
                             query: Option[String],
                             searchType: Boolean,
                             transactionCode: Option[String],
                             updated : DateTime = DateTime.now ,
                             updatedBy : Int,
                             poWindowId:Option[Int],
                             isDefault: Boolean = false,
                             uuid: String
                            ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = searchDefinitionId

  override val entityName: String = "AD_SearchDefinition"
  override val identifier: String = "AD_SearchDefinition_ID"

}

object SearchDefinition {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[SearchDefinition]
  def create(searchDefinitionId: Int,
             tenantId: Int,
             attributeId: Int,
             organizationId: Int,
             entityId: Int,
             windowId: Int,
             created: DateTime,
             createdBy: Int,
             dataType: Boolean,
             description: Option[String],
             isActive: Boolean,
             name: String,
             query: String,
             searchType: Boolean,
             transactionCode: String,
             updated :DateTime,
             updatedBy : Int,
             poWindowId:Int,
             isDefault: Boolean,
             uuid: String) = SearchDefinition(searchDefinitionId, tenantId, None, organizationId, entityId, windowId,
    updated, updatedBy, dataType, None, isActive, None, None, searchType, None, updated, updatedBy, None, isDefault, uuid)
} 
Example 41
Source File: Registration.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class Registration(registrationId: Int,
                        tenantId: Int,
                        systemId: Int,
                        organizationId: Int,
                        isActive : Boolean = true,
                        created : DateTime = DateTime.now,
                        createdBy : Int ,
                        updated : DateTime = DateTime.now,
                        updatedBy :Int,
                        isRegistered: Boolean = false,
                        recordId: Option[Int],
                        description: Option[String],
                        locationId: Option[Int],
                        isInProduction: Boolean = false,
                        startProductionDate: DateTime = new DateTime,
                        isAllowPublish: Boolean = true,
                        isAllowStatistics: Boolean = true,
                        platformInfo: Option[String],
                        industryInfo: Option[String],
                        salesVolume: Int = 0,
                        currencyId: Option[Int],
                        numberEmployees: Int = 0,
                        processing: Option[Boolean],
                        remoteHost: Option[String],
                        remoteAddress: Option[String],
                        uuid: String
                       ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = registrationId

  override val entityName: String = "AD_Registration"
  override val identifier: String = "AD_Registration_ID"
}

object Registration  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[Registration]
  def create(registrationId: Int,
             tenantId: Int,
             systemId: Int,
             organizationId: Int,
             isActive : Boolean,
             created : DateTime ,
             createdBy : Int ,
             updated : DateTime,
             updatedBy :Int,
             isRegistered: Boolean,
             recordId: Int,
             description: String,
             locationId: Int,
             isInProduction: Boolean,
             startProductionDate: DateTime ,
             isAllowPublish: Boolean ,
             isAllowStatistics: Boolean,
             platformInfo: String,
             industryInfo: String,
             salesVolume: Int,
             currencyId: Int,
             numberEmployees: Int ,
             processing: Boolean,
             remoteHost: String,
             remoteAddress: String,
             uuid: String) = Registration(registrationId, tenantId, systemId, organizationId, isActive,
    created, createdBy, updated, updatedBy, isRegistered, None, None, None, isInProduction, startProductionDate,
    isAllowPublish, isAllowStatistics, None, None, salesVolume, None, numberEmployees, None, None, None, uuid)
} 
Example 42
Source File: Window.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class Window(windowId: Int,
                  tenantId: Int,
                  organizationId : Int ,
                  isActive: Boolean = true,
                  created: DateTime = DateTime.now,
                  createdBy: Int,
                  updated: DateTime = DateTime.now,
                  updatedBy: Int,
                  name: String,
                  description: Option[String],
                  help: Option[String],
                  windowType: Option[Boolean],
                  isSOTrx: Boolean = true,
                  entityType: String = "D",
                  processing: Option[Boolean],
                  imageId: Option[Int],
                  colorId: Option[Int],
                  isDefault: Boolean = false,
                  winHeight: Option[Int],
                  winWidth: Option[Int],
                  isBetaFunctionality: Boolean = false,
                  uuid: String
                 ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = windowId

  override val entityName: String = "AD_Window"
  override val identifier: String = "AD_Window_ID"
}

object Window {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[Window]
  def create(windowId: Int,
             tenantId: Int,
             organizationId : Int ,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             name: String,
             description: String,
             help: String,
             windowType: Boolean,
             isSOTrx: Boolean,
             entityType: String,
             processing: Boolean,
             imageId: Int,
             colorId: Int,
             isDefault: Boolean,
             winHeight: Int,
             winWidth: Int,
             isBetaFunctionality: Boolean,
             uuid: String) = Window(windowId, tenantId, organizationId, isActive, created, createdBy, updated,
    updatedBy, name, None, None, None, isSOTrx, entityType, None, None, None, isDefault,
    None, None, isBetaFunctionality, uuid)
} 
Example 43
Source File: AttributeAccess.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class AttributeAccess(attributeId: Int,
                           roleId: Int,
                           tenantId: Int,
                           organizationId: Int,
                           isActive:Boolean=true,
                           created:DateTime = DateTime.now,
                           createdBy: Int,
                           updated: DateTime = DateTime.now,
                           updatedBy: Int,
                           isReadOnly: Boolean = false,
                           isExclude: Boolean = true,
                           entityId: Option[Int],
                           uuid: String
                       ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = attributeId

  override val entityName: String = "AD_Column_Access"
  override val identifier: String = null
}

object AttributeAccess {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[AttributeAccess]
  def create(attributeId: Int,
             roleId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive:Boolean,
             created:DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             isReadOnly: Boolean,
             isExclude: Boolean,
             entityId: Int,
             uuid: String) = AttributeAccess (attributeId, roleId, tenantId, organizationId,isActive,created,
    createdBy, updated, updatedBy, isReadOnly, isExclude, None, uuid)
} 
Example 44
Source File: Archive.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime




case class Archive(archiveId: Int,
                   tenantId: Int,
                   organizationId: Int,
                   isActive: Boolean = true,
                   created: DateTime = DateTime.now,
                   createdBy: Int,
                   updated: DateTime = DateTime.now,
                   updatedBy: Int,
                   name: String,
                   description: Option[String],
                   help: Option[String],
                   entityId: Option[Int],
                   recordId: Option[Int],
                   processId: Option[Int],
                   binaryData: String,
                   bPartnerId: Option[Int],
                   isReport: Boolean = true,
                   uuid: String
                  ) extends DomainModel


  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = archiveId

  override val entityName: String = "AD_Archive"
  override val identifier: String = "AD_Archive_ID"
}

object Archive {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[Archive]
  def create(archiveId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             name: String,
             description: String,
             help: String,
             entityId: Int,
             recordId: Int,
             processId: Int,
             binaryData: String,
             bPartnerId: Int,
             isReport: Boolean,
             uuid: String) = Archive(archiveId, tenantId, organizationId, isActive, created, createdBy,
    updated, updatedBy, name, None, None, None, None, None, binaryData, None, isReport, uuid)
} 
Example 45
Source File: UserMail.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class UserMail (userMailId: Int,
                     tenantId: Int,
                     organizationId: Int,
                     isActive: Boolean = true,
                     created: DateTime = DateTime.now,
                     createdBy: Int,
                     updated: DateTime = DateTime.now,
                     updatedBy: Int,
                     userId: Int,
                     mailTextId: Option[Int],
                     mailMsgId: Option[Int],
                     messageId: Option[String],
                     deliveryConfirmation: Option[String],
                     isDelivered: Option[Boolean],
                     subject: Option[String],
                     mailText: Option[String],
                     uuid: String
                    ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = userMailId

  override val entityName: String = "AD_UserMail"
  override val identifier: String = "AD_UserMail_ID"
}

object UserMail  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[UserMail]
  def create(userMailId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             userId: Int,
             mailTextId: Int,
             mailMsgId: Int,
             messageId: String,
             deliveryConfirmation: String,
             isDelivered: Boolean,
             subject: String,
             mailText: String,
             uuid: String) = UserMail(userMailId, tenantId, organizationId, isActive, created, createdBy,
    updated, updatedBy, userId, None, None, None, None, None, None, None, uuid)
} 
Example 46
Source File: PackageImportProcess.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime

case class PackageImportProcess(packageImportProcessId: Int,
                                tenantId: Int,
                                organizationId: Int,
                                isActive: Boolean = true,
                                created: DateTime = DateTime.now,
                                createdBy: Int,
                                updated: DateTime = DateTime.now,
                                updatedBy: Int,
                                overrideDict: Option[Boolean],
                                packageDir: Option[String],
                                packageSource: Option[String],
                                packageSourceType: String,
                                processing: Option[Boolean],
                                uuid: String
                          ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type
  override def Id: Int = packageImportProcessId

  override val entityName: String = "AD_Package_Imp_Proc"
  override val identifier: String = "AD_Package_Imp_Proc_ID"

}

object PackageImportProcess {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[PackageImportProcess]
  def create(packageImportProcessId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             overrideDict: Boolean,
             packageDir: String,
             packageSource: String,
             packageSourceType: String,
             processing: Boolean,
             uuid: String) = PackageImportProcess(packageImportProcessId, tenantId, organizationId, isActive, created,
    createdBy, updated, updatedBy, None, None, None, packageSourceType, None, uuid)
} 
Example 47
Source File: InformationColumn.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class InformationColumn(infoColumnId: Int,
                             tenantId : Int ,
                             organizationId : Int,
                             isActive: Boolean = true,
                             created: DateTime = DateTime.now,
                             createdBy: Int,
                             updated: DateTime = DateTime.now,
                             updatedBy: Int,
                             name: String,
                             description: Option[String],
                             help: Option[String],
                             infoWindowId: Int,
                             entityType: String = "D",
                             selectClause: String,
                             seqNo: Int = 0,
                             isDisplayed : Boolean = true,
                             isQueryCriteria: Boolean = false,
                             elementId: Option[Int],
                             referenceId: Int,
                             uuid: String
                     ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = infoColumnId

  override val entityName: String = "AD_InfoColumn"
  override val identifier: String = "AD_InfoColumn_ID"
}

object InformationColumn  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[InformationColumn]
  def create(infoColumnId: Int,
             tenantId : Int ,
             organizationId : Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             name: String,
             description: String,
             help: String,
             infoWindowId: Int,
             entityType: String,
             selectClause: String,
             seqNo: Int,
             isDisplayed : Boolean,
             isQueryCriteria: Boolean,
             elementId: Int,
             referenceId: Int,
             uuid: String) = InformationColumn(infoColumnId, tenantId, organizationId, isActive, created, createdBy,
    updated, updatedBy, name, None, None, infoWindowId, entityType, selectClause, seqNo,
    isDisplayed, isQueryCriteria, None, referenceId, uuid)
} 
Example 48
Source File: PackageImportBackup.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime


case class PackageImportBackup(packageImportBackupId: Int,
                               tenantId: Int,
                               organizationId: Int,
                               isActive: Boolean = true,
                               created: DateTime = DateTime.now,
                               createdBy: Int,
                               updated: DateTime = DateTime.now,
                               updatedBy: Int,
                               packageImportId: Int,
                               packageImportDetailId: Int,
                               entityId: Option[Int],
                               attributeId: Option[Int],
                               referenceId: Option[Int],
                               packageImportBckDir: Option[String],
                               packageImportOrgDir: Option[String],
                               colValue: Option[String],
                               uninstall: Option[Boolean],
                               uuid: String
                            ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type
  override def Id: Int = packageImportBackupId

  override val entityName: String = "AD_Package_Imp_Backup"
  override val identifier: String = "AD_Package_Imp_Backup_ID"

}

object PackageImportBackup {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[PackageImportBackup]
  def create(packageImportBackupId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             packageImportId: Int,
             packageImportDetailId: Int,
             entityId: Int,
             attributeId: Int,
             referenceId: Int,
             packageImportBckDir: String,
             packageImportOrgDir: String,
             colValue: String,
             uninstall: Boolean,
             uuid: String) = PackageImportBackup(packageImportBackupId, tenantId, organizationId, isActive, created,
    createdBy, updated, updatedBy, packageImportId, packageImportDetailId, None, None, None, None, None, None, None,
    uuid)
} 
Example 49
Source File: UserDefinedField.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class UserDefinedField(userDefinedFieldId: Int,
                            tenantId: Int,
                            organizationId: Int,
                            isActive: Boolean = true,
                            created: DateTime = DateTime.now,
                            createdBy: Int,
                            updated: DateTime = DateTime.now,
                            updatedBy: Int,
                            userDefinedTabId: Int,
                            fieldId: Int,
                            name: String,
                            description: Option[String],
                            help: Option[String],
                            isDisplayed: Boolean = true,
                            isReadOnly: Boolean = false,
                            isSameLine: Boolean = false,
                            isUpdateable: Boolean = true,
                            displayLength: Int = 0,
                            displayLogic: String,
                            defaultValue: String,
                            sortNo: Int = 0,
                            seqNo: Int = 0,
                            uuid: String
                       )extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = userDefinedFieldId

  override val entityName: String = "AD_UserDef_Field"
  override val identifier: String = "AD_UserDef_Field_ID"
}

object UserDefinedField  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[UserDefinedField]
  def create(userDefinedFieldId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             userDefinedTabId: Int,
             fieldId: Int,
             name: String,
             description: String,
             help: String,
             isDisplayed: Boolean,
             isReadOnly: Boolean,
             isSameLine: Boolean,
             isUpdateable: Boolean,
             displayLength: Int,
             displayLogic: String,
             defaultValue: String,
             sortNo: Int,
             seqNo: Int,
             uuid: String) = UserDefinedField(userDefinedFieldId, tenantId, organizationId, isActive, created, createdBy,
    updated, updatedBy, userDefinedTabId, fieldId, name, None, None, isDisplayed, isReadOnly, isSameLine, isUpdateable,
    displayLength, displayLogic, defaultValue, sortNo, seqNo, uuid)
} 
Example 50
Source File: TreeNodeCMC.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class TreeNodeCMC(treeId: Int,
                       nodeId: Int,
                       tenantId: Int,
                       organizationId: Int,
                       isActive: Boolean = true,
                       created: DateTime = DateTime.now,
                       createdBy: Int,
                       updatedBy: Int,
                       updated: DateTime = DateTime.now,
                       parentId: Option[Int],
                       seqNo: Option[Int],
                       uuid: String
                      ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = treeId

  override val entityName: String = "AD_TreeNodeCMC"
  override val identifier: String = null
}

object TreeNodeCMC  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[TreeNodeCMC]
  def create(treeNodeCMCId: Int,
             nodeId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updatedBy: Int,
             updated: DateTime,
             parentId: Int,
             seqNo: Int,
             uuid: String) = TreeNodeCMC(treeNodeCMCId, nodeId, tenantId,organizationId, isActive, created,
    createdBy, updatedBy, updated, None, None, uuid)
} 
Example 51
Source File: LabelPrinter.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime


case class LabelPrinter (labelPrinterId: Int,
                         tenantId: Int,
                         organizationId: Int,
                         isActive: Boolean = true,
                         created: DateTime = DateTime.now,
                         createdBy: Int,
                         updated: DateTime = DateTime.now,
                         updatedBy: Int,
                         name: String,
                         description: Option[String],
                         uuid: String
                        ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type
  override def Id: Int = labelPrinterId

  override val entityName: String = "AD_LabelPrinter"
  override val identifier: String = "AD_LabelPrinter_ID"

}

object LabelPrinter{
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[LabelPrinter]

  def create(labelPrinterId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             name: String,
             description: String,
             uuid: String) = LabelPrinter(labelPrinterId, tenantId, organizationId, isActive, created, createdBy,
    updated, updatedBy, name, None, uuid)
} 
Example 52
Source File: ReplicationLog.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class ReplicationLog(replicationLogId: Int,
                          tenantId: Int,
                          organizationId: Int,
                          isActive : Boolean = true,
                          created : DateTime = DateTime.now,
                          createdBy : Int ,
                          updated : DateTime = DateTime.now,
                          updatedBy : Int,
                          replicationRunId: Int,
                          replicationTableId: Option[Int],
                          message: Option[String],
                          isReplicated: Boolean = false,
                          uuid: String
                         ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = replicationLogId

  override val entityName: String = "AD_Replication_Log"
  override val identifier: String = "AD_Replication_Log_ID"
}

object ReplicationLog  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[ReplicationLog]
  def create(replicationLogId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive : Boolean,
             created : DateTime,
             createdBy : Int ,
             updated : DateTime,
             updatedBy : Int,
             replicationRunId: Int,
             replicationTableId: Int,
             message: String,
             isReplicated: Boolean,
             uuid: String) = ReplicationLog(replicationLogId, tenantId, organizationId, isActive, created,
    createdBy, updated, updatedBy, replicationRunId, None, None, isReplicated, uuid)
} 
Example 53
Source File: FieldGroupTrl.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class FieldGroupTrl (fieldGroupId: Int,
                          language: String,
                          tenantId: Int,
                          organizationId: Int,
                          isActive: Boolean = true,
                          created: DateTime= DateTime.now,
                          createdBy: Int,
                          updated: DateTime = DateTime.now,
                          updatedBy: Int,
                          name: String,
                          isTranslated: Boolean = false,
                          uuid: String
                         ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type
  override def Id: Int = fieldGroupId

  override val entityName: String = "AD_FieldGroup_Trl"
  override val identifier: String = null

}

object FieldGroupTrl {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[FieldGroupTrl]
  def create(fieldGroupId: Int ,
             language: String,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             name: String,
             isTranslated: Boolean,
             uuid: String) = FieldGroupTrl(fieldGroupId, language, tenantId, organizationId, isActive, created,
    createdBy, updated, updatedBy, name, isTranslated, uuid)
} 
Example 54
Source File: ReplicationStrategy.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime


case class ReplicationStrategy (replicationStrategyId: Int,
                                tenantId: Int,
                                organizationId: Int,
                                isActive : Boolean = true,
                                created : DateTime = DateTime.now,
                                createdBy : Int ,
                                updated : DateTime = DateTime.now,
                                updatedBy : Int,
                                name: Int,
                                description: Option[String],
                                help: Option[String],
                                entityType: String = "D",
                                expProcessorId: Option[Int],
                                value: Option[Int],
                                uuid: String
                               ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = replicationStrategyId

  override val entityName: String = "AD_ReplicationStrategy"
  override val identifier: String = "AD_ReplicationStrategy_ID"
}

object ReplicationStrategy  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[ReplicationStrategy]
  def create(replicationStrategyId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive : Boolean,
             created : DateTime,
             createdBy : Int ,
             updated : DateTime,
             updatedBy : Int,
             name: Int,
             description: String,
             help: String,
             entityType: String,
             expProcessorId: Int,
             value: Int,
             uuid: String) = ReplicationStrategy(replicationStrategyId,tenantId, organizationId, isActive,
    created, createdBy, updated, updatedBy, name, None, None, entityType, None, None, uuid)
} 
Example 55
Source File: ChartDataSource.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime


case class ChartDataSource (chartDataSourceId: Int,
                            chartId: Int,
                            tenantId: Int,
                            organizationId: Int,
                            entityId: Option[Int],
                            categoryAttribute: Option[String],
                            created: DateTime = DateTime.now,
                            createdBy: Int,
                            dateAttribute: Option[String],
                            description: Option[String],
                            entityType: String = "D",
                            fromClause: String,
                            isActive: Boolean = true,
                            keyAttribute: Option[String],
                            Name: String,
                            updated: DateTime = DateTime.now,
                            updatedBy: Int,
                            valueAttribute: String,
                            whereClause: String,
                            timeOffSet: Option[Int],
                            seriesAttribute: Option[String],
                            uuid: String
                           ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type
  override def Id: Int = chartDataSourceId

  override val entityName: String = "AD_ChartDataSource"
  override val identifier: String = "AD_ChartDataSource_ID"

}

object ChartDataSource {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[ChartDataSource]
  def create(chartDataSourceId: Int,
             chartId: Int,
             tenantId: Int,
             organizationId: Int,
             entityId: Int,
             categoryAttribute: String,
             created:  DateTime,
             createdBy: Int,
             dateAttribute: String,
             description: String,
             entityType: String,
             fromClause: String,
             isActive: Boolean,
             keyAttribute: String,
             Name: String,
             updated:  DateTime,
             updatedBy: Int,
             valueAttribute: String,
             whereClause: String,
             timeOffSet:Int,
             seriesAttribute: String,
             uuid: String) = ChartDataSource(chartDataSourceId, chartId, tenantId, organizationId, None, None, created,
    createdBy, None, None, entityType, fromClause, isActive, None, Name, updated, updatedBy, valueAttribute, whereClause,
    None, None, uuid)
} 
Example 56
Source File: HouseKeeping.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class HouseKeeping (houseKeepingId: Int,
                         tenantId : Int ,
                         organizationId : Int ,
                         entityId: Int,
                         backupFolder: Option[String],
                         created: DateTime = DateTime.now,
                         createdBy: Int,
                         description: Option[String],
                         help: Option[String],
                         isActive: Boolean = true,
                         isExportXMLBackup: Option[Boolean],
                         isSaveInHistoric: Option[Boolean],
                         lastDeleted: Option[Int],
                         lastRun: DateTime = new DateTime,
                         name: String,
                         processing: Option[Boolean],
                         updated: DateTime = DateTime.now,
                         updatedBy: Int,
                         value: String,
                         whereClause: Option[String],
                         uuid: String
                        ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = houseKeepingId

  override val entityName: String = "AD_HouseKeeping"
  override val identifier: String = "AD_HouseKeeping_ID"
}

object HouseKeeping  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[HouseKeeping]
  def create(houseKeepingId: Int,
             tenantId : Int ,
             organizationId : Int ,
             entityId: Int,
             backupFolder: String,
             created: DateTime,
             createdBy: Int,
             description: String,
             help: Option[String],
             isActive: Boolean,
             isExportXMLBackup: Boolean,
             isSaveInHistoric: Boolean,
             lastDeleted: Int,
             lastRun: DateTime,
             name: String,
             processing: Boolean,
             updated: DateTime,
             updatedBy: Int,
             value: String,
             whereClause: String,
             uuid: String) = HouseKeeping(houseKeepingId, tenantId, organizationId, entityId, None, created, createdBy,
    None, None, isActive, None, None, None, lastRun, name, None, updated, updatedBy, value, None, uuid)
} 
Example 57
Source File: WindowTrl.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class WindowTrl(windowId: Int,
                     tenantId: Int,
                     organizationId : Int ,
                     language: String,
                     isActive: Boolean = true,
                     created: DateTime = DateTime.now,
                     createdBy: Int,
                     updated: DateTime = DateTime.now,
                     updatedBy: Int,
                     name: String,
                     description: Option[String],
                     help: Option[String],
                     isTranslated: Boolean = false,
                     uuid: String
                    ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = windowId

  override val entityName: String = "AD_WindowTrl"
  override val identifier: String = null
}

object WindowTrl {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[WindowTrl]
  def create(windowId: Int,
             tenantId: Int,
             organizationId : Int ,
             language: String,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             name: String,
             description: String,
             help: String,
             isTranslated: Boolean,
             uuid: String) = WindowTrl(windowId, tenantId, organizationId, language, isActive, created, createdBy,
    updated, updatedBy, name, None, None, isTranslated, uuid)
} 
Example 58
Source File: Element.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime
import play.api.libs.json.{Format, Json}



case class Element(elementId: Int,
                   tenantId: Int,
                   organizationId: Int,
                   isActive: Boolean = true,
                   created: DateTime =  DateTime.now,
                   createdBy: Int,
                   updated: DateTime =  DateTime.now,
                   updatedBy: Int,
                   columnName: String,
                   entityType: String,
                   name: String,
                   printName: Option[String],
                   description: Option[String],
                   help: Option[String],
                   namePO: Option[String],
                   printNamePO: Option[String],
                   descriptionPO : Option[String],
                   helpPO: Option[String],
                   referenceId: Option[Int],
                   fieldLength: Option[Int],
                   referenceValueId: Option[Int],
                   uuid: String
                   ) extends DomainModel
with ActiveEnabled
with Identifiable
with Traceable{
  override type DomainModel = this.type
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type
  override def Id: Int = elementId

  override val entityName: String = "AD_Element"
  override val identifier: String = "AD_Element_ID"
}

object Element {
  implicit val format: Format[Element] = Json.format
  def create(elementId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean ,
             created: DateTime ,
             createdBy: Int,
             updated: DateTime ,
             updatedBy: Int,
             columnName: String,
             entityType: String,
             name: String,
             printName: String,
             description: String,
             help: String,
             namePO: String,
             printNamePO: String,
             descriptionPO : String,
             helpPO: String,
             referenceId: Int,
             fieldLength: Int,
             referenceValueId: Int,
             uuid: String) = Element(elementId, tenantId, organizationId, isActive , created , createdBy ,
    updated , updatedBy , columnName, entityType, name, None, None, None, None, None, None, None, None, None, None,
    uuid)
} 
Example 59
Source File: TreeNodeU4.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class TreeNodeU4(treeId: Int,
                      nodeId: Int,
                      tenantId: Int,
                      organizationId: Int,
                      isActive: Boolean = true,
                      created: DateTime = DateTime.now,
                      createdBy: Int,
                      updatedBy: Int,
                      updated: DateTime = DateTime.now,
                      parentId: Option[Int],
                      seqNo: Option[Int],
                      uuid: String
                     ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = treeId

  override val entityName: String = "AD_TreeNodeU4"
  override val identifier: String = null
}

object TreeNodeU4  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[TreeNodeU4]
  def create(treeId: Int,
             nodeId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updatedBy: Int,
             updated: DateTime,
             parentId: Int,
             seqNo: Int,
             uuid: String) = TreeNodeU4(treeId, nodeId, tenantId, organizationId, isActive, created,
    createdBy, updatedBy, updated, None, None, uuid)
} 
Example 60
Source File: BrowseAccess.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class BrowseAccess(tenantId: Int,
                        organizationId: Int,
                        created: DateTime =  DateTime.now,
                        createdBy: Int,
                        isActive: Boolean = true,
                        updated: DateTime =  DateTime.now,
                        updatedBy: Int,
                        browseId: Int,
                        roleId: Int,
                        isReadWrite: Boolean = true,
                        uuid: String
                       )extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = browseId

  override val entityName: String = "AD_Browse_Access"
  override val identifier: String = null
}

object BrowseAccess  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[BrowseAccess]
  def create(tenantId: Int,
             organizationId: Int,
             created: DateTime,
             createdBy: Int,
             isActive: Boolean,
             updated: DateTime,
             updatedBy: Int,
             browseId: Int,
             roleId: Int,
             isReadWrite: Boolean,
             uuid: String) = BrowseAccess(tenantId, organizationId, created, createdBy, isActive, updated,
    updatedBy, browseId, roleId, isReadWrite, uuid)
} 
Example 61
Source File: ChangeLog.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime


case class ChangeLog(changeLogId: Int,
                     sessionId: Int,
                     entityId: Int,
                     attributeId: Int,
                     tenantId: Int,
                     organizationId: Int,
                     isActive : Boolean = true,
                     created : DateTime = DateTime.now,
                     createdBy : Int ,
                     updated : DateTime = DateTime.now,
                     updatedBy : Int ,
                     recordId : Int,
                     oldValue : String,
                     newValue : String,
                     undo : Boolean ,
                     redo : Boolean ,
                     isCustomization : Boolean ,
                     trxName : String,
                     description: Option[String],
                     eventChangeLog : String,
                     uuid: String
                    ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = changeLogId

  override val entityName: String = "AD_ChangeLog"
  override val identifier: String = "AD_ChangeLog_ID"
}

object ChangeLog  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[ChangeLog]
  def create(changeLogId: Int,
             sessionId: Int,
             entityId: Int,
             attributeId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive : Boolean,
             created : DateTime,
             createdBy : Int ,
             updated :DateTime ,
             updatedBy : Int,
             recordId : Int,
             oldValue : String,
             newValue : String,
             undo : Boolean,
             redo : Boolean,
             isCustomization : Boolean,
             trxName : String,
             description: String,
             eventChangeLog : String,
             uuid: String) = ChangeLog(changeLogId, sessionId, entityId, attributeId, tenantId, organizationId,
    isActive, created, createdBy, updated, updatedBy, recordId, oldValue, newValue, undo, redo, isCustomization,
    trxName, None, eventChangeLog, uuid)
} 
Example 62
Source File: Message.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class Message(messageId: Int,
                   tenantId : Int ,
                   organizationId : Int,
                   isActive : Boolean = true,
                   created : DateTime = DateTime.now,
                   createdBy : Int ,
                   updated :DateTime = DateTime.now ,
                   updatedBy : Int,
                   value : String,
                   msgText : Option[String],
                   msgTip : Option[String],
                   msgType : Option[String],
                   entityType: String = EntityType.Dictionary,
                   uuid: String
                   ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = messageId

  override val entityName: String = "AD_Message"
  override val identifier: String = "AD_Message_ID"
}

object Message  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[Message]
  def create(messageId: Int,
             tenantId : Int ,
             organizationId : Int,
             isActive : Boolean,
             created : DateTime,
             createdBy : Int ,
             updated : DateTime ,
             updatedBy : Int,
             value : String,
             msgText : String,
             msgTip : String,
             msgType : String,
             entityType: String,
             uuid: String) = Message(messageId, tenantId, organizationId, isActive, created, createdBy,
    updated, updatedBy, value, None, None, None, entityType, uuid)
} 
Example 63
Source File: MigrationStep.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class MigrationStep(migrationStepId: Int,
                         tenantId: Int,
                         organizationId: Int,
                         migrationId: Int,
                         entityId: Option[Int],
                         action: Option[Boolean],
                         applyScript: Option[Boolean],
                         comments: Option[String],
                         created: DateTime =  DateTime.now,
                         createdBy: Int,
                         dbType: String = "ALL",
                         errorMsg: Option[String],
                         isActive: Boolean = true,
                         recordId: Option[Int],
                         seqNo: Int,
                         statusCode: Option[Boolean],
                         stepType: String,
                         updated: DateTime =  DateTime.now,
                         updatedBy: Int,
                         parse: Boolean = true,
                         sqlStatement: Option[String],
                         rollBackStatement: Option[String],
                         uuid: String
                        ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = migrationStepId

  override val entityName: String = "AD_MigrationStep"
  override val identifier: String = "AD_MigrationStep_ID"
}

object MigrationStep  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[MigrationStep]
  def create(migrationStepId: Int,
             tenantId: Int,
             organizationId: Int,
             migrationId: Int,
             entityId: Int,
             action: Boolean,
             applyScript: Boolean,
             comments: String,
             created: DateTime,
             createdBy: Int,
             dbType: String,
             errorMsg: String,
             isActive: Boolean,
             recordId: Int,
             seqNo: Int,
             statusCode: Boolean,
             stepType: String,
             updated: DateTime,
             updatedBy: Int,
             parse: Boolean,
             sqlStatement: String,
             rollBackStatement: String,
             uuid: String) = MigrationStep(migrationStepId, tenantId, organizationId, migrationId, None,
    None, None, None, created, createdBy, dbType, None, isActive, None, seqNo, None, stepType, updated,
    updatedBy, parse, None, None, uuid)
} 
Example 64
Source File: BrowseFieldTrl.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class BrowseFieldTrl(browseFieldId: Int,
                          tenantId: Int,
                          organizationId: Int,
                          created: DateTime =  DateTime.now,
                          createdBy: Int,
                          isActive: Boolean = true,
                          updated: DateTime =  DateTime.now,
                          updatedBy: Int,
                          language: String,
                          description: Option[String],
                          help: Option[String],
                          isTranslated: Boolean,
                          name: String,
                          uuid: String
                         ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = browseFieldId

  override val entityName: String = "AD_Browse_Field_Trl"
  override val identifier: String = null
}

object BrowseFieldTrl  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[BrowseFieldTrl]
  def create(browseFieldId: Int,
             tenantId: Int,
             organizationId: Int,
             created: DateTime,
             createdBy: Int,
             isActive: Boolean,
             updated: DateTime,
             updatedBy: Int,
             language: String,
             description: String,
             help: String,
             isTranslated: Boolean,
             name: String,
             uuid: String) = BrowseFieldTrl(browseFieldId, tenantId, organizationId, created, createdBy, isActive,
    updated, updatedBy, language, None, None, isTranslated, name, uuid)
} 
Example 65
Source File: AttributeValueExtend.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime


case class AttributeValueExtend(attributeId: Int,
                                isActive: Boolean,
                                created: DateTime,
                                createdBy: Int,
                                updated: DateTime,
                                updatedBy: Int,
                                recordId: Int,
                                vNumber: Option[Int],
                                vDate: Option[DateTime],
                                vString: Option[String],
                                uuid: String
                          ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = attributeId

  override val entityName: String = "AD_Attribute_Value"
  override val identifier: String = null

}

object AttributeValueExtend {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[AttributeValueExtend]
  def create(attributeId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             recordId: Int,
             vNumber: Int,
             vDate: DateTime,
             vString: String,
             uuid: String) = AttributeValueExtend(attributeId, isActive, created, createdBy,
    updated, updatedBy, recordId, None, None, None, uuid)
} 
Example 66
Source File: Rule.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model
import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class Rule (ruleId: Int,
                 tenantId : Int,
                 organizationId : Int,
                 accessLevel : Option[String] ,
                 created : DateTime = DateTime.now(),
                 createdBy : Int ,
                 description: Option[String],
                 entityType: String =  EntityType.Dictionary ,
                 eventType : String ,
                 help: Option[String],
                 isActive : Boolean = true,
                 name: String,
                 ruleType : String ,
                 updated : DateTime = DateTime.now,
                 updatedBy :Int,
                 value: String,
                 script : Option[String],
                 uuid: String
                ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = ruleId

  override val entityName: String = "AD_Rule"
  override val identifier: String = "AD_Rule_ID"
}

object Rule  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[Rule]
  def create(ruleId: Int,
             tenantId : Int,
             organizationId : Int,
             accessLevel : String,
             created : DateTime,
             createdBy : Int ,
             description: String,
             entityType: String,
             eventType : String ,
             help: String,
             isActive : Boolean,
             name: String,
             ruleType : String,
             updated : DateTime,
             updatedBy :Int,
             value: String,
             script : String,
             uuid: String) = Rule(ruleId, tenantId, organizationId, None, created, createdBy, None,
    entityType, eventType, None, isActive, name,ruleType, updated, updatedBy, value, None, uuid)
} 
Example 67
Source File: View.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class View(viewId: Int,
                tenantId: Int,
                organizationId : Int ,
                created: DateTime = DateTime.now,
                createdBy: Int,
                isActive: Boolean,
                updated: DateTime = DateTime.now,
                updatedBy: Int,
                value: Option[String],
                name: String,
                description: Option[String],
                entityType: String = "D",
                help: Option[String],
                copyFrom: Option[Boolean],
                uuid: String
               ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = viewId

  override val entityName: String = "AD_View"
  override val identifier: String = "AD_View_ID"
}

object View  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[View]
  def create(viewId: Int,
             tenantId: Int,
             organizationId : Int ,
             created: DateTime,
             createdBy: Int,
             isActive: Boolean,
             updated: DateTime,
             updatedBy: Int,
             value: String,
             name: String,
             description: String,
             entityType: String,
             help: String,
             copyFrom: Boolean,
             uuid: String) = View(viewId, tenantId, organizationId, created, createdBy, isActive, updated,
    updatedBy, None, name, None, entityType, None, None, uuid)
} 
Example 68
Source File: MigrationScript.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class MigrationScript(tenantId: Int,
                           migrationScriptId: Int,
                           organizationId: Int,
                           created: DateTime =  DateTime.now,
                           createdBy: Int,
                           description: Option[String],
                           developerName: Option[String],
                           isActive: Boolean = true,
                           name: String,
                           projectName: String,
                           reference: Option[String],
                           releaseNo: String,
                           scriptRoll: Option[Boolean],
                           status: String,
                           url: Option[String],
                           updated: DateTime =  DateTime.now,
                           updatedBy: Int,
                           isApply: Boolean,
                           filename: String,
                           script: String,
                           uuid: String
                          ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = migrationScriptId

  override val entityName: String = "AD_MigrationScript"
  override val identifier: String = "AD_MigrationScript_ID"
}

object MigrationScript {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[MigrationScript]
  def create(tenantId: Int,
             migrationScriptId: Int,
             organizationId: Int,
             created: DateTime,
             createdBy: Int,
             description: String,
             developerName: String,
             isActive: Boolean,
             name: String,
             projectName: String,
             reference: String,
             releaseNo: String,
             scriptRoll: Boolean,
             status: String,
             url: String,
             updated: DateTime,
             updatedBy: Int,
             isApply: Boolean,
             filename: String,
             script: String,
             uuid: String) = MigrationScript(tenantId, migrationScriptId, organizationId, created, createdBy, None,
    None, isActive, name, projectName, None, releaseNo, None, status, None, updated, updatedBy, isApply, filename,
    script, uuid)
} 
Example 69
Source File: ReplicationTable.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime


case class ReplicationTable (replicationTableId: Int,
                             tenantId: Int,
                             organizationId: Int,
                             isActive : Boolean = true,
                             created : DateTime = DateTime.now,
                             createdBy : Int ,
                             updated : DateTime = DateTime.now,
                             updatedBy : Int,
                             replicationStrategyId: Int,
                             entityId: Int,
                             replicationType: String = "L",
                             entityType: String = "D",
                             description: Option[String],
                             uuid: String
                            ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = replicationTableId

  override val entityName: String = "AD_ReplicationTable"
  override val identifier: String = "AD_ReplicationTable_ID"
}

object ReplicationTable  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[ReplicationTable]
  def create(replicationTableId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive : Boolean,
             created : DateTime,
             createdBy : Int ,
             updated : DateTime,
             updatedBy : Int,
             replicationStrategyId: Int,
             entityId: Int,
             replicationType: String,
             entityType: String,
             description: String,
             uuid: String) = ReplicationTable(replicationTableId, tenantId, organizationId, isActive, created,
    createdBy, updated, updatedBy, replicationStrategyId, entityId, replicationType, entityType, None, uuid)
} 
Example 70
Source File: PrintLabelLine.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime


case class PrintLabelLine (printLabelLineId: Int,
                           tenantId: Int,
                           organizationId: Int,
                           isActive: Boolean = true,
                           created: DateTime = DateTime.now,
                           createdBy: Int,
                           updated: DateTime = DateTime.now,
                           updatedBy: Int,
                           printLabelId: Int,
                           name: String,
                           seqNo: Int,
                           labelFormatType: Boolean,
                           printName: Option[String],
                           attributeId: Int,
                           labelPrinterFunctionId: Int,
                           xPosition: Int,
                           yPosition: Int,
                           uuid: String
                          ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type
  override def Id: Int = printLabelLineId

  override val entityName: String = "AD_PrintLabelLine"
  override val identifier: String = "AD_PrintGLabelLine_ID"

}

object PrintLabelLine {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[PrintLabelLine]
  def create(printLabelLineId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             printLabelId: Int,
             name: String,
             seqNo: Int,
             labelFormatType: Boolean,
             printName: String,
             attributeId: Int,
             labelPrinterFunctionId: Int,
             xPosition: Int,
             yPosition: Int,
             uuid: String) = PrintLabelLine(printLabelLineId, tenantId, organizationId, isActive, created, createdBy,
    updated, updatedBy, printLabelId, name, seqNo, labelFormatType, None, attributeId, labelPrinterFunctionId, xPosition,
    yPosition, uuid)
} 
Example 71
Source File: InformationWindowTrl.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class InformationWindowTrl(infoWindowId: Int,
                                language: String,
                                tenantId : Int ,
                                organizationId : Int,
                                isActive: Boolean = true,
                                created: DateTime = DateTime.now,
                                createdBy: Int,
                                updated: DateTime = DateTime.now,
                                updatedBy: Int,
                                isTranslated: Boolean = false,
                                name: String,
                                description: Option[String],
                                help: Option[String],
                                uuid: String
                         ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = infoWindowId

  override val entityName: String = "AD_InfoWindow_Trl"
  override val identifier: String = null
}

object InformationWindowTrl  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[InformationWindowTrl]
  def create(infoWindowId: Int,
             language: String,
             tenantId : Int ,
             organizationId : Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             isTranslated: Boolean,
             name: String,
             description: String,
             help: String,
             uuid: String) = InformationWindowTrl(infoWindowId, language, tenantId, organizationId, isActive, created,
    createdBy, updated, updatedBy, isTranslated, name, None, None, uuid)
} 
Example 72
Source File: ReplicationDocument.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class ReplicationDocument(replicationDocumentId: Int,
                               replicationStrategyId: Int,
                               tenantId: Int,
                               organizationId: Int,
                               isActive : Boolean = true,
                               created : DateTime = DateTime.now,
                               createdBy : Int ,
                               updated : DateTime = DateTime.now,
                               updatedBy : Int,
                               description: Option[String],
                               docTypeId: Int,
                               replicationType: Boolean,
                               entityId: Int,
                               uuid: String
                              ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = replicationDocumentId

  override val entityName: String = "AD_ReplicationDocument"
  override val identifier: String = "AD_ReplicationDocument_ID"
}

object ReplicationDocument  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[ReplicationDocument]
  def create(replicationDocumentId: Int,
             replicationStrategyId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive : Boolean,
             created : DateTime,
             createdBy : Int ,
             updated : DateTime,
             updatedBy : Int,
             description: String,
             docTypeId: Int,
             replicationType: Boolean,
             entityId: Int,
             uuid: String) = ReplicationDocument(replicationDocumentId, replicationStrategyId, tenantId,
    organizationId, isActive, created, createdBy, updated, updatedBy, None, docTypeId, replicationType,
    entityId, uuid)
} 
Example 73
Source File: TreeNodeMM.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class TreeNodeMM(treeId: Int,
                      nodeId: Int,
                      tenantId: Int,
                      organizationId: Int,
                      isActive: Boolean = true,
                      created: DateTime = DateTime.now,
                      createdBy: Int,
                      updated: DateTime = DateTime.now,
                      updatedBy: Int,
                      parentId: Option[Int],
                      seqNo: Option[Int],
                      uuid: String
                     ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = treeId

  override val entityName: String = "AD_TreeNodeMM"
  override val identifier: String = null
}

object TreeNodeMM  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[TreeNodeMM]
  def create(treeNodeMMId: Int,
             nodeId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             parentId: Int,
             seqNo: Int,
             uuid: String) = TreeNodeMM(treeNodeMMId, nodeId, tenantId, organizationId, isActive, created,
    createdBy, updated, updatedBy, None, None, uuid)
} 
Example 74
Source File: WorkflowBlock.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class WorkflowBlock(workflowBlockId: Int,
                         isActive: Boolean = true,
                         created: DateTime = DateTime.now,
                         createdBy: Int,
                         updated: DateTime = DateTime.now,
                         updatedBy: Int,
                         name: String,
                         description: Option[String],
                         workflowId: Int,
                         uuid: String
                  ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = workflowBlockId

  override val entityName: String = "AD_Wf_Block"
  override val identifier: String = "AD_Wf_Block_ID"
}

object WorkflowBlock {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[WorkflowBlock]
  def create(workflowBlockId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             name: String,
             description: String,
             workflowId: Int,
             uuid: String) = WorkflowBlock(workflowBlockId, isActive, created, createdBy, updated, updatedBy, name,
    None, workflowId, uuid)
} 
Example 75
Source File: LabelPrinterFunction.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime


case class LabelPrinterFunction (labelPrinterFunctionId: Int,
                                 tenantId: Int,
                                 organizationId: Int,
                                 isActive: Boolean = true,
                                 created: DateTime = DateTime.now,
                                 createdBy: Int,
                                 updated: DateTime = DateTime.now,
                                 updatedBy: Int,
                                 name: String,
                                 description: Option[String],
                                 labelPrinterId: Int,
                                 functionPrefix: Option[String],
                                 functionSuffix: Option[String],
                                 isXYPosition: Boolean = false,
                                 xySeparator: Option[String],
                                 uuid: String
                               ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type
  override def Id: Int = labelPrinterFunctionId

  override val entityName: String = "AD_LabelPrinterFunction"
  override val identifier: String = "AD_LabelPrinterFunction_ID"

}

object LabelPrinterFunction{
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[LabelPrinterFunction]

  def create(labelPrinterFunctionId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             name: String,
             description: String,
             labelPrinterId: Int,
             functionPrefix: String,
             functionSuffix: String,
             isXYPosition: Boolean,
             xySeparator: String,
             uuid: String) = LabelPrinterFunction(labelPrinterFunctionId, tenantId, organizationId, isActive, created,
    createdBy, updated, updatedBy, name, None, labelPrinterId, None, None, isXYPosition, None, uuid)
} 
Example 76
Source File: PackageImportInstall.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime

case class PackageImportInstall(packageImportInstallId: Int,
                                tenantId: Int,
                                organizationId: Int,
                                isActive: Boolean = true,
                                created: DateTime = DateTime.now,
                                createdBy: Int,
                                updated: DateTime = DateTime.now,
                                updatedBy: Int,
                                name: Option[String],
                                pkStatus: Option[String],
                                releaseNo: Option[String],
                                pkVersion: Option[String],
                                version: Option[String],
                                description: Option[String],
                                email: Option[String],
                                processed: Boolean = false,
                                processing: Boolean = false,
                                creator: Option[String],
                                creatorContact: Option[String],
                                createdDate: Option[String],
                                updateDate: Option[String],
                                uninstall: Option[Boolean],
                                uuid: String
                          ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type
  override def Id: Int = packageImportInstallId

  override val entityName: String = "AD_Package_Imp_Inst"
  override val identifier: String = "AD_Package_Imp_Inst_ID"

}

object PackageImportInstall {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[PackageImportInstall]
  def create(packageImportInstallId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             name: String,
             pkStatus: String,
             releaseNo: String,
             pkVersion: String,
             version: String,
             description: String,
             email: String,
             processed: Boolean,
             processing: Boolean,
             creator: String,
             creatorContact: String,
             createdDate: String,
             updateDate: String,
             uninstall: Boolean,
             uuid: String) = PackageImportInstall(packageImportInstallId, tenantId, organizationId, isActive, created,
    createdBy, updated, updatedBy, None, None, None, None, None, None, None, processed, processing, None, None, None,
    None, None, uuid)
} 
Example 77
Source File: Menu.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class Menu(menuId: Int,
                tenantId : Int ,
                organizationId : Int,
                isActive: Boolean = true,
                created: DateTime =  DateTime.now,
                createdBy: Int,
                updated: DateTime =  DateTime.now,
                name: String,
                updatedBy: Int,
                description: Option[String],
                isSummary: Boolean = false,
                isSOTrx: Boolean = true,
                isReadOnly: Boolean = false,
                action: Option[Boolean],
                windowId: Option[Int],
                workFlowId: Option[Int],
                taskId: Option[Int],
                processId: Option[Int],
                formId: Option[Int],
                workbenchId: Option[Int],
                entityType: String = "D",
                isCentrallyMaintained: Boolean = true,
                browseId: Option[Int],
                uuid: String
               ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
    override type ActiveEnabled = this.type
    override type Identifiable = this.type
    override type Traceable = this.type

    override def Id: Int = menuId

    override val entityName: String = "AD_Menu"
    override val identifier: String = "AD_Menu_ID"
}

object Menu {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[Menu]
  def create(menuId: Int,
             tenantId : Int ,
             organizationId : Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             name: String,
             updatedBy: Int,
             description: String,
             isSummary: Boolean,
             isSOTrx: Boolean,
             isReadOnly: Boolean,
             action: Boolean,
             windowId: Int,
             workFlowId: Int,
             taskId: Int,
             processId:Int,
             formId: Int,
             workbenchId: Int,
             entityType: String,
             isCentrallyMaintained: Boolean,
             browseId: Int,
             uuid: String) = Menu (menuId, tenantId, organizationId, isActive, created, createdBy, updated,
    name, updatedBy,None, isSummary, isSOTrx, isReadOnly, None, None, None, None, None, None,
    None, entityType, isCentrallyMaintained, None, uuid)
} 
Example 78
Source File: WorkflowResponsible.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class WorkflowResponsible(workflowResponsibleId: Int,
                               tenantId: Int,
                               organizationId: Int,
                               isActive: Boolean = true,
                               created: DateTime = DateTime.now,
                               createdBy: Int,
                               updated: DateTime = DateTime.now,
                               updatedBy: Int,
                               name: String,
                               description: Option[String],
                               responsibleType: Boolean,
                               userId: Option[Int],
                               roleId: Option[Int],
                               entityType: String = "D",
                               uuid: String
                              ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = workflowResponsibleId

  override val entityName: String = "AD_Wf_Responsible"
  override val identifier: String = "AD_Wf_Responsible_ID"
}

object WorkflowResponsible {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[WorkflowResponsible]
  def create(workflowResponsibleId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             name: String,
             description: String,
             responsibleType: Boolean,
             userId: Int,
             roleId: Int,
             entityType: String,
             uuid: String) = WorkflowResponsible(workflowResponsibleId, tenantId, organizationId, isActive, created,
    createdBy, updated, updatedBy, name, None, responsibleType, None, None, entityType, uuid)
} 
Example 79
Source File: WorkflowProcessorLog.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime


case class WorkflowProcessorLog(workflowProcessorLogId: Int,
                                workflowProcessorId: Int,
                                tenantId: Int,
                                organizationId : Int ,
                                isActive: Boolean = true,
                                created: DateTime = DateTime.now,
                                createdBy: Int,
                                updated: DateTime = DateTime.now,
                                updatedBy: Int,
                                isError: Boolean = false,
                                summary: Option[String],
                                reference: Option[String],
                                description: Option[String],
                                textMsg: Option[String],
                                binaryDate: Option[String],
                                uuid: String
                                ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type
  override def Id: Int = workflowProcessorLogId

  override val entityName: String = "AD_WorkflowProcessorLog"
  override val identifier: String = "AD_WorkflowProcessorLog_ID"

}

object WorkflowProcessorLog {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[WorkflowProcessorLog]
  def create(workflowProcessorLogId: Int,
             workflowProcessorId: Int,
             tenantId: Int,
             organizationId : Int ,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             isError: Boolean,
             summary: String,
             reference: String,
             description: String,
             textMsg: String,
             binaryDate: String,
             uuid: String) = WorkflowProcessorLog(workflowProcessorLogId, workflowProcessorId, tenantId, organizationId,
    isActive, created, createdBy, updated, updatedBy, isError, None, None, None, None, None, uuid)
} 
Example 80
Source File: SysConfig.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime


case class SysConfig (sysConfigId: Int,
                      tenantId: Int,
                      organizationId: Int,
                      created: DateTime = DateTime.now,
                      createdBy: Int,
                      updated: DateTime = DateTime.now,
                      updatedBy: Int,
                      isActive: Boolean = true,
                      name: String,
                      value: String,
                      description: Option[String],
                      entityType: String = "U",
                      configurationLevel: String = "S",
                      uuid: String
                     ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = sysConfigId

  override val entityName: String = "AD_SysConfig"
  override val identifier: String = "AD_SysConfig_ID"

}

object SysConfig {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[SysConfig]
  def create(sysConfigId: Int,
             tenantId: Int,
             organizationId: Int,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             isActive: Boolean,
             name: String,
             value: String,
             description: String,
             entityType: String,
             configurationLevel: String,
             uuid: String) = SysConfig(sysConfigId, tenantId, organizationId, created, createdBy, updated,
    updatedBy, isActive, name, value, None, entityType, configurationLevel, uuid)
} 
Example 81
Source File: ViewAttributeTrl.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class ViewAttributeTrl(tenantId: Int,
                            organizationId: Int,
                            created: DateTime = DateTime.now,
                            createdBy: Int,
                            isActive: Boolean,
                            updated: DateTime = DateTime.now,
                            updatedBy: Int,
                            viewAttributeId: Int,
                            language: String,
                            description: Option[String],
                            help: Option[String],
                            isTranslated: Boolean,
                            uuid: String
                        ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = viewAttributeId

  override val entityName: String = "AD_View_Column_Trl"
  override val identifier: String = null
}

object ViewAttributeTrl  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[ViewAttributeTrl]
  def create(tenantId: Int,
             organizationId: Int,
             created: DateTime,
             createdBy: Int,
             isActive: Boolean,
             updated: DateTime,
             updatedBy: Int,
             viewAttributeId: Int,
             language: String,
             description: String,
             help: String,
             isTranslated: Boolean,
             uuid: String) = ViewAttributeTrl(tenantId, organizationId, created, createdBy, isActive, updated, updatedBy,
    viewAttributeId, language, None, None, isTranslated, uuid)
} 
Example 82
Source File: Preference.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class Preference (preferenceId: Int,
                       tenantId: Int,
                       organizationId: Int,
                       isActive: Boolean = true,
                       created: DateTime = DateTime.now,
                       createdBy: Int,
                       updated: DateTime = DateTime.now,
                       updatedBy: Int,
                       windowId: Option[Int],
                       userId: Option[Int],
                       attribute: String,
                       value: String,
                       uuid: String
                      ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type
  override def Id: Int = preferenceId

  override val entityName: String = "AD_Preference"
  override val identifier: String = "AD_Preference_ID"

}

object Preference {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[Preference]
  def create(preferenceId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             windowId: Int,
             userId: Int,
             attribute: String,
             value: String,
             uuid: String) = Preference(preferenceId, tenantId, organizationId, isActive, created, createdBy, updated,
    updatedBy, None, None, attribute, value, uuid)
} 
Example 83
Source File: TreeFavoriteNode.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class TreeFavoriteNode(treeFavoriteNodeId: Int,
                            tenantId: Int,
                            organizationId: Int,
                            menuId: Int,
                            treeFavoriteId: Int,
                            created: DateTime = DateTime.now,
                            createdBy: Int,
                            isActive: Boolean = true,
                            isSummary: Boolean,
                            nodeName: Option[String],
                            parentId: Option[Int],
                            seqNo: Int,
                            updated: DateTime = DateTime.now,
                            updatedBy: Int,
                            isCollapsible: Boolean = false,
                            uuid: String
                           ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = treeFavoriteNodeId

  override val entityName: String = "AD_Tree_Favorite_Node"
  override val identifier: String = "AD_Tree_Favorite_Node_ID"
}

object TreeFavoriteNode  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[TreeFavoriteNode]
  def create(treeFavoriteNodeId: Int,
             tenantId: Int,
             organizationId: Int,
             menuId: Int,
             treeFavoriteId: Int,
             created: DateTime,
             createdBy: Int,
             isActive: Boolean,
             isSummary: Boolean,
             nodeName: String,
             parentId: Int,
             seqNo: Int,
             updated: DateTime,
             updatedBy: Int,
             isCollapsible: Boolean,
             uuid: String) = TreeFavoriteNode(treeFavoriteId, tenantId, organizationId, menuId, treeFavoriteId,
    created, createdBy, isActive, isSummary, None, None, seqNo, updated, updatedBy, isCollapsible, uuid)
} 
Example 84
Source File: AlertProcessorLog.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class AlertProcessorLog(alertProcessorLogId: Int,
                             alertProcessorId: Int,
                             tenantId: Int,
                             organizationId: Int,
                             isActive: Boolean = true,
                             created: DateTime = DateTime.now(),
                             createdBy: Int,
                             updated: DateTime = DateTime.now(),
                             updatedBy: Int,
                             isError: Boolean = false,
                             summary: Option[String],
                             reference: Option[String],
                             description: Option[String],
                             textMsg: Option[String],
                             binaryData: Option[String],
                             uuid: String
                            ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = alertProcessorLogId

  override val entityName: String = "AD_AlertProcessorLog"
  override val identifier: String = "AD_AlertProcessorLog_ID"
}

object AlertProcessorLog  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[AlertProcessorLog]
  def create(alertProcessorLogId: Int,
             alertProcessorId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             isError: Boolean,
             summary: String,
             reference: String,
             description: String,
             textMsg:String,
             binaryData: String,
             uuid: String) = AlertProcessorLog(alertProcessorLogId, alertProcessorId, tenantId, organizationId,
    isActive, created, createdBy, updated, updatedBy, isError, None, None, None, None, None, uuid)
} 
Example 85
Source File: AlertRule.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class AlertRule(alertRuleId: Int,
                     tenantId: Int,
                     organizationId: Int,
                     isActive: Boolean = true,
                     created: DateTime = DateTime.now,
                     createdBy: Int,
                     updated: DateTime = DateTime.now,
                     updatedBy: Int,
                     name: String,
                     alertId: Int,
                     selectClause: String,
                     fromClause: String,
                     whereClause: Option[String],
                     entityId: Option[Int],
                     preProcessing: Option[String],
                     postProcessing: Option[String],
                     isValid: Boolean = true,
                     errorMsg: Option[String],
                     otherClause: Option[String],
                     uuid: String
                    ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = alertRuleId

  override val entityName: String = "AD_AlertRule"
  override val identifier: String = "AD_AlertRule_ID"
}

object AlertRule  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[AlertRule]
  def create(alertRuleId: Int,
             tenantId: Int,
             organizationId: Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             name: String,
             alertId: Int,
             selectClause: String,
             fromClause: String,
             whereClause: String,
             entityId: Int,
             preProcessing: String,
             postProcessing: String,
             isValid: Boolean,
             errorMsg:String,
             otherClause: String,
             uuid: String) = AlertRule(alertId, tenantId, organizationId, isActive, created, createdBy, updated,
    updatedBy, name, alertId, selectClause, fromClause, None, None, None, None, isValid, None, None, uuid)
} 
Example 86
Source File: FormAccess.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime


case class FormAccess(formId : Int,
                      roleId : Int,
                      tenantId : Int ,
                      organizationId : Int ,
                      isActive : Boolean = true,
                      created : DateTime = DateTime.now,
                      createdBy : Int ,
                      updated : DateTime = DateTime.now,
                      updatedBy : Int ,
                      isReadWrite : Boolean = true,
                      uuid: String
                     ) extends DomainModel


  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = formId

  override val entityName: String = "AD_Form_Access"
  override val identifier: String = null
}

object FormAccess  {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[FormAccess]
  def create(formId : Int,
             roleId : Int,
             tenantId : Int ,
             organizationId : Int ,
             isActive : Boolean ,
             created : DateTime ,
             createdBy : Int ,
             updated : DateTime,
             updatedBy : Int,
             isReadWrite : Boolean,
             uuid: String) = FormAccess(formId, roleId, tenantId, organizationId, isActive, created, createdBy,
    updated, updatedBy, isReadWrite, uuid)
} 
Example 87
Source File: FormTrl.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.domain.model

import ai.x.play.json.Jsonx
import com.eevolution.context.dictionary.api.{ActiveEnabled, DomainModel, Identifiable, Traceable}
import org.joda.time.DateTime



case class FormTrl(formId: Int,
                   language: String,
                   tenantId : Int ,
                   organizationId : Int,
                   isActive: Boolean = true,
                   created: DateTime = DateTime.now,
                   createdBy: Int,
                   updated: DateTime = DateTime.now,
                   updatedBy: Int,
                   name: String,
                   description: Option[String],
                   help: Option[String],
                   isTranslated: Boolean = false,
                   uuid: String
                  ) extends DomainModel

  with ActiveEnabled
  with Identifiable
  with Traceable {
  override type ActiveEnabled = this.type
  override type Identifiable = this.type
  override type Traceable = this.type

  override def Id: Int = formId

  override val entityName: String = "AD_Form_Trl"
  override val identifier: String = null
}

object FormTrl {
  implicit lazy val jsonFormat = Jsonx.formatCaseClass[FormTrl]
  def create(formId: Int,
             language: String,
             tenantId : Int ,
             organizationId : Int,
             isActive: Boolean,
             created: DateTime,
             createdBy: Int,
             updated: DateTime,
             updatedBy: Int,
             name: String,
             description: String,
             help: String,
             isTranslated: Boolean,
             uuid: String) = FormTrl(formId, language, tenantId, organizationId, isActive, created, createdBy, updated,
    updatedBy, name, None, None, isTranslated, uuid)
} 
Example 88
Source File: ContactsBooksService.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.contacts.services

import cats.instances.all._
import com.dataengi.crm.contacts.models.ContactsBook
import com.dataengi.crm.contacts.repositories.ContactsBooksRepository
import com.google.inject.{Inject, Singleton}
import com.dataengi.crm.common.context.types._
import org.joda.time.DateTime

import scala.concurrent.ExecutionContext

trait ContactsBooksService {

  def update(value: ContactsBook): EmptyOr

  def get(id: Long): Or[ContactsBook]

  def findByOwner(userId: Long): Or[ContactsBook]

  def create(userId: Long): Or[ContactsBook]

}

@Singleton
class ContactsBooksServiceImplementation @Inject()(contactsBookRepository: ContactsBooksRepository,
                                                   implicit val executionContext: ExecutionContext)
    extends ContactsBooksService {

  override def findByOwner(userId: Long): Or[ContactsBook] =
    for {
      contactsBookOpt <- contactsBookRepository.findByOwner(userId)
      contactsBook    <- getOrCreate(contactsBookOpt, userId)
    } yield contactsBook

  override def create(userId: Long): Or[ContactsBook] = {
    val contactsBook = ContactsBook(ownerId = userId, createDate = DateTime.now().getMillis)
    contactsBookRepository.add(contactsBook).map(id => contactsBook.copy(id = Some(id)))
  }

  private def getOrCreate(contactBookOption: Option[ContactsBook], userId: Long) = contactBookOption match {
    case Some(contactsBook) => contactsBook.toOr
    case None               => create(userId)
  }

  override def get(id: Long): Or[ContactsBook] =
    for {
      contactsBook <- contactsBookRepository.get(id)
    } yield contactsBook

  override def update(contact: ContactsBook): EmptyOr = contactsBookRepository.update(contact.id.get, contact)

} 
Example 89
Source File: ContactsDAOContext.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.contacts.daos.context

import com.dataengi.crm.contacts.daos._
import com.dataengi.crm.contacts.models._
import com.dataengi.crm.contacts.context.ContactsServiceContext
import com.dataengi.crm.identities.daos.UsersDAO
import org.joda.time.DateTime

trait ContactsDAOContext extends ContactsServiceContext {

  lazy val contactsDAO      = application.injector.instanceOf[ContactsSlickDAO]
  lazy val contactsBooksDAO = application.injector.instanceOf[ContactsBooksDAO]
  lazy val groupsDAO        = application.injector.instanceOf[GroupsDAO]
  lazy val usersDAO         = application.injector.instanceOf[UsersDAO]

  val testContactFullWithoutRealIds = Contact(
    name = "TestContact",
    contactsBookId = 1, //change to real id
    createDate = new DateTime().getMillis,
    emails = List(Email(ContactFieldTypes.Home, "[email protected]"), Email(ContactFieldTypes.Work, "[email protected]")),
    groupIds = List(), //fill with real ids
    phones = List(Phone(ContactFieldTypes.Home, "10203040"), Phone(ContactFieldTypes.Work, "40302010")),
    skypeId = Some("TestSkypeId"),
    fax = Some("TestFax"),
    company = Some("IndusLogic"),
    jobPosition = Some("sr.Developer"),
    address = Some(Address(Some("Pushkina"), None, None, None, None)),
    timeZone = Some("UTC+2"),
    language = Some("Scala"),
    contactType = Some(ContactTypes.Client),
    note = Some("Test_note"))

} 
Example 90
Source File: ContactsBooksDAOSpec.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.contacts.daos

import com.dataengi.crm.common.context.CRMApplication
import com.dataengi.crm.contacts.models.ContactsBook
import org.joda.time.DateTime
import play.api.test.PlaySpecification
import com.dataengi.crm.common.extensions.awaits._
import com.dataengi.crm.common.context.types._
import org.specs2.runner.SpecificationsFinder

class ContactsBooksDAOSpec extends PlaySpecification with CRMApplication {

  sequential

  lazy val contactsBooksDAO: ContactsBooksDAO = application.injector.instanceOf[ContactsBooksDAO]

  val TestOwnerId = 0L

  lazy val TestContactsBook: ContactsBook = ContactsBook(TestOwnerId, new DateTime().getMillis)

  "ContactsBooksDAO" should {
    "add contacts book and get" in {
      val addContactsBookResult = contactsBooksDAO.add(TestContactsBook).await()
      addContactsBookResult.isRight === true
      val id                    = addContactsBookResult.value
      val getContactsBookResult = contactsBooksDAO.get(id).await()
      getContactsBookResult.isRight === true
      getContactsBookResult.value === TestContactsBook.copy(id = Some(id))
      val getContactsBookOptionResult = contactsBooksDAO.getOption(id).await()
      println(s"[contacts-books-dao][get-option] $getContactsBookOptionResult")
      getContactsBookOptionResult.isRight === true
      getContactsBookOptionResult.value === Some(TestContactsBook.copy(id = Some(id)))
      val getContactsBookByOwnerIdResult = contactsBooksDAO.getByOwnerId(TestOwnerId).await()
      getContactsBookByOwnerIdResult.isRight === true
    }

    "add and delete" in {
      val addContactsBookResult = contactsBooksDAO.add(TestContactsBook).await()
      addContactsBookResult.isRight === true
      val id                    = addContactsBookResult.value
      val getContactsBookResult = contactsBooksDAO.get(id).await()
      getContactsBookResult.isRight === true
      getContactsBookResult.value === TestContactsBook.copy(id = Some(id))
      val deleteContactsBookResult = contactsBooksDAO.delete(id).await()
      deleteContactsBookResult.isRight === true
    }

    "add and update" in {
      val addContactsBookResult = contactsBooksDAO.add(TestContactsBook).await()
      addContactsBookResult.isRight === true
      val id                    = addContactsBookResult.value
      val getContactsBookResult = contactsBooksDAO.get(id).await()
      getContactsBookResult.isRight === true
      getContactsBookResult.value === TestContactsBook.copy(id = Some(id))
      val updatedContactsBook      = TestContactsBook.copy(id = Some(id), createDate = new DateTime().getMillis)
      val updateContactsBookResult = contactsBooksDAO.update(updatedContactsBook).await()
      updateContactsBookResult.isRight === true
      val getUpdatedContactsBookResult = contactsBooksDAO.get(id).await()
      getUpdatedContactsBookResult.isRight === true
      getUpdatedContactsBookResult.value === updatedContactsBook
    }

  }

} 
Example 91
Source File: IdentitiesArbitrary.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.identities.arbitraries

import java.util.UUID
import java.util.concurrent.TimeUnit

import com.mohiva.play.silhouette.api.LoginInfo
import com.mohiva.play.silhouette.impl.authenticators.JWTAuthenticator
import com.dataengi.crm.common.arbitraries.CommonArbitrary
import com.dataengi.crm.identities.models.Actions.Action
import com.dataengi.crm.identities.models.InviteStatuses.InviteStatus
import com.dataengi.crm.identities.models._
import com.dataengi.crm.identities.models.PermissionStates.PermissionState
import com.mohiva.play.silhouette.api.util.PasswordInfo
import org.joda.time.DateTime
import org.scalacheck.{Arbitrary, Gen}
import play.api.libs.json.Json

import scala.concurrent.duration.FiniteDuration

trait IdentitiesArbitrary extends CommonArbitrary {

  lazy val companyArbitrary: Arbitrary[Company] = Arbitrary(Gen.resultOf(Company))

  implicit val actionArbitrary: Arbitrary[Action]                   = Arbitrary(Gen.oneOf(Actions.values.toList))
  implicit val permissionStateArbitrary: Arbitrary[PermissionState] = Arbitrary(Gen.oneOf(PermissionStates.values.toList))
  implicit val permissionArbitrary: Arbitrary[Permission]           = Arbitrary(Gen.resultOf(Permission))
  implicit val roleArbitrary: Arbitrary[Role]                       = Arbitrary(Gen.resultOf(Role))
  implicit val inviteStatusArbitrary: Arbitrary[InviteStatus]       = Arbitrary(Gen.oneOf(InviteStatuses.values.toList))
  implicit val uuidArbitrary: Arbitrary[UUID]                       = Arbitrary(Gen.uuid)
  implicit val inviteArbitrary: Arbitrary[Invite]                   = Arbitrary(Gen.resultOf(Invite))

  val dateTimeGen = for {
    value <- Gen.Choose.chooseLong.choose(0, Long.MaxValue)
  } yield new DateTime(value)

  val finiteDurationGen = for {
    value <- Gen.Choose.chooseLong.choose(0, Long.MaxValue)
  } yield new FiniteDuration(value, TimeUnit.NANOSECONDS)

  val jsObject = Gen.oneOf(List(Some(Json.obj("a" -> "b")), None))

  implicit val jsObjectArbitrary       = Arbitrary(jsObject)
  implicit val dateTimeArbitrary       = Arbitrary(dateTimeGen)
  implicit val finiteDurationArbitrary = Arbitrary(finiteDurationGen)
  implicit val loginInfoArbitrary      = Arbitrary(Gen.resultOf(LoginInfo))
  implicit val authenticatorArbitrary  = Arbitrary(Gen.resultOf(JWTAuthenticator.apply _))
  implicit val passwordInfoArbitrary   = Arbitrary(Gen.resultOf(PasswordInfo))
} 
Example 92
Source File: StreamingTSExample.scala    From spark-riak-connector   with Apache License 2.0 5 votes vote down vote up
package com.basho.riak.spark.examples.streaming

import java.util.UUID

import kafka.serializer.StringDecoder
import org.apache.spark.sql.Row
import org.apache.spark.streaming.Durations
import org.apache.spark.streaming.StreamingContext
import org.apache.spark.streaming.kafka.KafkaUtils
import org.apache.spark.{SparkConf, SparkContext}
import com.basho.riak.spark.streaming._
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat


object StreamingTSExample {
  def main(args: Array[String]): Unit = {

    val sparkConf = new SparkConf(true)
      .setAppName("Simple Spark Streaming to Riak TS Demo")

    setSparkOpt(sparkConf, "spark.master", "local")
    setSparkOpt(sparkConf, "spark.riak.connection.host", "127.0.0.1:8087")
    setSparkOpt(sparkConf, "kafka.broker", "127.0.0.1:9092")

    val sc = new SparkContext(sparkConf)
    val streamCtx = new StreamingContext(sc, Durations.seconds(15))

    val kafkaProps = Map[String, String](
      "metadata.broker.list" -> sparkConf.get("kafka.broker"),
      "client.id" -> UUID.randomUUID().toString
    )

    KafkaUtils.createDirectStream[String, String, StringDecoder, StringDecoder](streamCtx, kafkaProps, Set[String]("ingest-ts")
    ) map { case (key, value) =>
      val mapper = new ObjectMapper()
      mapper.registerModule(DefaultScalaModule)
      val wr = mapper.readValue(value, classOf[Map[String,String]])
      Row(
        wr("weather"),
        wr("family"),
        DateTime.parse(wr("time"),DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS")).getMillis,
        wr("temperature"),
        wr("humidity"),
        wr("pressure"))
    } saveToRiakTS "ts_weather_demo"

    streamCtx.start()
    println("Spark streaming context started. Spark UI could be found at http://SPARK_MASTER_HOST:4040")
    println("NOTE: if you're running job on the 'local' master open http://localhost:4040")
    streamCtx.awaitTermination()
  }


  private def setSparkOpt(sparkConf: SparkConf, option: String, defaultOptVal: String): SparkConf = {
    val optval = sparkConf.getOption(option).getOrElse(defaultOptVal)
    sparkConf.set(option, optval)
  }
} 
Example 93
Source File: Citizen.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.models.citizen

import org.joda.time.{DateTime, LocalDate}
import uk.gov.hmrc.domain.Nino
import play.api.libs.functional.syntax._
import play.api.libs.json._

case class Citizen(nino: Nino, firstName: Option[String] = None, lastName: Option[String] = None,
                   dateOfBirth: LocalDate) {
  def getNameFormatted: Option[String] = {
    (firstName, lastName) match {
      case (Some(firstName), Some(lastName)) => Some("%s %s".format(firstName, lastName))
      case _ => None
    }
  }
}

object Citizen {

  implicit val dateReads: Reads[LocalDate] = Reads[LocalDate] {
    case value: JsNumber => value.validate[Long].map(new LocalDate(_))
    case value => value.validate[String].map(LocalDate.parse)
  }

  implicit val formats = Json.format[Citizen]
} 
Example 94
Source File: PipeElement.scala    From sddf   with GNU General Public License v3.0 5 votes vote down vote up
package de.unihamburg.vsis.sddf.pipe

import org.joda.time.DateTime

import de.unihamburg.vsis.sddf.logging.Logging
import de.unihamburg.vsis.sddf.pipe.context.AbstractPipeContext
import de.unihamburg.vsis.sddf.visualisation.model.BasicAnalysable

trait PipeElement[A, B] extends Pipe[A, B] with Logging with Serializable {

  @transient var _prevStep: Option[Pipe[_, A]] = None
  def prevStep = _prevStep
  def prevStep_=(prevStep: Pipe[_, A]) = this._prevStep = Option(prevStep)

  @transient var _nextStep: Option[Pipe[B, _]] = None
  def nextStep = _nextStep
  def nextStep_=(nextStep: Pipe[B, _]) = this._nextStep = Option(nextStep)

  @transient val _analysable: BasicAnalysable = new BasicAnalysable
  def analysable = _analysable

  override def start(input: A)(implicit pipeContext: AbstractPipeContext): Unit = {
    analysable.name = this.name
    analysable.startTime = new DateTime
    this.output = step(input)
    analysable.endTime = new DateTime
    pipeContext.modelRouter.submitModel(analysable)
    if (nextStep.isDefined) {
      nextStep.get.start(this.output.get)
    }
  }
  
   
  override def run(input: A)(implicit pipeContext: AbstractPipeContext): B = {
    start(input)
    this.output.get
  }

  override def append[D](pipe: Pipe[B, D]): Pipeline[A, D] = {
    pipe match {
      case p: PipeElement[B, D] => {
        this.nextStep = pipe
        p.prevStep = this
        new Pipeline(this, p)
      }
      case p: Pipeline[B, D] => p.prepend(this)
      case _                 => throw new Exception("Unknown Pipe implementation!")
    }
  }

  override def prepend[D](pipe: Pipe[D, A]): Pipeline[D, B] = {
    pipe match {
      case p: PipeElement[D, A] => {
        this.prevStep = pipe
        p.nextStep = this
        new Pipeline(p, this)
      }
      case p: Pipeline[D, A] => p.append(this)
      case _                 => throw new Exception("Unknown Pipe implementation!")
    }

  }

} 
Example 95
Source File: LiigaJournalist.scala    From avoin-voitto   with MIT License 5 votes vote down vote up
package liigavoitto.journalist

import liigavoitto.journalist.author.AuthorGenerator
import liigavoitto.journalist.concepts.ConceptIdGenerator
import liigavoitto.journalist.events.GameEventsGenerator
import liigavoitto.journalist.stats.GameStatsTableGenerator
import liigavoitto.journalist.text.TextGenerator
import liigavoitto.journalist.title.TitleGenerator
import liigavoitto.scores.{LeagueTableEntry, Match, PlayerStatsEntry}
import liigavoitto.transform._
import liigavoitto.util.Logging
import org.joda.time.DateTime

case class MatchData(
                      mtch: Match,
                      seriesId: String,
                      season: String,
                      stage: String,
                      allHomeTeamMatches: List[Match] = List(),
                      allAwayTeamMatches: List[Match] = List(),
                      leagueTable: List[LeagueTableEntry] = List(),
                      playerStats: List[PlayerStatsEntry] = List()
                    )

object LiigaJournalist extends Logging with ArticlesV2Transformer {

  def createArticle(data: MatchData, language: String): Option[ArticleV2] = {
    val mtch = data.mtch
    if (mtch.status == "finished") {
      val id = mtch.id

      val title = new TitleGenerator(data, language).generateTitle.get
      val gen = new TextGenerator(data, language)
      val events = new GameEventsGenerator(data, language).getEventContentBlocks
      val gameStats = new GameStatsTableGenerator(data, language).getTable
      val concepts = new ConceptIdGenerator(data.seriesId, data.mtch).getIds
      val properties = List("importance:low")
      val author = Some(AuthorGenerator.getAuthor)

      Some(
        getV2Article(
          Article(
            id,
            title,
            gen.lead,
            gen.body,
            DateTime.now,
            List(),
            List(),
            events,
            gameStats,
            concepts,
            author,
            None,
            None,
            language,
            "Yle Urheilu",
            "national",
            None,
            properties,
            gen.shortSummary)
          )
        )
    } else None
  }
} 
Example 96
Source File: ArticlesApiV2Model.scala    From avoin-voitto   with MIT License 5 votes vote down vote up
package liigavoitto.transform

import org.joda.time.DateTime

case class Article(
  id: String,
  title: String,
  lead: String,
  body: List[String],
  datePublished: DateTime,
  escenicSections: List[EscenicSection],
  externalContent: List[ExternalContent],
  gameEvents: List[TextBlock],
  gameStats: List[ContentBlock],
  conceptIds: List[String] = List(),
  author: Option[liigavoitto.journalist.author.Author] = None,
  surveyLink: Option[String] = None,
  footNote: Option[String] = None,
  language: String = "fi",
  publisher: String = "Yle Urheilu",
  coverage: String = "national",
  dateModified: Option[DateTime] = None,
  properties: List[String] = List(),
  shortSummary: String)

case class ExternalContent(html: String, css: List[String], scripts: List[String], embedLocation: Option[String] = None)

case class ArticleV2(
  id: String,
  language: String,
  url: Url,
  headline: Headline,
  lead: String,
  publisher: Publisher,
  datePublished: String,
  dateContentModified: String,
  dateJsonModified: String,
  coverage: String,
  content: List[ContentBlock],
  subjects: List[Subject],
  mainMedia: List[ImageBlock],
  authors: Option[List[Author]],
  properties: List[String] = List(),
  shortSummary: String
)
case class Url(full: String, short: Option[String] = None)
case class Headline(full: String, image: Option[ImageBlock] = None)
case class Publisher(name: String)
case class Subject(id: String)
case class Author(`type`: String, id: String, name: String, organization: String, image: Option[ImageBlock])
case class EscenicSection(uniqueName: String, homeSection: Boolean, publication: String)

trait ContentBlock {
  val `type`: String
}
case class HeadingBlock(level: Int, text: String, `type`: String) extends ContentBlock
case class ImageBlock(id: String, aspect: Double, `type`: String, alt: Option[String] = None, url: Option[String] = None) extends ContentBlock
case class TextBlock(text: String, `type`: String) extends ContentBlock
case class ExternalContentV2(`type`: String, html: String, css: List[String] = List(), scripts: List[String] = List()) extends ContentBlock 
Example 97
Source File: ScoresFromFilesFetcher.scala    From avoin-voitto   with MIT License 5 votes vote down vote up
package liigavoitto.fetch

import liigavoitto.journalist.MatchData
import liigavoitto.scores.ScoresApiParser
import org.joda.time.DateTime

class ScoresFromFilesFetcher(matchId: String) extends ScoresApiParser {

  def getEnrichedMatchData: MatchData = {
    {
      val sport = matchFromJson(matchId)
      val series = sport.series.head
      val season = series.seasons.head
      val stage = season.stages.head
      val mtch = stage.matches.get.head
      for(
        allHomeTeamMatches <- matchesFromJson(mtch.teams.head.id, series.id, mtch.date);
        allAwayTeamMatches <- matchesFromJson(mtch.teams(1).id, series.id, mtch.date);
        leagueTable <- leagueTableFromJson(series.id);
        playerStats <- playerStatsFromJson(series.id)
      ) yield MatchData(mtch, series.id, season.id, stage.id, allHomeTeamMatches, allAwayTeamMatches, leagueTable, playerStats)
    }.get
  }


  def matchFromJson(matchId: String) = {
    val json = scala.io.Source.fromFile(s"data/matches/$matchId.json", "utf8").mkString
    parseMatchSport(json).get
  }

  def matchesFromJson(teamId: String, seriesId: String, toDate: DateTime) = {
    val json = scala.io.Source.fromFile(s"data/$seriesId/team-histories/$teamId.json", "utf8").mkString
    parseMatchList(json).map(p => p.filter(m => toDate.getMillis >= m.date.getMillis))
  }

  def leagueTableFromJson(seriesId: String) = {
    val json = scala.io.Source.fromFile(s"data/$seriesId/league.json", "utf8").mkString
    parseLeagueTable(json)
  }

  def playerStatsFromJson(seriesId: String) = {
    val json = scala.io.Source.fromFile(s"data/$seriesId/player.json", "utf8").mkString
    parsePlayerStats(json)
  }

} 
Example 98
Source File: ScoresApiParser.scala    From avoin-voitto   with MIT License 5 votes vote down vote up
package liigavoitto.scores

import org.joda.time.DateTime
import org.json4s.DefaultFormats
import org.json4s.jackson.JsonMethods._
import liigavoitto.util.{ DateTimeNoMillisSerializer, Logging }

import scala.util.{ Failure, Success, Try }

case class Data(data: List[Sport])
case class Sport(id: String, series: List[Series])
case class Series(id: String, seasons: List[Season])
case class Season(id: String, stages: List[Stage])
case class Stage(id: String, matches: Option[List[Match]],
  standing: Option[List[LeagueTableEntry]],
  playerStatistics: Option[List[PlayerStatsEntry]])

case class Match(id: String, name: String, date: DateTime, status: String, teams: List[Team], feed: List[Feed] = List(), stats: GeneralMatchStats)
case class Feed(`type`: String, gameTime: Option[String], period: Option[String], player: Option[FeedPlayer], standing: Option[String], team: Option[Team], goalType: Option[String], saves: Option[String], timeInMins: Option[String], text: Option[String], beginTime: Option[String], endTime: Option[String])
case class FeedPlayer(id: String, name: PlayerName, meta: Option[PlayerMeta])
case class Team(id: String, name: String, abbr: String, meta: Meta, score: Option[Score], players: List[Player])
case class Score(now: Int, periods: List[Period], outcome: Outcome)
case class Period(id: String, score: Int)
case class Meta(images: List[Image], directives: Option[Map[String, Any]])
case class Image(id: String, imageType: String)
case class Outcome(wins: Int, draws: Int, losses: Int, otWins: Int, otLosses: Int)

case class Player(id: String, name: PlayerName, position: Option[String], specific: Map[String, Any], meta: Option[PlayerMeta])
case class PlayerName(first: String, last: String)
case class PlayerMeta(gender: Option[String] = None, country: Option[String] = None, tags: List[String] = Nil, directives: Map[String, String] = Map.empty)

case class LeagueTableEntry(
  team: Team,
  home: Option[LeagueTableResult] = None,
  away: Option[LeagueTableResult] = None,
  total: Option[LeagueTableResult] = None,
  specific: Option[Map[String, Any]] = None
)
case class LeagueTableResult(gamesPlayed: Int, outcome: Outcome, goals: Goals, points: Option[Int] = None, specific: Option[Map[String, Any]] = None)
case class Goals(score: Int, conceded: Int)

case class PlayerStatsEntry(player: PlayerStatsPlayer, teamStats: List[PlayerTeamStatsEntry])
case class PlayerTeamStatsEntry(team: Team, points: Int, goals: Int, assists: Int)
case class PlayerStatsPlayer(id: String, name: PlayerName)

case class GeneralMatchStats(attendance: Int)

trait ScoresApiParser extends Logging {
  implicit val formats = DefaultFormats + DateTimeNoMillisSerializer

  def parseMatchSport(json: String): Option[Sport] = extractData(json).map(_.head)
  def parseMatchList(json: String): Option[List[Match]] = extractData(json) match {
    case Some(sports) => if (sports.nonEmpty) Some(extractMatchesFromSport(sports.head).get) else Some(List())
    case None => None
  }
  def parseLeagueTable(json: String): Option[List[LeagueTableEntry]] = {
    extractData(json) match {
      case Some(sports) => if (sports.nonEmpty) Some(extractLeagueTableFromSport(sports.head).get) else Some(List())
      case None => None
    }
  }
  def parsePlayerStats(json: String): Option[List[PlayerStatsEntry]] = {
    extractData(json) match {
      case Some(sports) =>
        if (sports.nonEmpty)
          Some(extractPlayerStatsFromSport(sports.head).get)
        else Some(List())
      case None => None
    }
  }

  protected def extractMatchesFromSport(sport: Sport) = sport.series.head.seasons.head.stages.head.matches
  protected def extractLeagueTableFromSport(sport: Sport) = sport.series.head.seasons.head.stages.head.standing
  protected def extractPlayerStatsFromSport(sport: Sport) = sport.series.head.seasons.head.stages.head.playerStatistics
  protected def extractData(json: String) = {
    Try {
      log.debug(s"Sport JSON: $json")
      parse(json).extract[Data]
    } match {
      case Success(s) => Some(s.data)
      case Failure(e) =>
        log.info(s"Failed to parse '$json': " + e)
        None
    }
  }
} 
Example 99
Source File: TimeFormat.scala    From flint   with Apache License 2.0 5 votes vote down vote up
package com.twosigma.flint.timeseries.time

import java.util.concurrent.TimeUnit

import org.joda.time.format.{ DateTimeFormat, DateTimeFormatter, ISODateTimeFormat }
import org.joda.time.{ DateTime, DateTimeZone }

import scala.concurrent.duration.TimeUnit
import scala.util.Try

object TimeFormat {

  
  protected[flint] def parseNano(text: String, timeZone: DateTimeZone = DateTimeZone.UTC): Long =
    parse(text, timeZone, timeUnit = TimeUnit.NANOSECONDS)

  private val formatters: List[DateTimeFormatter] = List(
    // Double `HH` formatter
    DateTimeFormat.forPattern("yyyyMMdd HH:mm:ss.SSS Z"),
    DateTimeFormat.forPattern("yyyyMMdd HH:mm:ss Z"),
    DateTimeFormat.forPattern("yyyyMMdd HH:mm Z"),
    DateTimeFormat.forPattern("yyyyMMdd HH:mm:ss.SSS"),
    DateTimeFormat.forPattern("yyyyMMdd HH:mm:ss"),
    DateTimeFormat.forPattern("yyyyMMdd HH:mm"),
    DateTimeFormat.forPattern("yyyyMMdd"),
    DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS Z"),
    DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss Z"),
    DateTimeFormat.forPattern("yyyy-MM-dd HH:mm Z"),
    DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS"),
    DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"),
    DateTimeFormat.forPattern("yyyy-MM-dd HH:mm"),
    DateTimeFormat.forPattern("yyyy-MM-dd"),
    // Single `H` formatter
    DateTimeFormat.forPattern("yyyyMMdd H:mm:ss.SSS"),
    DateTimeFormat.forPattern("yyyyMMdd H:mm:ss.SSS Z"),
    DateTimeFormat.forPattern("yyyy-MM-dd H:mm:ss.SSS"),
    DateTimeFormat.forPattern("yyyy-MM-dd H:mm:ss.SSS Z"),

    // ISO DateTime
    ISODateTimeFormat.dateTimeParser()
  )
} 
Example 100
Source File: StreamingExample.scala    From reactiveinflux-spark   with Apache License 2.0 5 votes vote down vote up
package com.pygmalios.reactiveinflux.spark.examples

import com.pygmalios.reactiveinflux._
import com.pygmalios.reactiveinflux.spark._
import org.apache.spark.SparkConf
import org.apache.spark.rdd.RDD
import org.apache.spark.streaming.dstream.DStream
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.joda.time.DateTime

import scala.concurrent.duration._


object StreamingExample extends App {
  val conf = new SparkConf()
    .setMaster("local[*]")
    .setAppName("Example")
  val ssc = new StreamingContext(conf, Seconds(1))

  val point1 = Point(
    time        = DateTime.now(),
    measurement = "measurement1",
    tags        = Map(
      "tagKey1" -> "tagValue1",
      "tagKey2" -> "tagValue2"),
    fields      = Map(
      "fieldKey1" -> "fieldValue1",
      "fieldKey2" -> 10.7)
  )

  // Provide settings for reactiveinflux
  implicit val params = ReactiveInfluxDbName("example")
  implicit val awaitAtMost = 1.second

  // Create DStream of Influx points
  val queue = new scala.collection.mutable.Queue[RDD[Point]]
  val queueStream: DStream[Point] = ssc.queueStream(queue)

  // Add single RDD with a single Influx point to the DStream
  queue.enqueue(ssc.sparkContext.parallelize(Seq(point1)))

  // Save DStream to Influx
  queueStream.saveToInflux()

  // Start Spark streaming
  ssc.start()
  ssc.awaitTermination()
} 
Example 101
Source File: Example.scala    From reactiveinflux-spark   with Apache License 2.0 5 votes vote down vote up
package com.pygmalios.reactiveinflux.spark.examples

import com.pygmalios.reactiveinflux._
import com.pygmalios.reactiveinflux.spark._
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.rdd.RDD
import org.joda.time.DateTime

import scala.concurrent.duration._


object Example extends App {
  val conf = new SparkConf()
    .setMaster("local[*]")
    .setAppName("Example")
  val sc = new SparkContext(conf)

  val point1 = Point(
    time        = DateTime.now(),
    measurement = "measurement1",
    tags        = Map(
      "tagKey1" -> "tagValue1",
      "tagKey2" -> "tagValue2"),
    fields      = Map(
      "fieldKey1" -> "fieldValue1",
      "fieldKey2" -> 10.7)
  )

  // Provide settings for reactiveinflux
  implicit val params = ReactiveInfluxDbName("example")
  implicit val awaitAtMost = 1.second

  // Create RDD with Influx point
  val rdd: RDD[Point] = sc.parallelize(Seq(point1))

  // Save RDD to Influx
  rdd.saveToInflux()

  // Stop Spark context
  sc.stop()
} 
Example 102
Source File: PointRDDExtensionsSpec.scala    From reactiveinflux-spark   with Apache License 2.0 5 votes vote down vote up
package com.pygmalios.reactiveinflux.extensions

import com.holdenkarau.spark.testing.SharedSparkContext
import com.pygmalios.reactiveinflux.Point.Measurement
import com.pygmalios.reactiveinflux._
import com.pygmalios.reactiveinflux.extensions.PointRDDExtensionsSpec._
import com.pygmalios.reactiveinflux.spark._
import com.pygmalios.reactiveinflux.spark.extensions.PointRDDExtensions
import org.joda.time.{DateTime, DateTimeZone}
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.{BeforeAndAfter, FlatSpec}

import scala.concurrent.duration._

@RunWith(classOf[JUnitRunner])
class PointRDDExtensionsSpec extends FlatSpec with SharedSparkContext
  with BeforeAndAfter {

  before {
    withInflux(_.create())
  }

  after {
    withInflux(_.drop())
  }

  behavior of "saveToInflux"

  it should "write single point to Influx" in {
    val points = List(point1)
    val rdd = sc.parallelize(points)

    // Execute
    rdd.saveToInflux()

    // Assert
    assert(PointRDDExtensions.totalBatchCount == 1)
    assert(PointRDDExtensions.totalPointCount == 1)
    val result = withInflux(
      _.query(Query(s"SELECT * FROM $measurement1"))
      .result
      .singleSeries)

    assert(result.rows.size == 1)

    val row = result.rows.head
    assert(row.time == point1.time)
    assert(row.values.size == 5)
  }

  it should "write 1000 points to Influx" in {
    val points = (1 to 1000).map { i =>
      Point(
        time = point1.time.plusMinutes(i),
        measurement = point1.measurement,
        tags = point1.tags,
        fields = point1.fields
      )
    }
    val rdd = sc.parallelize(points)

    // Execute
    rdd.saveToInflux()

    // Assert
    assert(PointRDDExtensions.totalBatchCount == 8)
    assert(PointRDDExtensions.totalPointCount == 1000)
    val result = withInflux(
      _.query(Query(s"SELECT * FROM $measurement1"))
        .result
        .singleSeries)

    assert(result.rows.size == 1000)
  }
}

object PointRDDExtensionsSpec {
  implicit val params: ReactiveInfluxDbName = ReactiveInfluxDbName("test")
  implicit val awaitAtMost: Duration = 1.second

  val measurement1: Measurement = "measurement1"
  val point1 = Point(
    time        = new DateTime(1983, 1, 10, 7, 43, 10, 3, DateTimeZone.UTC),
    measurement = measurement1,
    tags        = Map("tagKey1" -> "tagValue1", "tagKey2" -> "tagValue2"),
    fields      = Map("fieldKey1" -> StringFieldValue("fieldValue1"), "fieldKey2" -> BigDecimalFieldValue(10.7)))
} 
Example 103
Source File: model.scala    From sbt-org-policies   with Apache License 2.0 5 votes vote down vote up
package sbtorgpolicies.templates

import org.joda.time.DateTime
import sbtorgpolicies.rules.ValidationFunction
import sbtorgpolicies.templates.syntax._

import scala.util.matching.Regex

trait Replaceable {

  def asString: String
}

case class ReplaceableT[T](t: T) extends Replaceable {
  override def asString: String = t.toString
}

case class ReplaceableList[T](list: List[T]) extends Replaceable {
  override def asString: String =
    list.map(elem => s"* ${elem.asReplaceable.asString}").mkString("\n")
}

case class FileType(
    mandatory: Boolean,
    overWritable: Boolean,
    finalVersionOnly: Boolean,
    templatePath: String,
    outputPath: String,
    replacements: Replacements,
    fileSections: List[FileSection] = Nil,
    validations: List[ValidationFunction] = Nil
)

case class FileSection(
    appendPosition: AppendPosition,
    template: String,
    replacements: Replacements,
    shouldAppend: (String) => Boolean = _ => true
)

sealed trait AppendPosition
case object AppendAtTheBeginning    extends AppendPosition
case object AppendAtTheEnd          extends AppendPosition
case class AppendAfter(line: Regex) extends AppendPosition
case class ReplaceSection(
    from: Regex,
    to: Regex,
    insertIfNotFound: Boolean = true,
    defaultTop: Boolean = true
) extends AppendPosition

case class NewReleaseSection(date: DateTime, version: String, changes: String) 
Example 104
Source File: EventStatsServlet.scala    From spark-streaming-demo   with Apache License 2.0 5 votes vote down vote up
package com.datastax.examples.meetup

import org.joda.time.{DateTimeZone, DateTime, Duration}
import org.scalatra.scalate.ScalateSupport
import org.scalatra.{CorsSupport, ScalatraServlet}

import scala.concurrent.Await
import scala.concurrent.duration._
import org.json4s.{DefaultFormats, Formats}
import org.scalatra.json._

class EventStatsServlet() extends ScalatraServlet with CorsSupport with JacksonJsonSupport with ScalateSupport
{
  protected implicit val jsonFormats: Formats = DefaultFormats

  before() {
    contentType = formats("json")
  }

  options("/*"){
    response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
  }

  get("/trending") {
    val time = new DateTime(DateTimeZone.UTC)

    // Scan 5 second intervals within the past 1 minute.
    // Stop as soon as first successful found.
    val result = (for (i <- Stream range (0,12); v = getTrendingTopics(i, time); if v.nonEmpty) yield v).headOption

    // Order topics by count in desc order and take top 20
    result.map(r => r.toIndexedSeq.sortBy(_._2).reverse.take(20))
  }

  get("/countries") {
    val attendeesByCountry = Event.dimensions("attending", "ALL")

    Await.result(attendeesByCountry, 5 seconds)
      .map{ case (a,b) => Map("code" -> a.toUpperCase, "value" -> b)}
  }

  get("/") {
    contentType="text/html"
    layoutTemplate("dashboard.ssp")
  }

  def roundDateTime(t: DateTime, d: Duration) = {
    t minus (t.getMillis - (t.getMillis.toDouble / d.getMillis).round * d.getMillis)
  }

  def getTrendingTopics(i:Int, time:DateTime) = {
    val t = roundDateTime(time minusSeconds 5*i, Duration.standardSeconds(5))
    val trendingTopics = Event.dimensions("trending", "S" + t.toString("yyyyMMddHHmmss"))
    Await.result(trendingTopics, 5 seconds)
  }
} 
Example 105
Source File: ServiceMetaData.scala    From wookiee   with Apache License 2.0 5 votes vote down vote up
package com.webtrends.harness.service.meta

import com.webtrends.harness.utils.{Json, JsonSerializable}
import org.joda.time.DateTime

case class ServiceMetaData(name: String, version: String, loaded: DateTime,
                          path: String, akkaPath: String, jar: String,
                          supportsHttp: Boolean, dependencies: List[String]) extends JsonSerializable {
  override def toJson(): String = {
    val props = Map[String, Any](
      "name" -> name,
      "version" -> version,
      "loaded" -> loaded.toString,
      "path" -> path,
      "akkaPath" -> akkaPath,
      "jar" -> jar,
      "supportsHttp" -> supportsHttp,
      "dependencies" -> dependencies
    )
    Json.build(props).toString
  }
} 
Example 106
Source File: ApplicationHealth.scala    From wookiee   with Apache License 2.0 5 votes vote down vote up
package com.webtrends.harness.health

import ComponentState.ComponentState
import com.webtrends.harness.utils.{Json, JsonSerializable}
import org.joda.time.DateTime

import scala.collection.immutable.ListMap

case class ApplicationHealth(applicationName: String,
                             version: String,
                             time: DateTime,
                             state: ComponentState,
                             details: String,
                             components: Seq[HealthComponent]) extends JsonSerializable {
  override def toJson(): String = {
    val props = ListMap[String, Any](
      "applicationName" -> applicationName,
      "startedTime" -> time,
      "version" -> version,
      "state" -> state.toString,
      "details" -> details,
      "components" -> components
    )
    Json.build(props, sort = false).toString
  }
}

case class ComponentHealth(state: ComponentState, details: String) 
Example 107
Source File: HealthCheckProvider.scala    From wookiee   with Apache License 2.0 5 votes vote down vote up
package com.webtrends.harness.health

import java.util.jar.Attributes.Name
import java.util.jar.{Attributes, JarFile}

import akka.actor.Actor
import akka.pattern._
import akka.util.Timeout
import com.webtrends.harness.HarnessConstants
import com.webtrends.harness.logging.ActorLoggingAdapter
import com.webtrends.harness.service.messages.CheckHealth
import com.webtrends.harness.utils.ConfigUtil
import org.joda.time.DateTime

import scala.collection.mutable
import scala.concurrent.duration._
import scala.concurrent.{Future, Promise}
import scala.util.{Failure, Success}

trait HealthCheckProvider {
  this: Actor with ActorLoggingAdapter =>
  val upTime = DateTime.now
  implicit val timeout =
    ConfigUtil.getDefaultTimeout(context.system.settings.config, HarnessConstants.KeyDefaultTimeout, Timeout(15 seconds))

  val scalaVersion = util.Properties.versionString
  val file = getClass.getProtectionDomain.getCodeSource.getLocation.getFile

  val manifest = file match {
    case _ if file.endsWith(".jar") =>
      new JarFile(file).getManifest
    case _ =>
      val man = new java.util.jar.Manifest()
      man.getMainAttributes.put(Name.IMPLEMENTATION_TITLE, "Webtrends Harness Service")
      man.getMainAttributes.put(Name.IMPLEMENTATION_VERSION, "develop-SNAPSHOT")
      man.getMainAttributes.put(new Attributes.Name("Implementation-Build"), "N/A")
      man
  }

  val application = manifest.getMainAttributes.getValue(Name.IMPLEMENTATION_TITLE)
  val version = manifest.getMainAttributes.getValue(Name.IMPLEMENTATION_VERSION)
  val alerts: mutable.Buffer[ComponentHealth] = mutable.Buffer()

  
  def runChecks: Future[ApplicationHealth] = {

    import context.dispatcher

    // Ask for the health of each component
    val future = (context.actorSelection(HarnessConstants.ActorPrefix) ? CheckHealth).mapTo[Seq[HealthComponent]]
    val p = Promise[ApplicationHealth]

    future.onComplete({
      case Success(checks) =>
        // Rollup alerts for any critical or degraded components
        checks.foreach(checkComponents)
        // Rollup the statuses
        val overallHealth = rollupStatuses(alerts)
        alerts.clear()
        p success ApplicationHealth(application, version, upTime, overallHealth.state, overallHealth.details, checks)
      case Failure(e) =>
        log.error("An error occurred while fetching the health request results", e)
        p success ApplicationHealth(application, version, upTime, ComponentState.CRITICAL, e.getMessage, Nil)
    })

    p.future
  }
} 
Example 108
Source File: IngestorsEndpointSpec.scala    From hydra   with Apache License 2.0 5 votes vote down vote up
package hydra.ingest.http

import akka.actor.Actor
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.testkit.{TestActorRef, TestKit, TestProbe}
import hydra.common.util.ActorUtils
import hydra.ingest.IngestorInfo
import hydra.ingest.services.IngestorRegistry.{FindAll, FindByName, LookupResult}
import org.joda.time.DateTime
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

import scala.concurrent.duration._


class IngestorsEndpointSpec
    extends Matchers
    with AnyWordSpecLike
    with ScalatestRouteTest
    with HydraIngestJsonSupport {

  val ingestorsRoute = new IngestorRegistryEndpoint().route

  override def afterAll = {
    super.afterAll()
    TestKit.shutdownActorSystem(
      system,
      verifySystemShutdown = true,
      duration = 10 seconds
    )
  }

  val probe = TestProbe()

  val ingestorInfo = IngestorInfo(
    ActorUtils.actorName(probe.ref),
    "test",
    probe.ref.path,
    DateTime.now
  )

  val registry = TestActorRef(
    new Actor {

      override def receive = {
        case FindByName("tester") => sender ! LookupResult(Seq(ingestorInfo))
        case FindAll              => sender ! LookupResult(Seq(ingestorInfo))
      }
    },
    "ingestor_registry"
  ).underlyingActor

  "The ingestors endpoint" should {

    "returns all ingestors" in {
      Get("/ingestors") ~> ingestorsRoute ~> check {
        val r = responseAs[Seq[IngestorInfo]]
        r.size shouldBe 1
        r(0).path shouldBe ingestorInfo.path
        r(0).group shouldBe ingestorInfo.group
        r(0).path shouldBe ingestorInfo.path
        r(0).registeredAt shouldBe ingestorInfo.registeredAt.withMillisOfSecond(
          0
        )
      }
    }
  }
} 
Example 109
Source File: HydraIngestJsonSupportSpec.scala    From hydra   with Apache License 2.0 5 votes vote down vote up
package hydra.ingest.http

import akka.actor.ActorPath
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import hydra.core.HydraException
import hydra.core.ingest.IngestionReport
import hydra.core.protocol.{
  IngestorCompleted,
  IngestorError,
  IngestorStatus,
  InvalidRequest
}
import hydra.ingest.IngestorInfo
import org.joda.time.DateTime
import org.scalatest.matchers.should.Matchers
import org.scalatest.funspec.AnyFunSpecLike

class HydraIngestJsonSupportSpec
    extends Matchers
    with AnyFunSpecLike
    with HydraIngestJsonSupport
    with SprayJsonSupport {

  import spray.json._

  describe("Hydra Json Support") {
    it("converts IngestorInfo objects") {
      val time = DateTime.now
      val info = IngestorInfo(
        "test",
        "test",
        ActorPath.fromString("akka://hydra/test/ingestor"),
        time
      )
      val expectedValue =
        s"""{"name":"test","group":"test","path":"akka://hydra/test/ingestor",
          "registeredAt":${time.toJson}}""".parseJson
      info.toJson shouldBe expectedValue
    }

    it("converts IngestorStatus objects") {
      val st = InvalidRequest(new IllegalArgumentException("error"))
        .asInstanceOf[IngestorStatus]
      val stn = InvalidRequest(new IllegalArgumentException())
        .asInstanceOf[IngestorStatus]
      st.toJson shouldBe """{"code":400,"message":"error"}""".parseJson
      stn.toJson shouldBe """{"code":400,"message":"Unknown error."}""".parseJson
      intercept[NotImplementedError] {
        """{"code":400,"message":"error"}""".parseJson.convertTo[IngestorStatus]
      }
    }

    it("converts IngestorError objects with no message") {
      val st = IngestorError(new IllegalArgumentException("error"))
        .asInstanceOf[IngestorStatus]
      val stn = IngestorError(new IllegalArgumentException(""))
        .asInstanceOf[IngestorStatus]
      val stnCause = IngestorError(
        new HydraException("hydra", new IllegalArgumentException("underlying"))
      ).asInstanceOf[IngestorStatus]
      st.toJson shouldBe """{"code":503,"message":"error"}""".parseJson
      stn.toJson shouldBe """{"code":503,"message":""}""".parseJson
      stnCause.toJson shouldBe """{"code":503,"message":"hydra: underlying"}""".parseJson
    }

    it("converts IngestionReport objects") {
      val report =
        IngestionReport("a123", Map("testIngestor" -> IngestorCompleted), 200)
      val json = report.toJson.asJsObject.fields

      val pjson =
        """{"correlationId":"a123","ingestors":{"testIngestor":{"code":200,"message":"OK"}}}""".parseJson.asJsObject.fields

      json("correlationId") shouldBe pjson("correlationId")
      json("ingestors") shouldBe pjson("ingestors")

      intercept[NotImplementedError] {
        """{"correlationId":"1","ingestors":{"testIngestor":{"code":200,
          "message":"OK"}}}""".parseJson.convertTo[IngestionReport]
      }
    }

    it("converts IngestionReport without any ingestors") {
      val report = IngestionReport("1", Map.empty, 200)
      val json = report.toJson.asJsObject.fields

      val pjson =
        """{"correlationId":"1","ingestors":{}}""".parseJson.asJsObject.fields

      json("correlationId") shouldBe pjson("correlationId")
      json("ingestors") shouldBe pjson("ingestors")

    }
  }

} 
Example 110
Source File: TopicMetadataAdapterSpec.scala    From hydra   with Apache License 2.0 5 votes vote down vote up
package hydra.kafka

import java.util.UUID

import hydra.kafka.model.{TopicMetadata, TopicMetadataAdapter}
import org.joda.time.DateTime
import org.scalatest.matchers.should.Matchers
import org.scalatest.flatspec.AnyFlatSpecLike

class TopicMetadataAdapterSpec
    extends Matchers
    with AnyFlatSpecLike
    with TopicMetadataAdapter {

  "The TopicMetadataAdapter" should "build a resource" in {

    val uuid = UUID.randomUUID()

    val tm = TopicMetadata(
      id = uuid,
      schemaId = 1,
      streamType = "Notification",
      subject = "hydra-test",
      derived = false,
      deprecated = None,
      dataClassification = "public",
      contact = "alex",
      additionalDocumentation = None,
      notes = None,
      createdDate = DateTime.now
    )

    val resource = toResource(tm)
    val md = resource.asJsObject
    md.fields("_links")
      .asJsObject
      .fields("self")
      .asJsObject
      .fields("href")
      .convertTo[String] shouldBe s"/streams/${tm.subject}"
    md.fields("_links")
      .asJsObject
      .fields("hydra-schema")
      .asJsObject
      .fields("href")
      .convertTo[String] shouldBe "/schemas/hydra-test"
  }
} 
Example 111
Source File: BootstrapEndpointTestActors.scala    From hydra   with Apache License 2.0 5 votes vote down vote up
package hydra.kafka.endpoints

import java.util.UUID

import akka.actor.{ActorRef, Props}
import com.typesafe.config.Config
import hydra.avro.registry.ConfluentSchemaRegistry
import hydra.core.akka.SchemaRegistryActor
import hydra.kafka.model.TopicMetadata
import hydra.kafka.services.{StreamsManagerActor, TopicBootstrapActor}
import hydra.kafka.util.KafkaUtils
import io.confluent.kafka.schemaregistry.client.SchemaRegistryClient
import org.joda.time.DateTime

trait BootstrapEndpointTestActors extends BootstrapEndpointActors {

  class StreamsActorTest(
      bootstrapKafkaConfig: Config,
      bootstrapServers: String,
      schemaRegistryClient: SchemaRegistryClient
  ) extends StreamsManagerActor(
        bootstrapKafkaConfig,
        bootstrapServers,
        schemaRegistryClient
      ) {

    override val metadataMap: Map[String, TopicMetadata] =
      Map[String, TopicMetadata] {
        "exp.test-existing.v1.SubjectPreexisted" -> TopicMetadata(
          "exp.test-existing.v1.SubjectPreexisted",
          0,
          "",
          derived = false,
          None,
          "",
          "",
          None,
          None,
          UUID.randomUUID(),
          DateTime.now().minusSeconds(10)
        )
      }
  }

  object StreamsActorTest {

    def props(
        bootstrapKafkaConfig: Config,
        bootstrapServers: String,
        schemaRegistryClient: SchemaRegistryClient
    ) = {
      Props(
        new StreamsActorTest(
          bootstrapKafkaConfig,
          bootstrapServers,
          schemaRegistryClient
        )
      )
    }
  }

  private[kafka] val streamsManagerPropsTest = StreamsActorTest.props(
    bootstrapKafkaConfig,
    KafkaUtils.BootstrapServers,
    ConfluentSchemaRegistry.forConfig(applicationConfig).registryClient
  )

  override val bootstrapActor: ActorRef = system.actorOf(
    TopicBootstrapActor.props(
      schemaRegistryActor,
      kafkaIngestor,
      streamsManagerPropsTest,
      Some(bootstrapKafkaConfig)
    )
  )

} 
Example 112
Source File: DateUtilsSpec.scala    From hydra   with Apache License 2.0 5 votes vote down vote up
package hydra.common.util

import org.joda.time.format.{DateTimeFormat, ISODateTimeFormat}
import org.joda.time.{DateTime, DateTimeZone}
import org.scalatest.matchers.should.Matchers
import org.scalatest.funspec.AnyFunSpecLike


class DateUtilsSpec extends Matchers with AnyFunSpecLike {

  private val iso8601format = ISODateTimeFormat.dateTimeNoMillis()
  private val iso8601withMillis = ISODateTimeFormat.dateTime()

  import DateUtils._

  val now = DateTime.now()

  val f = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")
  val dt = f.parseDateTime("2017-01-10 23:13:26")

  describe("When using DateUtils") {
    it("converts to ISO format") {
      iso8601(now, false) shouldBe iso8601format.print(now)
      iso8601(now, true) shouldBe iso8601withMillis.print(now)
    }

    it("converts to UTC") {
      val dt = new DateTime(1234567000, DateTimeZone.UTC)
      dtFromUtcSeconds(1234567) shouldBe dt
      dtFromIso8601("1970-01-15T06:56:07Z") shouldBe dt
    }

    it("implicitly converts to the wrapper") {
      val dtw: DateTimeWrapper = dt
      dtw shouldBe DateTimeWrapper(dt)
    }

    it("sorts and compares dates") {
      val dtw: DateTimeWrapper = dt
      dtw.compare(now) should be < 0

      dtw.compare(now, dt) should be > 0

      Seq(now, dt).sorted shouldBe Seq(dt, now)
    }
  }

} 
Example 113
Source File: HydraJsonSupport.scala    From hydra   with Apache License 2.0 5 votes vote down vote up
package hydra.core.marshallers

import java.io.{PrintWriter, StringWriter}
import java.util.UUID

import akka.actor.ActorPath
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.StatusCode
import hydra.common.util.Resource._
import org.joda.time.DateTime
import org.joda.time.format.ISODateTimeFormat
import spray.json.{JsString, _}

import scala.util.{Failure, Success, Try}


  implicit def tryWriter[R: JsonWriter]: RootJsonWriter[Try[R]] =
    new RootJsonWriter[Try[R]] {

      override def write(responseTry: Try[R]): JsValue = {
        responseTry match {
          case Success(r) => JsObject("success" -> r.toJson)
          case Failure(t) => JsObject("failure" -> t.toJson)
        }
      }
    }

  implicit object StreamTypeFormat extends RootJsonFormat[StreamType] {

    def read(json: JsValue): StreamType = json match {
      case JsString("Notification") => Notification
      case JsString("History")      => History
      case JsString("CurrentState") => CurrentState
      case JsString("Telemetry")    => Telemetry
      case _ => {
        import scala.reflect.runtime.{universe => ru}
        val tpe = ru.typeOf[StreamType]
        val clazz = tpe.typeSymbol.asClass
        throw new DeserializationException(
          s"expected a streamType of ${clazz.knownDirectSubclasses}, but got $json"
        )
      }
    }

    def write(obj: StreamType): JsValue = {
      JsString(obj.toString)
    }
  }

  implicit val genericErrorFormat = jsonFormat2(GenericError)

  implicit val topicCreationMetadataFormat = jsonFormat8(TopicMetadataRequest)

  implicit val genericSchemaFormat = jsonFormat2(GenericSchema)

}

case class GenericError(status: Int, errorMessage: String)

case class TopicMetadataRequest(
    schema: JsObject,
    streamType: StreamType,
    derived: Boolean,
    deprecated: Option[Boolean],
    dataClassification: String,
    contact: String,
    additionalDocumentation: Option[String],
    notes: Option[String]
)

case class GenericSchema(name: String, namespace: String) {
  def subject = s"$namespace.$name"
}

sealed trait StreamType
case object Notification extends StreamType
case object CurrentState extends StreamType
case object History extends StreamType
case object Telemetry extends StreamType 
Example 114
Source File: MiscSpec.scala    From hydra   with Apache License 2.0 5 votes vote down vote up
package hydra.core

import hydra.core.ingest.HydraRequest
import hydra.core.protocol._
import org.joda.time.DateTime
import org.scalatest.matchers.should.Matchers
import org.scalatest.flatspec.AnyFlatSpecLike

import scala.concurrent.duration._

class MiscSpec extends Matchers with AnyFlatSpecLike {
  "The Hydra Exception " should "be instantiated without a cause" in {
    val ex = new HydraException("error")
    ex.getCause shouldBe null
  }

  "The IngestionTimedOutException" should "have correct values" in {
    val req = HydraRequest("123", "test")
    val ex = new IngestionTimedOut(req, DateTime.now(), 1.second, "test")
    ex.statusCode shouldBe 408
    ex.cause shouldBe an[IngestionTimedOutException]
  }

  "The IngestorUnavailable error" should "have correct values" in {
    val req = HydraRequest("123", "test")
    val err = IngestorUnavailable("test", new IllegalArgumentException, req)
    err.cause shouldBe an[IllegalArgumentException]
    err.statusCode shouldBe 503
  }

  "The InvalidRequest" should "have correct values" in {
    val err = InvalidRequest(new IllegalArgumentException("error"))
    err.cause shouldBe an[IllegalArgumentException]
    err.statusCode.intValue shouldBe 400
    err.completed shouldBe true
    err.message shouldBe "error"

    val err1 = InvalidRequest(new IllegalArgumentException)
    err1.message shouldBe "Unknown error."
  }

  "The InvalidRequestError" should "have correct values" in {
    val req = HydraRequest("123", "test")
    val err = InvalidRequestError(
      "test",
      req,
      DateTime.now,
      new IllegalArgumentException
    )
    err.statusCode shouldBe 400
  }
} 
Example 115
Source File: DefaultGeneratorFactoriesTest.scala    From courier   with Apache License 2.0 5 votes vote down vote up
package org.coursera.courier.fixture

import org.coursera.courier.fixture.generator.CoercedValueGenerator
import org.coursera.courier.fixture.generator.DefaultGeneratorFactories
import org.coursera.courier.generator.customtypes.CoercedDateTimeGenerator
import org.coursera.courier.generator.customtypes.DateTimeCoercer
import org.example.Fortune
import org.joda.time.DateTime
import org.junit.Test
import org.scalatest.junit.AssertionsForJUnit
import org.scalatest.junit.JUnitSuite

import FixtureSugar._

class DefaultGeneratorFactoriesTest extends JUnitSuite with AssertionsForJUnit {

  val defaultTime = new DateTime("2016-07-05T17:19:46.087-07:00")
  class ConstantDateTimeGenerator extends CoercedValueGenerator[DateTime] {
    override val coercer = new DateTimeCoercer
    def nextValue(): DateTime = defaultTime
  }

  @Test
  def fixtureGenerator_WithoutDefaultTimeGenerator_UseDefinedTimeGenerator(): Unit = {
    val generator = fixtureGenerator[Fortune]

    val expectedTime = new CoercedDateTimeGenerator().nextValue()
    assertResult(expectedTime)(generator.next().createdAt)
  }

  @Test
  def fixtureGenerator_WithDefaultGeneratorForType_UseDefaultTypeGenerator(): Unit = {
    implicit val defaultGenerator: DefaultGeneratorFactories = DefaultGeneratorFactories()
      .set[DateTime]((name: String) => new ConstantDateTimeGenerator)

    val generator = fixtureGenerator[Fortune]

    assertResult(defaultTime)(generator.next().createdAt)
  }

  @Test
  def fixtureGenerator_WithFieldOverride_UseGeneratorOverride(): Unit = {
    implicit val defaultGenerator: DefaultGeneratorFactories = DefaultGeneratorFactories()
      .set[DateTime]((name: String) => new ConstantDateTimeGenerator)

    val customTime = defaultTime.plus(10000L)
    val coercer = new DateTimeCoercer()
    val generator = fixtureGenerator[Fortune]
        .withField("createdAt", coercer.coerceInput(customTime))

    assertResult(customTime)(generator.next().createdAt)
  }

} 
Example 116
Source File: AbstractEvaluator.scala    From cave   with MIT License 5 votes vote down vote up
package com.cave.metrics.data.evaluator

import org.joda.time.DateTime

import scala.concurrent.duration.FiniteDuration
import scala.concurrent.{ExecutionContext, Future}
import scala.util.Try

abstract class AbstractEvaluator(conditionStr: String) extends AlertParser {

  private val condition = parseAll(anyAlert, conditionStr) match {
    case Success(SimpleAlert(leftOperand, operator, rightOperand, repeatCount, delay), _) =>
      Left((leftOperand, operator, rightOperand, repeatCount, delay))

    case Success(MissingDataAlert(metricSource, duration), _) =>
      Right((metricSource, duration))

    case _ => sys.error("Unsupported check condition: " + conditionStr)
  }

  def evaluateRange(clusterName: Option[String], databaseName: String, end: DateTime)
                   (implicit fetcher: DataFetcher, ec: ExecutionContext): Future[Try[Boolean]] = {
    condition match {
      case Left((left, operator, right, repeats, delay)) =>
        val results = for {
          leftResult <- evaluateSource(clusterName, databaseName, end, left, repeats, delay)(fetcher, ec)
          rightResult <- evaluateSource(clusterName, databaseName, end, right, repeats, delay)(fetcher, ec)
        } yield (leftResult, rightResult)

        results map {
          case (Some(l), Some(r)) =>
            val zipped = l.zip(r)
            implicit val op = operator
            scala.util.Success((zipped.size == repeats) && (zipped forall evaluatePair))

          case _ =>
            scala.util.Failure(new RuntimeException("Failed to evaluate: at least one series does not exist."))
        }

      case Right((metricSrc, duration)) =>
        getData(clusterName, databaseName, metricSrc.metric, metricSrc.tags, duration, end)(fetcher, ec) map {
          case Some(values) =>
            scala.util.Success(values.size == 0)

          case None => util.Failure(new RuntimeException("Cannot evaluate: series does not exist!"))
        }
    }
  }

  def evaluateSource(clusterName: Option[String], databaseName: String, end: DateTime,
                     source: Source, repeats: Int, delay: FiniteDuration)
                    (implicit fetcher: DataFetcher, ec: ExecutionContext): Future[Option[List[Double]]] =
    source match {
      case ValueSource(num) => Future.successful(Some(List.fill(repeats)(num)))
      case MetricSource(name, tags) => getData(clusterName, databaseName, name, tags, repeats, delay, end)(fetcher, ec)
      case a: AggregatedSource => getData(clusterName, databaseName, a, repeats, delay, end)(fetcher, ec)

      case FactoredSource(src, factor) => src match {
        case ValueSource(num) =>
          Future.successful(Some(List.fill(repeats)(num * factor)))

        case MetricSource(name, tags) =>
          getData(clusterName, databaseName, name, tags, repeats, delay, end)(fetcher, ec) map(_.map(_.map(_ * factor)))

        case a: AggregatedSource =>
          getData(clusterName, databaseName, a, repeats, delay, end)(fetcher, ec) map(_.map(_.map(_ * factor)))

        case _ => Future.failed(new RuntimeException("Impossible to evaluate."))
      }
    }

  def getData(clusterName: Option[String], databaseName: String, metricName: String,
                       metricTags: Map[String, String], repeats: Int, delay: FiniteDuration, end: DateTime)
                      (implicit fetcher: DataFetcher, ec: ExecutionContext): Future[Option[List[Double]]]

  def getData(clusterName: Option[String], databaseName: String, metricName: String,
                       metricTags: Map[String, String], duration: FiniteDuration, end: DateTime)
                      (implicit fetcher: DataFetcher, ec: ExecutionContext): Future[Option[List[Double]]]

  def getData(clusterName: Option[String], databaseName: String, agg: AggregatedSource, repeats: Int, delay: FiniteDuration, end: DateTime)
                      (implicit fetcher: DataFetcher, ec: ExecutionContext): Future[Option[List[Double]]]

  def evaluatePair(values: (Double, Double))(implicit op: Operator.Value): Boolean = op match {
    case Operator.LessThan            => values._1 <  values._2
    case Operator.LessThanOrEqual     => values._1 <= values._2
    case Operator.GreaterThan         => values._1 >  values._2
    case Operator.GreaterThanOrEqual  => values._1 >= values._2
    case Operator.Equal               => values._1 == values._2
    case Operator.NotEqual            => values._1 != values._2
  }
} 
Example 117
Source File: DataFetcher.scala    From cave   with MIT License 5 votes vote down vote up
package com.cave.metrics.data.evaluator

import com.cave.metrics.data.ExponentialBackOff
import com.cave.metrics.data.influxdb.InfluxClientFactory
import org.joda.time.DateTime

import scala.concurrent.{ExecutionContext, Future}
import scala.concurrent.duration.FiniteDuration
import scala.util.control.NonFatal

class DataFetcher(clientFactory: InfluxClientFactory) extends ExponentialBackOff {

  // parameters for Exponential BackOff
  protected val MaxBackOffTimeInMillis = 1000L
  protected val ShouldLogErrors = true
  def maxTries: Int = 3

  def fetchData(clusterName: Option[String], databaseName: String, metricName: String, metricTags: Map[String, String],
                repeats: Int, delay: FiniteDuration, end: DateTime)(implicit ec: ExecutionContext): Future[Option[List[Double]]] =
    try {
      val delayedEnd = end.minusMinutes(delay.toMinutes.toInt)
      val (client, context) = clientFactory.getClient(clusterName)

      retryUpTo(maxTries) {
        client.getMetricData(
          database = databaseName,
          metric = metricName,
          tags = metricTags,
          start = None,
          end = Some(delayedEnd),
          limit = Some(repeats))(context)
      } map {
        case scala.util.Success(data) => data.map(_.metrics.map(_.value).toList)

        case scala.util.Failure(t) => sys.error(t.getMessage)
      }
    } catch {
      case e: RuntimeException =>
        Future.failed(e)
    }

  def fetchData(clusterName: Option[String], databaseName: String, metricName: String, metricTags: Map[String, String],
                duration: FiniteDuration, end: DateTime)(implicit ec: ExecutionContext): Future[Option[List[Double]]] =
    try {
      val (client, context) = clientFactory.getClient(clusterName)
      retryUpTo(maxTries) {
        client.getMetricData(
          database = databaseName,
          metric = metricName,
          tags = metricTags,
          start = Some(end.minusSeconds(duration.toSeconds.toInt)),
          end = Some(end),
          limit = None)(context)
      } map {
        case scala.util.Success(data) => data.map(_.metrics.map(_.value).toList)

        case scala.util.Failure(t) => sys.error(t.getMessage)
      }
    } catch {
      case e: RuntimeException =>
        Future.failed(e)
    }

  def fetchData(clusterName: Option[String], databaseName: String, aggregator: String, period: FiniteDuration,
                metric: String, tags: Map[String, String], repeats: Int, delay: FiniteDuration, end: DateTime)
               (implicit ec: ExecutionContext) = {
    try {
      val delayedEnd = end.minusMinutes(delay.toMinutes.toInt)
      val (client, context) = clientFactory.getClient(clusterName)
      retryUpTo(maxTries) {
        client.getAggregatedData(
          databaseName,
          aggregator, period,
          metric, tags,
          start = None,
          end = Some(delayedEnd),
          limit = Some(repeats)
        )(context)
      } map {
        case scala.util.Success(data) => data.map(_.metrics.map(_.value).toList)
        case scala.util.Failure(t) => sys.error(t.getMessage)
      }
    } catch {
      case NonFatal(e) =>
        Future.failed(e)
    }
  }
} 
Example 118
Source File: InfluxClientFactory.scala    From cave   with MIT License 5 votes vote down vote up
package com.cave.metrics.data.influxdb

import java.util.concurrent.Executors

import com.cave.metrics.data.Metric
import com.typesafe.config.Config
import org.joda.time.{DateTimeZone, DateTime}
import collection.JavaConversions._
import scala.concurrent.ExecutionContext

case class InfluxConfiguration(default: InfluxClusterConfig, alternates: Map[String, InfluxClusterConfig]) {

  val alts = alternates.map { case (name, config) => s"Name: $name, Config: $config"}
  println(s"Default: $default, Alters: $alts")
}

object InfluxConfiguration {

  def apply(config: Config) = {

    val default = InfluxClusterConfig(config.getString("url"), config.getString("user"), config.getString("pass"))

    val alternates = config.getConfigList("alternates") map { conf =>
      conf.getString("name") -> InfluxClusterConfig(conf.getString("url"), default.user, default.pass)
    }

    new InfluxConfiguration(default, alternates.toMap)
  }
}

class InfluxClientFactory(config: InfluxConfiguration) {

  def createClient(clusterConfig: InfluxClusterConfig): (InfluxClient, ExecutionContext) =
    new InfluxClient(clusterConfig) -> ExecutionContext.fromExecutorService(Executors.newSingleThreadExecutor())

  val defaultClient = createClient(config.default)
  val alternates = config.alternates map { case (name, clusterConfig) => name -> createClient(clusterConfig)}

  def getClient(name: Option[String]): (InfluxClient, ExecutionContext) = name match {
    case None => defaultClient
    case Some(clusterName) => alternates.getOrElse(clusterName, default = defaultClient)
  }

  def sendMetrics(metrics: Seq[Metric]): Unit = {

    val now = new DateTime().withZone(DateTimeZone.UTC).getMillis / 1000
    val maxDelay = metrics.foldLeft(0L) { case (delay, metric) =>
        Math.max(delay, Math.abs(metric.timestamp - now))
    }
    val (defaultClient, defaultContext) = getClient(None)
    defaultClient.putMetricData(Seq(
      Metric("writer-delay", now, maxDelay, Map(Metric.Organization -> Metric.Internal))
    ))(defaultContext)

    metrics.groupBy(_.tags.get(Metric.Cluster)) map { case (cluster, metricSeq) =>
      val (client, context) = getClient(cluster)
      client.putMetricData(metricSeq)(context)
    }
  }

  def close(): Unit = {
    defaultClient._1.close()
    alternates foreach { case (_, (client, _)) => client.close() }
  }
} 
Example 119
Source File: CaveStatus.scala    From cave   with MIT License 5 votes vote down vote up
package com.cave.metrics.data

import org.joda.time.DateTime
import play.api.libs.functional.syntax._
import play.api.libs.json._
import org.joda.time.format.ISODateTimeFormat._

case class CaveIssue(description: String, since: DateTime, until: Option[DateTime])
case class CaveStatus(current: Seq[CaveIssue], recent: Seq[CaveIssue])


object CaveIssue {

  final val KeyDescription = "description"
  final val KeySince = "since"
  final val KeyUntil = "until"

  private implicit val jsonReadsJodaDateTime = __.read[String].map(dateTimeParser.parseDateTime(_))

  private implicit val jsonWritesJodaDateTime = new Writes[org.joda.time.DateTime] {
    def writes(x: org.joda.time.DateTime) = JsString(dateTime.print(x))
  }

  implicit val issueReads: Reads[CaveIssue] = (
    (__ \ KeyDescription).read[String] and
      (__ \ KeySince).read[DateTime] and
      (__ \ KeyUntil).readNullable[DateTime]
    )(CaveIssue.apply _)

  implicit val issueWrites: Writes[CaveIssue] = (
    (__ \ KeyDescription).write[String] and
      (__ \ KeySince).write[DateTime] and
      (__ \ KeyUntil).writeNullable[DateTime]
    )(unlift(CaveIssue.unapply))
}

object CaveStatus {
  final val KeyCurrent = "current"
  final val KeyRecent  = "recent"

  implicit val statusReads: Reads[CaveStatus] = (
    (__ \ KeyCurrent).read[Seq[CaveIssue]] and
      (__ \ KeyRecent).read[Seq[CaveIssue]]
    )(CaveStatus.apply _)

  implicit val statusWrites: Writes[CaveStatus] = (
    (__ \ KeyCurrent).write[Seq[CaveIssue]] and
      (__ \ KeyRecent).write[Seq[CaveIssue]]
    )(unlift(CaveStatus.unapply))
} 
Example 120
Source File: Check.scala    From cave   with MIT License 5 votes vote down vote up
package com.cave.metrics.data

import org.joda.time.DateTime
import org.joda.time.format.ISODateTimeFormat
import play.api.libs.json._

case class Check(schedule: Schedule, timestamp: DateTime)

object Check {

  final val FMT = ISODateTimeFormat.dateTimeNoMillis()

  implicit val checkReads = new Reads[Check] {
    def reads(value: JsValue) = try {
      JsSuccess(new Check(
        (value \ "schedule").as[Schedule],
        FMT.parseDateTime((value \ "timestamp").as[String])
      ))
    } catch {
      case e: Exception => JsError(e.getMessage)
    }
  }

  implicit val checkWrites = new Writes[Check] {
    def writes(check: Check): JsValue = {
      Json.obj(
        "schedule" -> Json.toJson(check.schedule),
        "timestamp" -> JsString(FMT.print(check.timestamp))
      )
    }
  }
} 
Example 121
Source File: SchedulerDataManager.scala    From cave   with MIT License 5 votes vote down vote up
package com.cave.metrics.data.postgresql

import java.sql.Timestamp

import com.cave.metrics.data.AwsConfig
import com.cave.metrics.data.postgresql.Tables._
import org.joda.time.format.DateTimeFormat
import org.joda.time.DateTime

import scala.slick.jdbc.{GetResult, StaticQuery => Q}
import scala.slick.driver.PostgresDriver.simple._

class SchedulerDataManager(awsConfig: AwsConfig) extends DatabaseConnection(awsConfig) {

  def leadershipTermTimeoutSeconds = awsConfig.leadershipTermTimeoutSeconds
  def leadershipTermLengthSeconds = awsConfig.leadershipTermLengthSeconds

  def DBDateTimeFormatter = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss Z")

  implicit val getSchedulersResult = GetResult(r => SchedulersRow(r.<<, r.<<, r.<<))

  
  def takeLeadership(hostname: String): Boolean = {
    db.withTransaction { implicit session =>
      val termTimeout = new DateTime().minusSeconds(leadershipTermTimeoutSeconds)
      val timeoutSql = DBDateTimeFormatter.print(termTimeout)
      val sql = s"BEGIN; SELECT * FROM schedulers WHERE created_at < '$timeoutSql' FOR UPDATE"
      val query = Q.queryNA[SchedulersRow](sql)

      def updateTimestamp(): Boolean = Schedulers.filter(_.createdAt < new Timestamp(termTimeout.getMillis))
        .map(s => (s.name, s.createdAt)).update(hostname, new Timestamp(System.currentTimeMillis())) == 1

      try {
        query.list.length == 1 &&
          (updateTimestamp() || {
            session.rollback()
            false
          })
      } catch {
        case e: Exception =>
          log.error(e)
          session.rollback()
          false
      }
    }
  }
} 
Example 122
Source File: Token.scala    From cave   with MIT License 5 votes vote down vote up
package com.cave.metrics.data

import org.apache.commons.lang3.RandomStringUtils
import org.joda.time.format.ISODateTimeFormat.{dateTime, dateTimeParser}
import org.joda.time.{DateTime, DateTimeZone}
import play.api.libs.functional.syntax._
import play.api.libs.json._

case class Token(id: Option[String], description: String, value: String, created: DateTime)

object Token {
  final val KeyId = "id"
  final val KeyDescription = "description"
  final val KeyValue = "value"
  final val KeyCreated = "created"

  final val DefaultName = "default"

  implicit val datetimeReads: Reads[DateTime] =  __.read[String].map(dateTimeParser.parseDateTime)
  implicit val datetimeWrites = new Writes[DateTime] {
    def writes(value: DateTime) = JsString(dateTime.print(value))
  }


  implicit val tokenReads: Reads[Token] = (
      (__ \ KeyId).readNullable[String] and
      (__ \ KeyDescription).read[String] and
      (__ \ KeyValue).read[String] and
      (__ \ KeyCreated).read[DateTime]
    )(Token.apply _)

  implicit val tokenWrites: Writes[Token] = (
      (__ \ KeyId).writeNullable[String] and
      (__ \ KeyDescription).write[String] and
      (__ \ KeyValue).write[String] and
      (__ \ KeyCreated).write[DateTime]
    )(unlift(Token.unapply))

  val secureRandom = new java.security.SecureRandom

  def createToken(description: String): Token =
    new Token(None, description,
      RandomStringUtils.random(56, 0, 0, true, true, null, secureRandom),
      new DateTime().withZone(DateTimeZone.UTC)
    )
} 
Example 123
Source File: GetMetricData.scala    From cave   with MIT License 5 votes vote down vote up
package com.cave.metrics.data

import org.joda.time.DateTime
import org.joda.time.format.ISODateTimeFormat._
import play.api.libs.json._

case class MetricData(time: DateTime, value: Double)
case class MetricDataBulk(metrics: Seq[MetricData])
case class MetricInfo(name: String, tags: List[String])

object MetricData {

  implicit val datetimeReads: Reads[DateTime] =  __.read[String].map(dateTimeParser.parseDateTime)
  implicit val datetimeWrites = new Writes[DateTime] {
    def writes(value: DateTime) = JsString(dateTimeNoMillis.print(value))
  }

  implicit val metricDataReads = Json.reads[MetricData]
  implicit val metricDataWrites = Json.writes[MetricData]
}

object MetricDataBulk {
  implicit val metricDataBulkReads = Json.reads[MetricDataBulk]
  implicit val metricDataBulkWrites = Json.writes[MetricDataBulk]
}

object MetricInfo {
  implicit val metricInfoReads = Json.reads[MetricInfo]
  implicit val metricInfoWrites = Json.writes[MetricInfo]
}

trait GetMetricData {

  
  def getMetricData(metric: String, tags: Map[String, String], timeRange: (DateTime, DateTime)): MetricDataBulk
} 
Example 124
Source File: ModelStateQuery.scala    From model-serving-tutorial   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.modelserving.flink.query

import com.lightbend.modelserving.model.ModelToServeStats
import org.apache.flink.api.common.state.ValueStateDescriptor
import org.apache.flink.api.common.typeinfo.BasicTypeInfo
import org.apache.flink.api.common.{ExecutionConfig, JobID}
import org.apache.flink.api.scala.createTypeInformation
import org.apache.flink.queryablestate.client.QueryableStateClient
import org.joda.time.DateTime


  def query(job: String, keys: Seq[String], host: String = "127.0.0.1", port: Int = 9069,
            timeInterval: Long=defaulttimeInterval): Unit = {

    // JobID, has to correspond to a running job
    val jobId = JobID.fromHexString(job)
    // Client
    val client = new QueryableStateClient(host, port)

    // the state descriptor of the state to be fetched.
    val descriptor = new ValueStateDescriptor[ModelToServeStats](
      "currentModel",   // state name
      createTypeInformation[ModelToServeStats].createSerializer(new ExecutionConfig)
    )
    // Key type
    val keyType = BasicTypeInfo.STRING_TYPE_INFO

    // Sample output line, used to compute the following format string:
    // | winequalityGeneralizedLinearRegressionGaussian | generated from TensorFlow saved bundle | 2019/01/28 13:01:61 | 0.3157894736842105 |  0 | 4 |
    val format       = "| %-50s | %-38s | %-19s | %8.5f | %3d | %3d |\n"
    val headerFormat = "| %-50s | %-38s | %-19s | %-8s | %-3s | %-3s |\n"
    printf(headerFormat, "Name", "Description", "Since", "Average", "Min", "Max")
    printf(headerFormat, "-" * 50, "-" * 38, "-" * 19, "-" * 8, "-" * 3, "-" * 3)
    while(true) {
      for (key <- keys) {
        // For every key
        try {
          // Get statistics
          val future = client.getKvState(jobId, "currentModelState", key, keyType, descriptor)
          val stats = future.join().value()
          printf(format, stats.name, stats.description,
            new DateTime(stats.since).toString("yyyy/MM/dd HH:MM:SS"),
            stats.duration/stats.usage, stats.min, stats.max)
        }
        catch {case e: Exception => e.printStackTrace()}
      }
      // Wait for next
      Thread.sleep(timeInterval)
    }
  }
} 
Example 125
Source File: JsonFormatsTest.scala    From courscala   with Apache License 2.0 5 votes vote down vote up
package org.coursera.common.jsonformat

import org.coursera.common.collection.Enum
import org.coursera.common.collection.EnumSymbol
import org.coursera.common.stringkey.StringKey
import org.coursera.common.stringkey.StringKeyFormat
import org.joda.time.DateTime
import org.joda.time.DateTimeZone
import org.joda.time.Duration
import org.joda.time.Instant
import org.junit.Test
import org.scalatest.junit.AssertionsForJUnit
import play.api.libs.json.Format
import play.api.libs.json.JsNumber
import play.api.libs.json.JsString
import play.api.libs.json.JsSuccess
import play.api.libs.json.Json

class JsonFormatsTest extends AssertionsForJUnit {

  import JsonFormatsTest._

  @Test
  def stringKey(): Unit = {
    val id = TestId(2, "test")
    val idString = StringKey.stringify(id)
    assert(JsString(idString) === Json.toJson(id))
    assert(JsSuccess(id) === Json.fromJson[TestId](JsString(idString)))
    assert(JsString(s"invalid stuff $idString").validate[TestId].isError)
  }

  @Test
  def enums(): Unit = {
    assertResult(Color.Amber)(JsString("Amber").as[Color])

    assertResult(JsString("Green"))(Json.toJson(Color.Green))
  }

  @Test
  def instant(): Unit = {
    import JsonFormats.Implicits.instantFormat
    val testInstant = new Instant(137)
    assertResult(JsNumber(137))(Json.toJson(testInstant))
    assertResult(Some(testInstant))(Json.parse("137").asOpt[Instant])
  }


  @Test
  def duration(): Unit = {
    import JsonFormats.Implicits.durationFormat
    val testDuration = Duration.millis(137L)
    assertResult(JsNumber(137))(Json.toJson(testDuration))
    assertResult(Some(testDuration))(Json.parse("137").asOpt[Duration])
  }


  @Test
  def dateTime(): Unit = {
    import JsonFormats.Implicits.dateTimeFormat
    val testDatetime = new DateTime(2010, 1, 1, 0, 0, 0, 0, DateTimeZone.UTC)
    assertResult(JsNumber(1262304000000L))(Json.toJson(testDatetime))
    assertResult(Some(testDatetime))(Json.parse("1262304000000").asOpt[DateTime].map(_.withZone(DateTimeZone.UTC)))
  }
}

object JsonFormatsTest {

  case class TestId(part1: Int, part2: String)

  object TestId {
    implicit val stringKeyFormat: StringKeyFormat[TestId] =
      StringKeyFormat.caseClassFormat((apply _).tupled, unapply)
    implicit val format: Format[TestId] = JsonFormats.stringKeyFormat[TestId]
  }

  sealed trait Color extends EnumSymbol

  object Color extends Enum[Color] {
    case object Red extends Color
    case object Amber extends Color
    case object Green extends Color

    implicit val format: Format[Color] = JsonFormats.enumFormat(Color)
  }

} 
Example 126
Source File: ToTableRow.scala    From scio   with Apache License 2.0 5 votes vote down vote up
package com.spotify.scio.extra.bigquery

import com.spotify.scio.extra.bigquery.AvroConverters.AvroConversionException

import java.math.{BigDecimal => JBigDecimal}
import java.nio.ByteBuffer
import java.util

import com.spotify.scio.bigquery.TableRow
import org.apache.avro.Schema
import org.apache.avro.generic.{GenericFixed, IndexedRecord}
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.io.BaseEncoding
import org.joda.time.format.DateTimeFormat
import org.joda.time.{DateTime, LocalDate, LocalTime}

import scala.jdk.CollectionConverters._


private[bigquery] trait ToTableRow {
  private lazy val encodingPropName: String = "bigquery.bytes.encoder"
  private lazy val base64Encoding: BaseEncoding = BaseEncoding.base64()
  private lazy val hexEncoding: BaseEncoding = BaseEncoding.base16()

  // YYYY-[M]M-[D]D
  private[this] val localDateFormatter =
    DateTimeFormat.forPattern("yyyy-MM-dd").withZoneUTC()

  // YYYY-[M]M-[D]D[( |T)[H]H:[M]M:[S]S[.DDDDDD]]
  private[this] val localTimeFormatter =
    DateTimeFormat.forPattern("HH:mm:ss.SSSSSS")

  // YYYY-[M]M-[D]D[( |T)[H]H:[M]M:[S]S[.DDDDDD]][time zone]
  private[this] val timestampFormatter =
    DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS")

  private[bigquery] def toTableRowField(fieldValue: Any, field: Schema.Field): Any =
    fieldValue match {
      case x: CharSequence          => x.toString
      case x: Enum[_]               => x.name()
      case x: JBigDecimal           => x.toString
      case x: Number                => x
      case x: Boolean               => x
      case x: GenericFixed          => encodeByteArray(x.bytes(), field.schema())
      case x: ByteBuffer            => encodeByteArray(toByteArray(x), field.schema())
      case x: util.Map[_, _]        => toTableRowFromMap(x.asScala, field)
      case x: java.lang.Iterable[_] => toTableRowFromIterable(x.asScala, field)
      case x: IndexedRecord         => AvroConverters.toTableRow(x)
      case x: LocalDate             => localDateFormatter.print(x)
      case x: LocalTime             => localTimeFormatter.print(x)
      case x: DateTime              => timestampFormatter.print(x)
      case _ =>
        throw AvroConversionException(
          s"ToTableRow conversion failed:" +
            s"could not match ${fieldValue.getClass}"
        )
    }

  private def toTableRowFromIterable(iterable: Iterable[Any], field: Schema.Field): util.List[_] =
    iterable
      .map { item =>
        if (item.isInstanceOf[Iterable[_]] || item.isInstanceOf[Map[_, _]]) {
          throw AvroConversionException(
            s"ToTableRow conversion failed for item $item: " +
              s"iterable and map types not supported"
          )
        }
        toTableRowField(item, field)
      }
      .toList
      .asJava

  private def toTableRowFromMap(map: Iterable[Any], field: Schema.Field): util.List[_] =
    map
      .map {
        case (k, v) =>
          new TableRow()
            .set("key", toTableRowField(k, field))
            .set("value", toTableRowField(v, field))
      }
      .toList
      .asJava

  private def encodeByteArray(bytes: Array[Byte], fieldSchema: Schema): String =
    Option(fieldSchema.getProp(encodingPropName)) match {
      case Some("BASE64") => base64Encoding.encode(bytes)
      case Some("HEX")    => hexEncoding.encode(bytes)
      case Some(encoding) =>
        throw AvroConversionException(s"Unsupported encoding $encoding")
      case None => base64Encoding.encode(bytes)
    }

  private def toByteArray(buffer: ByteBuffer) = {
    val copy = buffer.asReadOnlyBuffer
    val bytes = new Array[Byte](copy.limit)
    copy.rewind
    copy.get(bytes)
    bytes
  }
} 
Example 127
Source File: JodaSerializer.scala    From scio   with Apache License 2.0 5 votes vote down vote up
package com.spotify.scio.coders.instances.kryo

import com.esotericsoftware.kryo.io.{Input, Output}
import com.esotericsoftware.kryo.{Kryo, Serializer}
import org.joda.time.{DateTime, DateTimeZone, LocalDate, LocalDateTime, LocalTime}
import org.joda.time.chrono.ISOChronology

private[coders] class JodaLocalDateTimeSerializer extends Serializer[LocalDateTime] {
  setImmutable(true)

  def write(kryo: Kryo, output: Output, ldt: LocalDateTime): Unit = {
    output.writeInt(ldt.getYear,  false)
    val month = input.readByte().toInt
    val day = input.readByte().toInt

    new LocalDate(year, month, day)
  }
}

private[coders] class JodaDateTimeSerializer extends Serializer[DateTime] {
  setImmutable(true)

  def write(kryo: Kryo, output: Output, dt: DateTime): Unit = {
    output.writeLong(dt.getMillis)
    output.writeString(dt.getZone.getID)
  }

  def read(kryo: Kryo, input: Input, tpe: Class[DateTime]): DateTime = {
    val millis = input.readLong()
    val zone = DateTimeZone.forID(input.readString())
    new DateTime(millis, zone)
  }
} 
Example 128
Source File: JodaSerializerTest.scala    From scio   with Apache License 2.0 5 votes vote down vote up
package com.spotify.scio.coders.instances.kryo

import com.spotify.scio.coders.{CoderTestUtils, KryoAtomicCoder, KryoOptions}
import org.joda.time.{DateTime, DateTimeZone, LocalDate, LocalDateTime, LocalTime}
import org.scalacheck._
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatestplus.scalacheck.Checkers

import scala.jdk.CollectionConverters._
import scala.util.Try

class JodaSerializerTest extends AnyFlatSpec with Checkers {
  // TODO: remove this once https://github.com/scalatest/scalatest/issues/1090 is addressed
  implicit override val generatorDrivenConfig: PropertyCheckConfiguration =
    PropertyCheckConfiguration(minSuccessful = 100)

  implicit val dateTimeArb = Arbitrary {
    for {
      year <- Gen.choose(-292275054, 292278993)
      month <- Gen.choose(1, 12)
      maxDayOfMonth <- Try {
        Gen.const(new LocalDateTime(year, month, 1, 0, 0).dayOfMonth().getMaximumValue)
      }.getOrElse(Gen.fail)
      day <- Gen.choose(1, maxDayOfMonth)
      hour <- Gen.choose(0, 23)
      minute <- Gen.choose(0, 59)
      second <- Gen.choose(0, 59)
      ms <- Gen.choose(0, 999)
      tz <- Gen.oneOf(DateTimeZone.getAvailableIDs.asScala.toSeq)
      attempt <- Try {
        val ldt = new DateTime(year, month, day, hour, minute, second, ms, DateTimeZone.forID(tz))
        Gen.const(ldt)
      }.getOrElse(Gen.fail)
    } yield attempt
  }

  implicit val localDateTimeArb = Arbitrary {
    Arbitrary.arbitrary[DateTime].map(_.toLocalDateTime)
  }

  implicit val localTimeArb = Arbitrary {
    Arbitrary.arbitrary[LocalDateTime].map(_.toLocalTime)
  }

  implicit val localDateArb = Arbitrary {
    Arbitrary.arbitrary[LocalDateTime].map(_.toLocalDate)
  }

  val coder = new KryoAtomicCoder[Any](KryoOptions())

  def roundTripProp[T](value: T): Prop = Prop.secure {
    CoderTestUtils.testRoundTrip(coder, value)
  }

  "KryoAtomicCoder" should "roundtrip LocalDate" in {
    check(roundTripProp[LocalDate] _)
  }

  it should "roundtrip LocalTime" in {
    check(roundTripProp[LocalTime] _)
  }

  it should "roundtrip LocalDateTime" in {
    check(roundTripProp[LocalDateTime] _)
  }

  it should "roundtrip DateTime" in {
    check(roundTripProp[DateTime] _)
  }
} 
Example 129
Source File: CheckEvaluator.scala    From cave   with MIT License 5 votes vote down vote up
package com.cave.metrics.data.evaluator

import com.cave.metrics.data.Check
import org.joda.time.DateTime

import scala.concurrent.duration.FiniteDuration
import scala.concurrent.{ExecutionContext, Future}
import scala.util.Try

class CheckEvaluator(check: Check) extends AbstractEvaluator(check.schedule.alert.condition) {

  def evaluate(fetcher: DataFetcher)(implicit ec: ExecutionContext): Future[Try[Boolean]] = {
    evaluateRange(clusterName = check.schedule.clusterName,
                  databaseName = check.schedule.databaseName,
                  end = check.timestamp)(fetcher, ec)
  }

  override def getData(clusterName: Option[String], databaseName: String, metricName: String,
                       metricTags: Map[String, String], repeats: Int, delay: FiniteDuration, end: DateTime)
                      (implicit fetcher: DataFetcher, ec: ExecutionContext): Future[Option[List[Double]]] =
    fetcher.fetchData(clusterName, databaseName, metricName, metricTags, repeats, delay, end)(ec)

  override def getData(clusterName: Option[String], databaseName: String, metricName: String,
                       metricTags: Map[String, String], duration: FiniteDuration, end: DateTime)
                      (implicit fetcher: DataFetcher, ec: ExecutionContext): Future[Option[List[Double]]] =
    fetcher.fetchData(clusterName, databaseName, metricName, metricTags, duration, end)(ec)

  override def getData(clusterName: Option[String], databaseName: String, agg: AggregatedSource, repeats: Int, delay: FiniteDuration, end: DateTime)
                      (implicit fetcher: DataFetcher, ec: ExecutionContext): Future[Option[List[Double]]] =
    fetcher.fetchData(clusterName, databaseName, agg.toString, Map.empty[String, String], repeats, delay, end)(ec)
} 
Example 130
Source File: DateTimeCoercer.scala    From courier   with Apache License 2.0 5 votes vote down vote up
package org.coursera.courier.generator.customtypes

import com.linkedin.data.template.Custom
import com.linkedin.data.template.DirectCoercer
import org.joda.time.DateTime

class DateTimeCoercer extends DirectCoercer[DateTime] {

   override def coerceInput(obj: DateTime): AnyRef = {
     obj.toString()
   }

   override def coerceOutput(obj: Any): DateTime = {
     obj match {
       case string: String => new DateTime(string)
       case _: Any =>
         throw new IllegalArgumentException(
           s"DateTime field must be string, but was ${obj.getClass}")
     }
   }
 }

object DateTimeCoercer {

   registerCoercer()

   def registerCoercer(): Unit = {
     Custom.registerCoercer(new DateTimeCoercer, classOf[DateTime])
   }
 } 
Example 131
Source File: ReceiptGenerator.scala    From apple-of-my-iap   with MIT License 5 votes vote down vote up
package com.meetup.iap.receipt

import com.meetup.iap.AppleApi
import com.meetup.iap.Plan
import AppleApi.{ReceiptResponse, ReceiptInfo}
import org.joda.time.{DateTime, Period}

object ReceiptGenerator {

  def genEncoding(plan: Plan,
                  existingEncodings: Set[String]): String = {
    def helper: String = {
      val id = java.util.UUID.randomUUID.toString.split("-")
      val id1 = id(0)
      val id2 = id(1)
      val receipt = s"${plan.name}_$id1-$id2"

      if(existingEncodings.contains(receipt)) helper
      else receipt
    }

    helper
  }

  def apply(plan: Plan,
            receiptOrSub: Either[String, Subscription] ): (String, ReceiptInfo) = {

    val purchaseDateTime = new DateTime()
    val purchaseDate = purchaseDateTime.toDate
    val productId = plan.productId
    val transactionId = s"$productId-$purchaseDateTime"
    val expiresDate = calculateEndDate(purchaseDateTime, plan.billInterval, plan.billIntervalUnit).toDate

    val (origPurchaseDate, origTransId, receiptToken) = receiptOrSub match {
      case Left(receipt) =>
        (purchaseDate, transactionId, receipt)
      case Right(subscription) =>
        val orig = subscription.originalReceiptInfo
        val origReceipt = subscription.receiptTokenMap.get(orig.transactionId).getOrElse("ERROR_no_receipt_token_found")
        val id = subscription.receiptsList.size
        (orig.purchaseDate, orig.transactionId, f"$origReceipt-${id}%03d")
    }

    (receiptToken, ReceiptInfo(
                    origPurchaseDate,
                    origTransId,
                    transactionId,
                    purchaseDate,
                    expiresDate,
                    productId,
                    cancellationDate = None,
                    isTrialPeriod = false,
                    isInIntroOfferPeriod = None,
                    quantity = 1))
  }

  def apply(sub: Subscription): ReceiptResponse = {
    ReceiptResponse(
      sub.latestReceiptToken,
      sub.receiptsList,
      sub.status)
  }

  def calculateEndDate(startDate: DateTime, interval: Int, intervalUnit: String): DateTime = {
    startDate.plus(getPeriod(intervalUnit, interval))
  }

  private def getPeriod(interval: String, length: Int): Period = {
    interval match {
      case "seconds" => Period.seconds(length)
      case "minutes" => Period.minutes(length)
      case "hours"   => Period.hours(length)
      case "days"    => Period.days(length)
      case "weeks"   => Period.weeks(length)
      case "months"  => Period.months(length)
      case "years"   => Period.years(length)
      case _         => throw new IllegalStateException(s"Could not create period for interval: $interval")
    }
  }
} 
Example 132
Source File: ReceiptRendererTest.scala    From apple-of-my-iap   with MIT License 5 votes vote down vote up
package com.meetup.iap.receipt

import com.meetup.iap.AppleApi
import AppleApi.{ReceiptResponse, ReceiptInfo}

import org.scalatest.{Matchers, PropSpec}
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.joda.time.{Period, DateTime}

class ReceiptRendererTest extends PropSpec with GeneratorDrivenPropertyChecks with Matchers {

  property("Renderer should produce valid dates") {
    val purchaseDate = new DateTime().withMillis(0).toDate
    val expiresDate = new DateTime().withMillis(0).plus(Period.days(7)).toDate
    val cancellationDate = new DateTime().withMillis(0).plus(Period.days(3)).toDate

    println(s"Orig purchaseDate: $purchaseDate, $expiresDate, $cancellationDate")

    val transactionId = "10022345304"
    val receiptInfo = ReceiptInfo(
          purchaseDate,
          transactionId,
          transactionId,
          purchaseDate,
          expiresDate,
          "123943451",
          isTrialPeriod = false,
          isInIntroOfferPeriod = None,
          Some(cancellationDate),
          1)

    val json = ReceiptRenderer(ReceiptResponse(None, List(receiptInfo)))
    val response = AppleApi.parseResponse(json)

    response.latestInfo.isDefined should equal (true)
    response.latestInfo.map { info =>
      info.purchaseDate should equal (purchaseDate)
      info.expiresDate should equal (expiresDate)

      info.cancellationDate.isDefined should equal (true)
      info.cancellationDate.map(_ should equal (cancellationDate))
    }
  }
} 
Example 133
Source File: PSetAny.scala    From yoda-orm   with MIT License 5 votes vote down vote up
package in.norbor.yoda.orm

import java.sql.{Blob, Timestamp}

import org.joda.time.DateTime


trait PSetAny {

  def set(p: PStatement, v: Any): PStatement = v match {
    case _: Boolean => p.setBoolean(v.asInstanceOf[Boolean])
    case _: Int => p.setInt(v.asInstanceOf[Int])
    case _: Long => p.setLong(v.asInstanceOf[Long])
    case _: Float => p.setDouble(v.asInstanceOf[Double])
    case _: Double => p.setDouble(v.asInstanceOf[Double])
    case _: String => p.setString(v.asInstanceOf[String])
    case _: Timestamp => p.setTimestamp(v.asInstanceOf[Timestamp])
    case _: DateTime => p.setDateTime(v.asInstanceOf[DateTime])
    case _: Blob => p.setBlob(v.asInstanceOf[Blob])
    case _: Array[Byte] => p.setBytes(v.asInstanceOf[Array[Byte]])
    case _ => p;
  }

} 
Example 134
Source File: PStatementTest.scala    From yoda-orm   with MIT License 5 votes vote down vote up
package in.norbor.yoda.orm

import java.sql.{Connection, DriverManager, ResultSet, Timestamp}

import com.typesafe.scalalogging.LazyLogging
import in.norbor.yoda.implicits.JavaSqlImprovement._
import mocks.People
import org.joda.time.DateTime
import org.scalatest.funsuite.AnyFunSuite


class PStatementTest extends AnyFunSuite {

  Class.forName("org.h2.Driver")

  private implicit val conn: Connection = DriverManager.getConnection("jdbc:h2:~/test", "sa", "")

  test("0) apply") {

    val ps = PStatement("SELECT 1")(conn)
    assert(ps !== null)

    ps.equals(null)
    ps.canEqual(null)
    ps.hashCode
    ps.toString
    ps.productPrefix
    ps.productArity
    ps.productElement(0)
    ps.productIterator
    ps.copy()
  }

  test("0) query") {

    PStatement("DROP TABLE IF EXISTS yoda_sql; CREATE TABLE yoda_sql (id INTEGER);")
      .update
  }

  test("0) update") {

    val rs = PStatement("""select 1""")
      .query

    assert(rs !== null)
  }

  test("0) queryOne with non index parameter") {

    val result = PStatement("""select ?, ?, ?, ?, ?, ?, ?, ?""")
      .setBoolean(true)
      .setInt(1)
      .setLong(1L)
      .setDouble(1)
      .setString("YO")
      .setDateTime(DateTime.now)
      .setTimestamp(new Timestamp(System.currentTimeMillis))
      .setTimestamp(null)
      .queryOne(parse)

    assert(result.head._1 === true)
  }

  test("3) queryList with parse method") {

    val peoples = PStatement("""select 1 as id, 'Peerapat' as name, now() as born;""")
      .queryList(parsePeople)

    assert(peoples.head.id === 1)
    assert(peoples.head.name === "Peerapat")
    assert(peoples.head.born.getMillis <= DateTime.now.getMillis)
  }

  test("5) batch") {

    val insert = PStatement("INSERT INTO yoda_sql VALUES(?)")
      .setInt(1)
      .addBatch()
      .setInt(2)
      .addBatch()
      .executeBatch

    assert(insert.length === 2)
  }


  private def parse(rs: ResultSet): (Boolean, Int, Long, Double, String, DateTime, Timestamp) = (rs.getBoolean(1)
    , rs.getInt(2)
    , rs.getLong(3)
    , rs.getDouble(4)
    , rs.getString(5)
    , rs.getDateTime(6)
    , rs.getTimestamp(7)
  )

  private def parsePeople(rs: ResultSet): People = People(id = rs.getLong("id")
    , name = rs.getString("name")
    , born = rs.getDateTime("born")
  )

} 
Example 135
Source File: OrmAnnotate.scala    From yoda-orm   with MIT License 5 votes vote down vote up
package mocks

import in.norbor.yoda.annotations.{ColumnSchema, TableSchema}
import org.joda.time.DateTime


@TableSchema(name = "orm", pk = "id")
case class OrmAnnotate(@ColumnSchema(name = "id") id: Long
                       , @ColumnSchema(name = "full_name"
                                      , dbType = "VARCHAR"
                                      , isUnique = false
                                      , defaultValue = "Somchai") name: String
                       , sex: Int
                       , born: DateTime
                       , created: DateTime) {

  @SuppressWarnings(Array("Do not use"))
  def noOneUse: Boolean = false

} 
Example 136
Source File: DateTimeConverter.scala    From seahorse-workflow-executor   with Apache License 2.0 5 votes vote down vote up
package io.deepsense.commons.datetime

import java.sql.Timestamp

import org.joda.time.format.{DateTimeFormatter, ISODateTimeFormat}
import org.joda.time.{DateTime, DateTimeZone}

trait DateTimeConverter {
  val zone: DateTimeZone = DateTimeZone.getDefault
  val dateTimeFormatter: DateTimeFormatter = ISODateTimeFormat.dateTime()
  def toString(dateTime: DateTime): String = dateTime.toString(dateTimeFormatter)
  def parseDateTime(s: String): DateTime = dateTimeFormatter.parseDateTime(s).withZone(zone)
  def parseTimestamp(s: String): Timestamp = new Timestamp(parseDateTime(s).getMillis)
  def now: DateTime = new DateTime(zone)
  def fromMillis(millis: Long): DateTime = new DateTime(zone).withMillis(millis)
  def dateTime(
      year: Int,
      monthOfyear: Int,
      dayOfMonth: Int,
      hourOfDay: Int = 0,
      minutesOfHour: Int = 0,
      secondsOfMinute: Int = 0): DateTime =
    new DateTime(year, monthOfyear, dayOfMonth, hourOfDay, minutesOfHour, secondsOfMinute, zone)
  def dateTimeFromUTC(
      year: Int,
      monthOfyear: Int,
      dayOfMonth: Int,
      hourOfDay: Int = 0,
      minutesOfHour: Int = 0,
      secondsOfMinute: Int = 0): DateTime =
    new DateTime(
      year,
      monthOfyear,
      dayOfMonth,
      hourOfDay,
      minutesOfHour,
      secondsOfMinute,
      DateTimeZone.UTC).withZone(DateTimeConverter.zone)
}

object DateTimeConverter extends DateTimeConverter 
Example 137
Source File: DatasourceTestData.scala    From seahorse-workflow-executor   with Apache License 2.0 5 votes vote down vote up
package io.deepsense.commons.datasource

import java.util.UUID

import org.joda.time.DateTime

import io.deepsense.api.datasourcemanager.model.{AccessLevel, DatasourceParams, DatasourceType, Visibility, _}

object DatasourceTestData {
  def multicharSeparatorLibraryCsvDatasource: Datasource = {
    val ds = new Datasource
    val libraryFileParams = new LibraryFileParams
    libraryFileParams.setLibraryPath("some_path")
    libraryFileParams.setFileFormat(FileFormat.CSV)
    val csvType = new CsvFileFormatParams
    csvType.setConvert01ToBoolean(false)
    csvType.setIncludeHeader(false)
    csvType.setSeparatorType(CsvSeparatorType.CUSTOM)
    csvType.setCustomSeparator(",,")
    libraryFileParams.setCsvFileFormatParams(csvType)

    val params = new DatasourceParams
    params.setDatasourceType(DatasourceType.LIBRARYFILE)
    params.setLibraryFileParams(libraryFileParams)
    params.setName("name")
    params.setVisibility(Visibility.PUBLICVISIBILITY)

    ds.setCreationDateTime(new DateTime)
    ds.setParams(params)
    ds.setId(UUID.randomUUID.toString)
    ds.setCreationDateTime(new DateTime())
    ds.setAccessLevel(AccessLevel.WRITEREAD)
    ds.setOwnerId("abcd")
    ds.setOwnerName("owner_name")
    ds
  }
} 
Example 138
Source File: DatasourceListJsonProtocolSpec.scala    From seahorse-workflow-executor   with Apache License 2.0 5 votes vote down vote up
package io.deepsense.commons.json.envelope

import org.joda.time.DateTime
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{Matchers, WordSpec}

import io.deepsense.api.datasourcemanager.model.{AccessLevel, Datasource, DatasourceParams, DatasourceType}
import io.deepsense.commons.datasource.DatasourceTestData
import io.deepsense.commons.json.datasources.DatasourceListJsonProtocol

class DatasourceListJsonProtocolSpec
  extends WordSpec
  with MockitoSugar
  with Matchers {

  val uuid = "123e4567-e89b-12d3-a456-426655440000"
  val externalFile = DatasourceType.EXTERNALFILE

  val dsList = List(DatasourceTestData.multicharSeparatorLibraryCsvDatasource)

  "DatasourceJsonProtocolSpec" should {
    "serialize and deserialize single datasource" in {
      val datasourcesJson = DatasourceListJsonProtocol.toString(dsList)
      val asString = datasourcesJson.toString
      val datasources = DatasourceListJsonProtocol.fromString(asString)
      info(s"Datasource: $datasources, json: $asString")
      datasources should contain theSameElementsAs dsList
    }

    "serialize no datasource" in {
      val datasourcesJson = DatasourceListJsonProtocol.toString(List.empty[Datasource])
      datasourcesJson shouldBe "[]"
    }
  }
} 
Example 139
Source File: WorkflowInfo.scala    From seahorse-workflow-executor   with Apache License 2.0 5 votes vote down vote up
package io.deepsense.models.workflows

import org.joda.time.DateTime

case class WorkflowInfo(
  id: Workflow.Id,
  name: String,
  description: String,
  created: DateTime,
  updated: DateTime,
  ownerId: String,
  ownerName: String)

object WorkflowInfo {
  def empty(): WorkflowInfo =
    WorkflowInfo(Workflow.Id.randomId, "", "", DateTime.now, DateTime.now, "", "")

  def forId(id: Workflow.Id): WorkflowInfo =
    WorkflowInfo(id, "", "", DateTime.now, DateTime.now, "", "")
} 
Example 140
Source File: BacktestBenchmarks.scala    From Scala-High-Performance-Programming   with MIT License 5 votes vote down vote up
package highperfscala.concurrency.backtesting

import java.util.concurrent.TimeUnit

import highperfscala.concurrency.backtesting.Backtest.{BacktestPerformanceSummary, DecisionDelayMillis}
import org.joda.time.{DateTime, Interval, MonthDay}
import org.openjdk.jmh.annotations.Mode._
import org.openjdk.jmh.annotations._

import scala.annotation.tailrec

@BenchmarkMode(Array(Throughput))
@OutputTimeUnit(TimeUnit.SECONDS)
@Warmup(iterations = 3, time = 5, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 30, time = 10, timeUnit = TimeUnit.SECONDS)
@Fork(value = 1, warmups = 1, jvmArgs = Array("-Xms1G", "-Xmx1G"))
class BacktestBenchmarks {

  import BacktestBenchmarks._

  @Benchmark
  def withoutConcurrency(state: BenchmarkState): BacktestPerformanceSummary =
    Backtest.backtestWithoutConcurrency(state.backtestDays, state.decisionDelay)
      .unsafePerformSync

  @Benchmark
  def withBatchedForking(state: BenchmarkState): BacktestPerformanceSummary =
    Backtest.backtestWithBatchedForking(state.backtestDays, state.decisionDelay)
      .unsafePerformSync

  @Benchmark
  def withAllForked(state: BenchmarkState): BacktestPerformanceSummary =
    Backtest.backtestWithAllForked(state.backtestDays, state.decisionDelay)
      .unsafePerformSync
}

object BacktestBenchmarks {

  private def daysWithin(i: Interval): List[MonthDay] = {
    @tailrec
    def recurse(xs: List[MonthDay], current: DateTime): List[MonthDay] =
      current.isAfter(i.getEnd) match {
        case true => xs
        case false => recurse(
          new MonthDay(current.getMonthOfYear, current.getDayOfMonth) :: xs,
          current.plusDays(1))
      }
    recurse(Nil, i.getStart)
  }

  // Constant starting point to avoid differences due to number of days
  // per month
  private val end: DateTime = new DateTime(2016, 1, 1, 0, 0, 0, 0)
  private def trailingMonths(backtestIntervalMonths: Int): Interval =
    new Interval(
      end.minusMonths(backtestIntervalMonths), end)

  @State(Scope.Benchmark)
  class BenchmarkState {
    @Param(Array("1", "10"))
    var decisionDelayMillis: Long = 0
    @Param(Array("1", "12", "24" ))
    var backtestIntervalMonths: Int = 0

    var decisionDelay: DecisionDelayMillis = DecisionDelayMillis(-1)
    var backtestDays: List[MonthDay] = Nil

    @Setup
    def setup(): Unit = {
      decisionDelay = DecisionDelayMillis(decisionDelayMillis)
      backtestDays = daysWithin(trailingMonths(backtestIntervalMonths))
    }
  }
} 
Example 141
Source File: Backtesting.scala    From Scala-High-Performance-Programming   with MIT License 5 votes vote down vote up
package highperfscala.concurrency.backtesting

import java.util.concurrent.TimeUnit

import org.joda.time.{DateTime, Interval}

import scala.concurrent.{Await, Future}

object Backtesting {

  sealed trait Strategy

  case class PnL(value: BigDecimal) extends AnyVal
  case class BacktestPerformanceSummary(pnl: PnL)

  case class Ticker(value: String) extends AnyVal

  def backtest(
    strategy: Strategy,
    ticker: Ticker,
    testInterval: Interval): BacktestPerformanceSummary = ???

  sealed trait VectorBasedReturnSeriesFrame

  def loadReturns(testInterval: Interval): VectorBasedReturnSeriesFrame = ???

  case object Dave1 extends Strategy
  case object Dave2 extends Strategy

  object Serial {
    def lastMonths(months: Int): Interval =
      new Interval(new DateTime().minusMonths(months), new DateTime())
    backtest(Dave1, Ticker("AAPL"), lastMonths(3))
    backtest(Dave1, Ticker("GOOG"), lastMonths(3))
    backtest(Dave2, Ticker("AAPL"), lastMonths(3))
    backtest(Dave2, Ticker("GOOG"), lastMonths(2))
  }

  object ForComprehension {
    def lastMonths(months: Int): Interval =
      new Interval(new DateTime().minusMonths(months), new DateTime())

    implicit val ec = scala.concurrent.ExecutionContext.Implicits.global
    val summariesF = for {
      firstDaveAapl <- Future(backtest(Dave1, Ticker("AAPL"), lastMonths(3)))
      firstDaveGoog <- Future(backtest(Dave1, Ticker("GOOG"), lastMonths(3)))
      secondDaveAapl <- Future(backtest(Dave2, Ticker("AAPL"), lastMonths(3)))
      secondDaveGoog <- Future(backtest(Dave2, Ticker("GOOG"), lastMonths(2)))
    } yield (firstDaveAapl, firstDaveGoog, secondDaveAapl, secondDaveGoog)

    Await.result(summariesF, scala.concurrent.duration.Duration(1, TimeUnit.SECONDS))

    Future(1).flatMap(f1 => Future(2).flatMap(f2 => Future(3).map(f3 => (f1, f2, f3))))
  }

  object Concurrency {
    def lastMonths(months: Int): Interval =
      new Interval(new DateTime().minusMonths(months), new DateTime())

    implicit val ec = scala.concurrent.ExecutionContext.Implicits.global
    val firstDaveAaplF = Future(backtest(Dave1, Ticker("AAPL"), lastMonths(3)))
    val firstDaveGoogF = Future(backtest(Dave1, Ticker("GOOG"), lastMonths(3)))
    val secondDaveAaplF = Future(backtest(Dave2, Ticker("AAPL"), lastMonths(3)))
    val secondDaveGoogF = Future(backtest(Dave2, Ticker("GOOG"), lastMonths(2)))
    val z = for {
      firstDaveAapl <- firstDaveAaplF
      firstDaveGoog <- firstDaveGoogF
      secondDaveAapl <- secondDaveAaplF
      secondDaveGoog <- secondDaveGoogF
    } yield (firstDaveAapl, firstDaveGoog, secondDaveAapl, secondDaveGoog)

  }

} 
Example 142
Source File: MidpointSeriesSpec.scala    From Scala-High-Performance-Programming   with MIT License 5 votes vote down vote up
package highperfscala.dataanalysis

import org.joda.time.DateTime
import org.specs2.mutable.Specification

class MidpointSeriesSpec extends Specification {

  "A MidpointSeries" should {

    "be properly created from execution data points" in {
      val t0 = TimestampMinutes.fromDateTime(DateTime.now)
      val t1 = t0.next
      val t2 = t1.next
      val t3 = t2.next
      val t4 = t3.next
      val t5 = t4.next
      val t6 = t5.next
      val executions = Vector(
        Execution(t0, AskPrice(40), BidPrice(20)),
        Execution(t1, AskPrice(30), BidPrice(25)),
        Execution(t1, AskPrice(50), BidPrice(22)),
        Execution(t4, AskPrice(24), BidPrice(16)),
        Execution(t4, AskPrice(84), BidPrice(78)),
        Execution(t4, AskPrice(64), BidPrice(37)),
        Execution(t6, AskPrice(41), BidPrice(23))
      )

      val series = MidpointSeries.fromExecution(executions)
      series.size ==== 7
      series.midpointAt(t0).get ==== Midpoint(t0, 30)
      series.midpointAt(t1).get ==== Midpoint(t1, 31.75)
      series.midpointAt(t2).get ==== Midpoint(t2, 31.75)
      series.midpointAt(t3).get ==== Midpoint(t3, 31.75)
      series.midpointAt(t4).get ==== Midpoint(t4, 50.5)
      series.midpointAt(t5).get ==== Midpoint(t5, 50.5)
      series.midpointAt(t6).get ==== Midpoint(t6, 32)
      series.midpointAt(t6.next) ==== None
    }

  }

} 
Example 143
Source File: UserAuthRepositorySpec.scala    From akka-http-rest-api   with MIT License 5 votes vote down vote up
package authentication

import org.joda.time.DateTime
import org.scalatest.Matchers
import user.{User, UserRepository}
import utils.FlatSpecWithSql

import scala.concurrent.ExecutionContext.Implicits.global

class UserAuthRepositorySpec extends FlatSpecWithSql with Matchers {
  behavior of "UserAuthRepository"

  val userRepo = new UserRepository
  val userAuthRepo = new UserAuthRepository

  it should "add new user auth" in {
    val user = User(None, DateTime.now().getMillis, "Jan", "Kowalski", 1, None, None, None, 0)
    val userId = userRepo.insert(user).futureValue.id.get

    val userAuth = UserAuth(None, "[email protected]", "password", userId)
    val userAuthId = userAuthRepo.insert(userAuth).futureValue.id.get

    userAuthRepo.findByUserAuthId(userAuthId).futureValue should be('defined)
  }

  it should "find user auth by email" in {
    val user = User(None, DateTime.now().getMillis, "Marek", "Nowak", 1, None, None, None, 0)
    val userId = userRepo.insert(user).futureValue.id.get

    val email = "[email protected]"
    val userAuth = UserAuth(None, email, "password", userId)
    val userAuthId = userAuthRepo.insert(userAuth).futureValue.id.get

    userAuthRepo.findByUserEmail(email).futureValue should equal(Some(userAuth.copy(id = Some(userAuthId))))
  }

  it should "delete user auth" in {
    val user = User(None, DateTime.now().getMillis, "Marek", "Nowak", 1, None, None, None, 0)
    val userId = userRepo.insert(user).futureValue.id.get

    val userAuth = UserAuth(None, "[email protected]", "password", userId)
    userAuthRepo.insert(userAuth).futureValue.id.get

    userAuthRepo.deleteByUserId(userId).futureValue

    userAuthRepo.findByUserId(userId).futureValue should be(None)
  }
} 
Example 144
Source File: VisitSpec.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package services.visit

import java.util.UUID
import services.ContentType
import services.RuntimeAccessLevel
import org.specs2.mutable._
import org.specs2.runner._
import org.junit.runner._
import org.joda.time.{ DateTime, DateTimeZone }
import org.joda.time.format.DateTimeFormat
import play.api.libs.json.Json
import play.api.test._
import play.api.test.Helpers._
import scala.io.Source

@RunWith(classOf[JUnitRunner])
class VisitSpec extends Specification {
  
  private val DATE_TIME_PATTERN = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ")
  private val visitedAt = DateTime.parse("2016-11-08T07:27:00Z", DATE_TIME_PATTERN).withZone(DateTimeZone.UTC)

  "The sample Visit" should {
    
    "be properly created from JSON" in {
      val json = Source.fromFile("test/resources/services/visit/visit.json").getLines().mkString("\n")
      val result = Json.fromJson[Visit](Json.parse(json))
            
      result.isSuccess must equalTo(true) 
      
      val visit = result.get
      visit.url must equalTo("http://recogito.pelagios.org/document/fb2f3hm1ihnwgn/part/1/edit")
      visit.referer must equalTo(Some("http://recogito.pelagios.org/rainer"))
      visit.visitedAt must equalTo(visitedAt)  
      visit.responseFormat must equalTo("text/html")
      visit.accessLevel must equalTo(Some(RuntimeAccessLevel.READ_ALL))
      
      val client = visit.client
      client.userAgent must equalTo("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/52.0.2743.116 Chrome/52.0.2743.116 Safari/537.36")
      client.browser must equalTo("CHROME")
      client.os must equalTo("LINUX")
      client.deviceType must equalTo("COMPUTER")
      
      val item = visit.visitedItem.get
      item.documentId must equalTo("fb2f3hm1ihnwgn")
      item.documentOwner must equalTo("rainer")
      item.filepartId must equalTo(Some(UUID.fromString("a7126845-16ac-434b-99bd-0f297e227822")))
      item.contentType must equalTo(Some(ContentType.TEXT_PLAIN))
    }
    
  }
  
  "JSON serialization/parsing roundtrip" should {
    
    "yield an equal Visit" in {
      val visit = Visit(
        "http://recogito.pelagios.org/document/fb2f3hm1ihnwgn/part/1/edit",
        Some("http://recogito.pelagios.org/rainer"),
        visitedAt,
        Client(
          "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36",
          "CHROME",
          "LINUX",
          "COMPUTER"
        ),
        "text/html",
        Some(VisitedItem(
          "fb2f3hm1ihnwgn",
          "rainer",
          Some(UUID.randomUUID),
          Some(ContentType.TEXT_PLAIN)
        )),
        Some(RuntimeAccessLevel.READ_ALL)
      )
        
      // Convert to JSON
      val serialized = Json.prettyPrint(Json.toJson(visit))
      
      val parseResult = Json.fromJson[Visit](Json.parse(serialized))
      parseResult.isSuccess must equalTo(true)
      parseResult.get must equalTo(visit)
    }
    
  }
  
} 
Example 145
Source File: TwitterBatchTimely.scala    From Mastering-Spark-for-Data-Science   with MIT License 5 votes vote down vote up
package io.gzet.timeseries

import java.sql.Timestamp

import com.cloudera.sparkts.{DateTimeIndex, TimeSeriesRDD}
import io.gzet.timeseries.timely.MetricImplicits._
import io.gzet.timeseries.timely.TimelyImplicits._
import io.gzet.timeseries.twitter.Twitter._
import io.gzet.utils.spark.accumulo.AccumuloConfig
import org.apache.spark.sql.SQLContext
import org.apache.spark.{SparkConf, SparkContext}
import org.joda.time.{DateTime, Minutes, Period}

object TwitterBatchTimely extends SimpleConfig {

  case class Observation(
                          hashtag: String,
                          time: Timestamp,
                          count: Double
                        )

  def main(args: Array[String]) = {

    val sparkConf = new SparkConf().setAppName("Twitter Extractor")
    val sc = new SparkContext(sparkConf)
    val sqlContext = new SQLContext(sc)
    import sqlContext.implicits._

    val twitterJsonRDD = sc.textFile("file:///Users/antoine/CHAPTER/twitter-trump", 500)
    val tweetRDD = twitterJsonRDD mapPartitions analyzeJson cache()

    // Publish metrics to Timely
    tweetRDD.count()
    tweetRDD.countByState.publish()
    tweetRDD.sentimentByState.publish()

    // Read metrics from Timely
    val conf = AccumuloConfig("GZET", "alice", "alice", "localhost:2181")
    val metricsRDD = sc.timely(conf, Some("io.gzet.count"))

    val minDate = metricsRDD.map(_.time).min()
    val maxDate = metricsRDD.map(_.time).max()

    class TwitterFrequency(val minutes: Int) extends com.cloudera.sparkts.PeriodFrequency(Period.minutes(minutes)) {
      def difference(dt1: DateTime, dt2: DateTime): Int = Minutes.minutesBetween(dt1, dt2).getMinutes / minutes
      override def toString: String = s"minutes $minutes"
    }

    val dtIndex = DateTimeIndex.uniform(minDate, maxDate, new TwitterFrequency(1))

    val metricsDF = metricsRDD.filter({
      metric =>
        metric.tags.keys.toSet.contains("tag")
    }).flatMap({
      metric =>
        metric.tags map {
          case (k, v) =>
            ((v, roundFloorMinute(metric.time, 1)), metric.value)
        }
    }).reduceByKey(_+_).map({
      case ((metric, time), sentiment) =>
        Observation(metric, new Timestamp(time), sentiment)
    }).toDF()

    val tsRDD = TimeSeriesRDD.timeSeriesRDDFromObservations(dtIndex, metricsDF, "time", "hashtag", "count").filter(_._2.toArray.exists(!_.isNaN))

  }

  def roundFloorMinute(time: Long, windowMinutes: Int) = {
    val dt = new DateTime(time)
    dt.withMinuteOfHour((dt.getMinuteOfHour / windowMinutes) * windowMinutes).minuteOfDay().roundFloorCopy().toDate.getTime
  }

} 
Example 146
Source File: BaseEndpoints.scala    From service-container   with Apache License 2.0 5 votes vote down vote up
package com.github.vonnagy.service.container.http

import akka.actor.ActorSystem
import akka.http.scaladsl.model.StatusCodes
import akka.japi.Util._
import com.github.vonnagy.service.container.http.directives.CIDRDirectives
import com.github.vonnagy.service.container.http.routing.RoutedEndpoints
import com.github.vonnagy.service.container.service.ServicesManager.ShutdownService
import org.joda.time.{DateTime, DateTimeZone}

import scala.concurrent.ExecutionContext
import scala.concurrent.duration._
import scala.util.{Failure, Success}

class BaseEndpoints(implicit system: ActorSystem, executor: ExecutionContext)
  extends RoutedEndpoints with CIDRDirectives {

  lazy val config = system.settings.config.getConfig("container.http")
  lazy val serviceActor = system.actorSelection("/user/service")

  implicit val marshaller = plainMarshaller

  val route = {
    path("favicon.ico") {
      complete(StatusCodes.NoContent)
    } ~
      path("ping") {
        complete("pong: ".concat(new DateTime(System.currentTimeMillis(), DateTimeZone.UTC).toString))
      } ~
      path("shutdown") {
        post {
          cidrFilter(immutableSeq(config.getStringList("cidr.allow")),
            immutableSeq(config.getStringList("cidr.deny"))) { ctx =>

            ctx.complete("The system is being shutdown: ".concat(new DateTime(System.currentTimeMillis(),
              DateTimeZone.UTC).toString)) andThen {
              case _ =>
                // Send a message to the root actor of this service
                serviceActor.resolveOne()(3 seconds).onComplete {
                  case Success(ref) => ref ! ShutdownService(true)
                  case Failure(_) => sys.exit()
                }
            }
          }
        }
      }
  }
} 
Example 147
Source File: HealthEndpoints.scala    From service-container   with Apache License 2.0 5 votes vote down vote up
package com.github.vonnagy.service.container.health

import akka.actor.ActorSystem
import akka.http.scaladsl.marshalling._
import akka.http.scaladsl.model.{MediaTypes, StatusCodes}
import akka.http.scaladsl.server._
import akka.japi.Util.immutableSeq
import com.github.vonnagy.service.container.http.DefaultMarshallers
import com.github.vonnagy.service.container.http.directives.CIDRDirectives
import com.github.vonnagy.service.container.http.routing.RoutedEndpoints
import org.joda.time.DateTime

import scala.concurrent.ExecutionContext
import scala.util.{Failure, Success, Try}



  def handleHealth[T <: ContainerHealth](loadBalancer: Boolean)(implicit marshaller: ToEntityMarshaller[AnyRef]):
  PartialFunction[Try[ContainerHealth], Route] = {

    case Success(check) =>
      check.state match {
        case HealthState.OK => complete(serialize(loadBalancer, check))
        case HealthState.DEGRADED => complete(serialize(loadBalancer, check))
        case HealthState.CRITICAL =>
          complete(StatusCodes.ServiceUnavailable -> serialize(loadBalancer, check))
      }

    case Failure(t) =>
      log.error("An error occurred while fetching the system's health", t)
      complete(StatusCodes.InternalServerError, ContainerHealth(ContainerInfo.host, ContainerInfo.application,
        ContainerInfo.applicationVersion, ContainerInfo.containerVersion,
        DateTime.now, HealthState.CRITICAL, t.getMessage, Nil))
  }

} 
Example 148
Source File: ElasticWriteConfig.scala    From elastic-indexer4s   with MIT License 5 votes vote down vote up
package com.yannick_cw.elastic_indexer4s.elasticsearch.elasic_config

import com.sksamuel.elastic4s.http.{ElasticClient, ElasticNodeEndpoint}
import org.apache.http.HttpHost
import org.elasticsearch.client.RestClient
import org.elasticsearch.client.sniff.Sniffer
import org.joda.time.DateTime

import scala.concurrent.duration.{FiniteDuration, _}

case class ElasticWriteConfig(
    elasticNodeEndpoints: List[ElasticNodeEndpoint],
    indexPrefix: String,
    docType: String,
    mappingSetting: MappingSetting = TypedMappingSetting(),
    writeBatchSize: Int = 50,
    writeConcurrentRequest: Int = 10,
    writeMaxAttempts: Int = 5,
    logWriteSpeedEvery: FiniteDuration = 1 minute,
    waitForElasticTimeout: FiniteDuration = 5 seconds,
    sniffCluster: Boolean = false
) {
  val indexName: String = indexPrefix + "_" + new DateTime().toString("yyyy-MM-dd't'HH:mm:ss")

  lazy val restClient: RestClient =
    RestClient
      .builder(elasticNodeEndpoints.map(e => new HttpHost(e.host, e.port, "http")): _*)
      .build()

  lazy val client: ElasticClient = {
    if (sniffCluster) {
      // sniffs every 5 minutes for the best hosts to connect to
      Sniffer.builder(restClient).build()
    }
    ElasticClient.fromRestClient(restClient)
  }
}

object ElasticWriteConfig {
  def apply(
      esNodeEndpoints: List[ElasticNodeEndpoint],
      esTargetIndexPrefix: String,
      esTargetType: String
  ): ElasticWriteConfig =
    new ElasticWriteConfig(esNodeEndpoints, esTargetIndexPrefix, esTargetType)
} 
Example 149
Source File: CreateIndexTest.scala    From stream-reactor   with Apache License 2.0 5 votes vote down vote up
package com.datamountaineer.streamreactor.connect.elastic6

import com.datamountaineer.kcql.Kcql
import com.datamountaineer.streamreactor.connect.elastic6.indexname.CreateIndex
import org.joda.time.{DateTime, DateTimeZone}
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec

class CreateIndexTest extends AnyWordSpec with Matchers {
  "CreateIndex" should {
    "create an index name without suffix when suffix not set" in {
      val kcql = Kcql.parse("INSERT INTO index_name SELECT * FROM topicA")
      CreateIndex.getIndexName(kcql) shouldBe "index_name"
    }

    "create an index name with suffix when suffix is set" in {
      val kcql = Kcql.parse("INSERT INTO index_name SELECT * FROM topicA WITHINDEXSUFFIX=_suffix_{YYYY-MM-dd}")

      val formattedDateTime = new DateTime(DateTimeZone.UTC).toString("YYYY-MM-dd")
      CreateIndex.getIndexName(kcql) shouldBe s"index_name_suffix_$formattedDateTime"
    }
  }
} 
Example 150
Source File: PurgeAwsCliAction.scala    From berilia   with Apache License 2.0 5 votes vote down vote up
package com.criteo.dev.cluster.aws

import com.criteo.dev.cluster.config.GlobalConfig
import com.criteo.dev.cluster.{CliAction, Public}
import org.jclouds.compute.domain.NodeMetadata
import org.jclouds.compute.domain.NodeMetadata.Status
import org.joda.time.DateTime
import org.scala_tools.time.Imports._
import org.slf4j.LoggerFactory


object PurgeAwsCliAction extends CliAction[Unit] {

  override def command: String = "purge"

  override def usageArgs: List[Any] = List()

  override def help: String = "Purge all expired Running clusters."

  override def isHidden = true

  private val logger = LoggerFactory.getLogger(PurgeAwsCliAction.getClass)

  override def applyInternal(args: List[String], config: GlobalConfig): Unit = {
    val currentTime = DateTime.now(DateTimeZone.UTC)
    val conf = config.backCompat

    logger.info(s"Running purge, current time is ${AwsUtilities.dtToString(currentTime)} (UTC)")
    val results = AwsUtilities.getAllClusters(conf).filter(c => c.master.getStatus.equals(Status.RUNNING))
    val toPurge = results.filter(c => isPurgable(c.master, currentTime))

    toPurge.foreach(u => {
      val nodeText = AwsUtilities.nodeInformation(conf, u.master)
      logger.info(s"Found node of user : ${AwsUtilities.getUser(u.master)}")
      logger.info(nodeText)
    })

    DestroyAwsCliAction.destroy(conf, toPurge)
  }

  def isPurgable(node: NodeMetadata, dt: DateTime) : Boolean = {
    val userMetadata = node.getUserMetadata
    val expireTime = userMetadata.get(AwsConstants.expireTime)
    if (expireTime == null) {
      //kill nodes without expire time
      return true
    }

    try {
      val date = AwsUtilities.stringToDt(expireTime)
      return date.isBefore(dt)
    } catch {
      //if expire time is corrupt, kill the node.
      case e: IllegalArgumentException => return true
    }
  }
} 
Example 151
Source File: GithubTagAndRelease.scala    From releaser   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.releaser.github

import org.joda.time.DateTime

import scala.util.Try

trait GithubTagAndRelease {

  def verifyGithubTagExists(repo: Repo, sha: CommitSha): Try[Unit]

  def createGithubTagAndRelease(tagDate: DateTime,
                                commitSha: CommitSha,
                                commitAuthor: String,
                                commitDate: DateTime,
                                artefactName: String,
                                gitRepo: Repo,
                                releaseCandidateVersion: String,
                                version: String,
                                releaseNotes: Option[String]): Try[Unit]

} 
Example 152
Source File: MetaDataProvider.scala    From releaser   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.releaser

import java.nio.file.Path
import java.util.jar.Manifest
import java.util.zip.ZipFile

import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import uk.gov.hmrc.releaser.github.CommitSha

import scala.collection.JavaConversions._
import scala.io.Source
import scala.util.{Failure, Success, Try}

trait MetaDataProvider {
  def fromJarFile(p: Path): Try[ArtefactMetaData]
  def fromCommitManifest(p: Path): Try[ArtefactMetaData]
}

case class ArtefactMetaData(sha:CommitSha, commitAuthor:String, commitDate:DateTime)

class ArtefactMetaDataProvider extends MetaDataProvider {
  import ArtefactMetaDataProvider._

  def fromJarFile(p: Path): Try[ArtefactMetaData] = {
    Try {new ZipFile(p.toFile) }.flatMap { jarFile =>
      jarFile.entries().filter(_.getName == "META-INF/MANIFEST.MF").toList.headOption.map { ze =>
        val man = new Manifest(jarFile.getInputStream(ze))
        ArtefactMetaData(
          man.getMainAttributes.getValue("Git-Head-Rev"),
          man.getMainAttributes.getValue("Git-Commit-Author"),
          gitCommitDateFormat.parseDateTime(man.getMainAttributes.getValue("Git-Commit-Date"))
        )
      }.toTry(new Exception(s"Failed to retrieve manifest from $p"))
    }
  }

  def fromCommitManifest(p: Path): Try[ArtefactMetaData] = {
    Try {
      val map = Source.fromFile(p.toFile)
        .getLines().toSeq
        .map(_.split("="))
        .map { case Array(key, value) => key.trim -> value.trim }.toMap

      ArtefactMetaData(map("sha"), map("author"),  gitCommitDateFormat.parseDateTime(map("date")))
    }
  }
}

object ArtefactMetaDataProvider {

  val gitCommitDateFormat = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")

  implicit class OptionPimp[A](opt: Option[A]){
    def toTry(e:Exception):Try[A] = opt match {
      case Some(x) => Success(x)
      case None => Failure(e)
    }
  }
} 
Example 153
Source File: Recommender.scala    From awesome-recommendation-engine   with Apache License 2.0 5 votes vote down vote up
package example.utils

import example.model.AmazonRating
import org.apache.spark.SparkContext
import org.apache.spark.mllib.recommendation.{ALS, Rating}
import org.joda.time.{Seconds, DateTime}
import scala.io.Source
import scala.util.Random

class Recommender(@transient sc: SparkContext, ratingFile: String) extends Serializable {
  val NumRecommendations = 10
  val MinRecommendationsPerUser = 10
  val MaxRecommendationsPerUser = 20
  val MyUsername = "myself"
  val NumPartitions = 20

  @transient val random = new Random() with Serializable

  println("Using this ratingFile: " + ratingFile)
  // first create an RDD out of the rating file
  val rawTrainingRatings = sc.textFile(ratingFile).map {
    line =>
      val Array(userId, productId, scoreStr) = line.split(",")
      AmazonRating(userId, productId, scoreStr.toDouble)
  }

  // only keep users that have rated between MinRecommendationsPerUser and MaxRecommendationsPerUser products
  val trainingRatings = rawTrainingRatings.groupBy(_.userId)
                                          .filter(r => MinRecommendationsPerUser <= r._2.size  && r._2.size < MaxRecommendationsPerUser)
                                          .flatMap(_._2)
                                          .repartition(NumPartitions)
                                          .cache()

  println(s"Parsed $ratingFile. Kept ${trainingRatings.count()} ratings out of ${rawTrainingRatings.count()}")

  // create user and item dictionaries
  val userDict = new Dictionary(MyUsername +: trainingRatings.map(_.userId).distinct.collect)
  println("User Dictionary have " + userDict.size + " elements.")
  val productDict = new Dictionary(trainingRatings.map(_.productId).distinct.collect)
  println("Product Dictionary have " + productDict.size + " elements.")

  private def toSparkRating(amazonRating: AmazonRating) = {
    Rating(userDict.getIndex(amazonRating.userId),
      productDict.getIndex(amazonRating.productId),
      amazonRating.rating)
  }

  private def toAmazonRating(rating: Rating) = {
    AmazonRating(userDict.getWord(rating.user),
      productDict.getWord(rating.product),
      rating.rating
    )
  }

  // convert to Spark Ratings using the dictionaries
  val sparkRatings = trainingRatings.map(toSparkRating)

  def getRandomProductId = productDict.getWord(random.nextInt(productDict.size))

  def predict(ratings: Seq[AmazonRating]) = {
    // train model
    val myRatings = ratings.map(toSparkRating)
    val myRatingRDD = sc.parallelize(myRatings)

    val startAls = DateTime.now
    val model = ALS.train((sparkRatings ++ myRatingRDD).repartition(NumPartitions), 10, 20, 0.01)

    val myProducts = myRatings.map(_.product).toSet
    val candidates = sc.parallelize((0 until productDict.size).filterNot(myProducts.contains))

    // get ratings of all products not in my history ordered by rating (higher first) and only keep the first NumRecommendations
    val myUserId = userDict.getIndex(MyUsername)
    val recommendations = model.predict(candidates.map((myUserId, _))).collect
    val endAls = DateTime.now
    val result = recommendations.sortBy(-_.rating).take(NumRecommendations).map(toAmazonRating)
    val alsTime = Seconds.secondsBetween(startAls, endAls).getSeconds

    println(s"ALS Time: $alsTime seconds")
    result
  }
} 
Example 154
Source File: ManifestUploader.scala    From teamcity-s3-plugin   with Apache License 2.0 5 votes vote down vote up
package com.gu.teamcity

import java.io.ByteArrayInputStream
import java.util.Date

import jetbrains.buildServer.messages.{BuildMessage1, DefaultMessagesInfo, Status}
import jetbrains.buildServer.serverSide.{BuildServerAdapter, SRunningBuild}
import org.joda.time.{DateTime, DateTimeZone}
import org.json4s.JsonAST.JObject
import org.json4s.JsonDSL._
import org.json4s.native.JsonMethods._

import scala.util.{Failure, Success}

class ManifestUploader(config: S3ConfigManager, s3: S3) extends BuildServerAdapter {

  override def beforeBuildFinish(runningBuild: SRunningBuild) {
    import scala.collection.convert.wrapAsScala._

    if (!runningBuild.isHasInternalArtifactsOnly) {
      val properties = Seq(
        "projectName" -> S3Plugin.cleanFullName(runningBuild),
        "buildNumber" -> runningBuild.getBuildNumber,
        "startTime" -> new DateTime(runningBuild.getStartDate).withZone(DateTimeZone.UTC).toString //Joda default is ISO8601
      ) ++ runningBuild.getRevisions.flatMap(revision => Seq(
        "revision" -> revision.getRevision,
        "vcsURL" -> revision.getRoot.getProperties.get("url")
      )) ++ Option(runningBuild.getBranch).map(b =>
        "branch" -> b.getDisplayName
      ).orElse(runningBuild.getVcsRootEntries.headOption.map(r =>
        "branch" -> r.getProperties.get("branch")
      ))

      val propertiesJSON = pretty(render(properties.foldLeft(JObject())(_ ~ _)))
      val jsBytes = propertiesJSON.getBytes("UTF-8")

      config.buildManifestBucket.map { bucket =>
        s3.upload(bucket, runningBuild, "build.json", new ByteArrayInputStream(jsBytes), jsBytes.length) match {			
          case Failure(e) => runningBuild.getBuildLog().message(s"Error uploading manifest: ${e.getMessage}",
              Status.ERROR,new Date,DefaultMessagesInfo.MSG_BUILD_FAILURE,DefaultMessagesInfo.SOURCE_ID,null)
          case Success(_) => runningBuild.getBuildLog().message("Manifest S3 upload complete",
              Status.NORMAL,new Date,DefaultMessagesInfo.MSG_TEXT,DefaultMessagesInfo.SOURCE_ID,null) 
        }
      }
    }
  }

  private def normalMessage(text: String) =
    new BuildMessage1(DefaultMessagesInfo.SOURCE_ID, DefaultMessagesInfo.MSG_TEXT, Status.NORMAL, new Date, text)
} 
Example 155
Source File: KafkaFlowExample.scala    From kafka-scala-api   with Apache License 2.0 5 votes vote down vote up
package com.example.flow

import org.apache.spark.streaming.dstream.DStream._
import org.apache.spark.streaming.dstream.{DStream, InputDStream}
import org.joda.time.DateTime
import org.json4s.DefaultFormats
import org.json4s.jackson.JsonMethods._

import scala.util.Try

case class Purchase(item_id: String, amount: BigDecimal, time: Long)
case class Key(item_id: String, time: DateTime)
case class Summary(item_id: String, time: DateTime, total: BigDecimal)

object KafkaFlowExample {
  implicit val formats = DefaultFormats

  def extract(message: String): Option[(Key, BigDecimal)] = {
    for {
      parsed <- Try(parse(message)).toOption
      purchase <- parsed.extractOpt[Purchase]
    } yield {
      val datetime = new DateTime(purchase.time)
      val roundedTime = datetime.withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0)
      Key(purchase.item_id, roundedTime) -> purchase.amount
    }
  }

  def transformStream(stream: InputDStream[String]): DStream[Summary] = {
    stream
      .flatMap(extract)
      .reduceByKey(_ + _)
      .map { case (key, amount) =>
        Summary(key.item_id, key.time, amount)
      }
  }
} 
Example 156
Source File: UserAuthService.scala    From akka-http-rest-api   with MIT License 5 votes vote down vote up
package authentication

import java.math.BigInteger
import java.security.SecureRandom

import authentication.UserAuthResult.{UserNotExists, UserExists, Success, InvalidData}
import core.authentication.Identity
import org.joda.time.DateTime
import org.mindrot.jbcrypt.BCrypt
import redis.RedisClient
import token.TokenRepository
import user.{UserRepository, User}
import core.authentication.UserSerializer._

import scala.concurrent.{Future, ExecutionContext}

class UserAuthService(tokenRepo: TokenRepository, userAuthRepo: UserAuthRepository, userRepo: UserRepository)
                     (implicit ec: ExecutionContext, redisClient: RedisClient) {

  def register(request: UserRegistrationRequest): Future[UserAuthResult] = {
    if (!RegistrationValidator.isDataValid(request.email, request.password)) {
      Future.successful(InvalidData("E-mail or password is invalid"))
    } else {
      userAuthRepo.findByUserEmail(request.email).flatMap {
        case Some(userAuth) => Future.successful(UserExists("E-mail already in use"))
        case None =>
          val now = DateTime.now().getMillis
          val token = generateToken
          for {
            user <- userRepo.insert(User(None, now, request.firstName, request.lastName, request.gender, None, None, None, request.role))
            _ <- userAuthRepo.insert(UserAuth(None, request.email, hashPassword(request.password), user.id.get))
            _ <- tokenRepo.insert(token, user.id.get)
            _ <- redisClient.setnx(token, Identity.User(user.id.get, user.role))
          } yield {
            Success(token)
          }
      }
    }
  }

  def login(request: UserLoginRequest): Future[UserAuthResult] = {
    userAuthRepo.findByUserEmail(request.email).flatMap {
      case Some(userAuth) if checkPassword(request.password, userAuth.password) =>
        val token = generateToken
        for {
          Some(user) <- userRepo.findByUserId(userAuth.userId)
          _ <- tokenRepo.insert(token, user.id.get)
          _ <- redisClient.setnx(token, Identity.User(user.id.get, user.role))
        } yield {
          Success(token)
        }
      case Some(_) => Future.successful(InvalidData("Password is invalid"))
      case None => Future.successful(UserNotExists("E-mail does not exist"))
    }
  }

  private lazy val random = new SecureRandom()

  private def generateToken: String = new BigInteger(255, random).toString(32)

  private def hashPassword(password: String): String = BCrypt.hashpw(password, BCrypt.gensalt(12))

  private def checkPassword(password: String, passwordHash: String): Boolean = BCrypt.checkpw(password, passwordHash)
}

trait UserAuthResult

object UserAuthResult {

  case class InvalidData(msg: String) extends UserAuthResult

  case class UserExists(msg: String) extends UserAuthResult

  case class UserNotExists(msg: String) extends UserAuthResult

  case class Success(token: String) extends UserAuthResult

} 
Example 157
Source File: RelationSpec.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package services.annotation.relation

import org.joda.time.{DateTime, DateTimeZone}
import org.joda.time.format.DateTimeFormat
import org.junit.runner._
import org.specs2.mutable._
import org.specs2.runner._
import play.api.test._
import play.api.test.Helpers._
import play.api.libs.json.Json
import scala.io.Source
import services.annotation.{Annotation, AnnotationBody}

@RunWith(classOf[JUnitRunner])
class RelationSpec extends Specification {
  
  private val DATE_TIME_PATTERN = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ")
  
  import services.annotation.BackendAnnotation._
  
  "The sample annotation" should {
  
    "be properly created from JSON" in {
      val json = Source.fromFile("test/resources/services/annotation/annotation-with-relation.json").getLines().mkString("\n")
      val result = Json.fromJson[Annotation](Json.parse(json))
      
      result.isSuccess must equalTo(true) 
      
      val relations = result.get.relations
      relations.size must equalTo(1)
      relations.head.bodies.size must equalTo(1)
      
      val body = relations.head.bodies.head
      body.hasType must equalTo(AnnotationBody.TAG)
      body.lastModifiedBy must equalTo(Some("rainer"))
      body.lastModifiedAt must equalTo(DateTime.parse("2018-05-07T15:31:00Z", DATE_TIME_PATTERN).withZone(DateTimeZone.UTC))
      body.value must equalTo("flyingTo")
    }
    
  }
  
} 
Example 158
Source File: UserRepositorySpec.scala    From akka-http-rest-api   with MIT License 5 votes vote down vote up
package user

import org.joda.time.DateTime
import org.scalatest.Matchers
import utils.FlatSpecWithSql

import scala.concurrent.ExecutionContext.Implicits.global

class UserRepositorySpec extends FlatSpecWithSql with Matchers {
  behavior of "UserRepository"

  val userRepo = new UserRepository

  it should "add new user" in {
    val user = User(None, DateTime.now().getMillis, "Jan", "Kowalski", 1, None, None, None, 0)
    val userId = userRepo.insert(user).futureValue.id.get
    userRepo.findByUserId(userId).futureValue should equal(Some(user.copy(id = Some(userId))))
  }

  it should "get users" in {
    for (i <- 1 to 30) {
      val now = DateTime.now().getMillis
      userRepo.insert(User(None, now, "Jan", "Kowalski" + i, 1, None, None, None, 0)).futureValue
    }

    userRepo.getUsers(0, 20).futureValue should have size 20
  }

  it should "get users with offset greater than 0" in {
    for (i <- 1 to 50) {
      val now = DateTime.now().getMillis
      userRepo.insert(User(None, now, "Jan", "Kowalski" + i, 1, None, None, None, 0)).futureValue
    }

    userRepo.getUsers(23, 20).futureValue.last.lastName should be("Kowalski43")
  }

  it should "update user" in {
    val user = User(None, DateTime.now().getMillis, "Jan", "Kowalski", 1, Some("Marszalkowska 12/123"), Some("12-345"), Some("Warsaw"), 0)
    val userId = userRepo.insert(user).futureValue.id.get

    val newUser = user.copy(
      id = Some(userId),
      firstName = "Kasia",
      lastName = "Nowak",
      gender = 0,
      streetAddress = Some("Krucza 12"),
      postalCode = Some("65-432"),
      postalCity = Some("Radom")
    )
    userRepo.update(userId, newUser.firstName, newUser.lastName, newUser.gender, newUser.streetAddress, newUser.postalCode, newUser.postalCity).futureValue

    userRepo.findByUserId(userId).futureValue should equal(Some(newUser))
  }

  it should "update user role" in {
    val user = User(None, DateTime.now().getMillis, "Jan", "Kowalski", 1, None, None, None, 0)
    val userId = userRepo.insert(user).futureValue.id.get

    userRepo.update(userId, 1).futureValue

    userRepo.findByUserId(userId).futureValue.map(_.role).get should be(1)
  }

  it should "delete user" in {
    val user = User(None, DateTime.now().getMillis, "Jan", "Kowalski", 1, None, None, None, 1)
    val userId = userRepo.insert(user).futureValue.id.get

    userRepo.delete(userId).futureValue

    userRepo.findByUserId(userId).futureValue should be(None)
  }
} 
Example 159
Source File: Tasks.scala    From sundial   with MIT License 5 votes vote down vote up
package controllers

import java.util.{Date, UUID}

import javax.inject.Inject
import com.hbc.svc.sundial.v2
import com.hbc.svc.sundial.v2.models.json._
import dao.SundialDaoFactory
import model.ReportedTaskStatus
import org.joda.time.DateTime
import play.api.libs.json.Json
import play.api.mvc.InjectedController
import util.Conversions._

class Tasks @Inject()(daoFactory: SundialDaoFactory)
    extends InjectedController {

  def get(processDefinitionName: String,
          taskDefinitionName: String,
          allowedStatuses: List[v2.models.TaskStatus],
          startTime: Option[DateTime],
          endTime: Option[DateTime],
          limit: Option[Int]) = Action {

    val allowedStatusTypes = {
      if (allowedStatuses.isEmpty) {
        None
      } else {
        Some(allowedStatuses.map(ModelConverter.toInternalTaskStatusType))
      }
    }
    val result = daoFactory.withSundialDao { implicit dao =>
      val tasks = dao.processDao.findTasks(Some(processDefinitionName),
                                           Some(taskDefinitionName),
                                           startTime,
                                           endTime,
                                           allowedStatusTypes,
                                           limit)
      tasks.map(ModelConverter.toExternalTask)
    }

    Ok(Json.toJson(result))
  }

  def postLogEntriesByTaskId(taskId: UUID) =
    Action(parse.json[List[v2.models.LogEntry]]) { request =>
      daoFactory.withSundialDao { implicit dao =>
        val events =
          request.body.map(ModelConverter.toInternalLogEntry(taskId, _))
        dao.taskLogsDao.saveEvents(events)
      }

      Created
    }

  def postMetadataByTaskId(taskId: UUID) =
    Action(parse.json[List[v2.models.MetadataEntry]]) { request =>
      daoFactory.withSundialDao { implicit dao =>
        val entries =
          request.body.map(ModelConverter.toInternalMetadataEntry(taskId, _))
        dao.taskMetadataDao.saveMetadataEntries(entries)
      }

      Created
    }

  def postSucceedByTaskId(taskId: UUID) = Action {
    daoFactory.withSundialDao { implicit dao =>
      dao.processDao.saveReportedTaskStatus(
        ReportedTaskStatus(taskId, model.TaskStatus.Success(new Date())))
    }

    Created
  }

  def postFailByTaskId(taskId: UUID) = Action {
    daoFactory.withSundialDao { implicit dao =>
      dao.processDao.saveReportedTaskStatus(ReportedTaskStatus(
        taskId,
        model.TaskStatus.Failure(new Date(), Some("Marked as failed via API"))))
    }

    Created
  }

} 
Example 160
Source File: GraphDatapoint.scala    From cave   with MIT License 5 votes vote down vote up
package com.gilt.cavellc.models

import org.joda.time.DateTime
import org.joda.time.format.ISODateTimeFormat
import org.joda.time.format.ISODateTimeFormat._
import play.api.libs.functional.syntax._
import play.api.libs.json._

case class GraphDatapoint(timestamp: DateTime, value: Option[Double])

object GraphDatapoint {
  implicit val datetimeWrites = new Writes[DateTime] {
    def writes(value: DateTime) = JsString(dateTime.print(value))
  }

  implicit val graphDataWrites: Writes[GraphDatapoint] = (
    (__ \ "ts").write[DateTime] and
      (__ \ "value").write[Option[Double]]
    )(unlift(GraphDatapoint.unapply))

  def parseDateTime(dateString: Option[String]): Option[DateTime] =
    dateString map ISODateTimeFormat.timeNoMillis().parseDateTime
} 
Example 161
Source File: Bindables.scala    From cave   with MIT License 5 votes vote down vote up
package com.gilt.cavellc.models

object Bindables {

  import org.joda.time.format.ISODateTimeFormat
  import org.joda.time.{DateTime, LocalDate}
  import play.api.mvc.{PathBindable, QueryStringBindable}

  // Type: date-time-iso8601
  implicit val pathBindableTypeDateTimeIso8601 = new PathBindable.Parsing[DateTime](
    ISODateTimeFormat.dateTimeParser.parseDateTime(_), _.toString, (key: String, e: Exception) => s"Error parsing date time $key. Example: 2014-04-29T11:56:52Z"
  )

  // Type: date-time-iso8601
  implicit val queryStringBindableTypeDateTimeIso8601 = new QueryStringBindable.Parsing[DateTime](
    ISODateTimeFormat.dateTimeParser.parseDateTime(_), _.toString, (key: String, e: Exception) => s"Error parsing date time $key. Example: 2014-04-29T11:56:52Z"
  )

  // Type: date-iso8601
  implicit val pathBindableTypeDateIso8601 = new PathBindable.Parsing[LocalDate](
    ISODateTimeFormat.yearMonthDay.parseLocalDate(_), _.toString, (key: String, e: Exception) => s"Error parsing date time $key. Example: 2014-04-29"
  )

  // Enum: Role
  private val enumRoleNotFound = (key: String, e: Exception) => s"Unrecognized $key, should be one of ${Role.all.mkString(", ")}"

  private val enumAggregatorNotFound = (key: String, e: Exception) => s"Unrecognized $key, should be one of ${Aggregator.all.mkString(", ")}"

  implicit val pathBindableEnumRole = new PathBindable.Parsing[Role](
    Role.fromString(_).get, _.toString, enumRoleNotFound
  )

  implicit val queryStringBindableEnumRole = new QueryStringBindable.Parsing[Role](
    Role.fromString(_).get, _.toString, enumRoleNotFound
  )

  implicit val queryStringBindableAggregator = new QueryStringBindable.Parsing[Aggregator](
    Aggregator.fromString(_).get, _.toString, enumAggregatorNotFound
  )

} 
Example 162
Source File: Status.scala    From cave   with MIT License 5 votes vote down vote up
package controllers

import org.joda.time.DateTime
import scala.concurrent.ExecutionContext.Implicits.global

case class IssueData(description: String, since: DateTime, until: Option[DateTime])

class Status extends AbstractCaveController {

  def status = caveAsyncAction { implicit request =>
    withCaveClient { client =>
      client.Statuses.getStatus() map {
        case Some(status) =>
          val currentIssues = status.current.map(issue => IssueData(issue.description, issue.since, issue.until))
          val recentIssues = status.recent.map(issue => IssueData(issue.description, issue.since, issue.until))
          Ok(views.html.status.statusFragment(currentIssues, recentIssues))
        case None =>
          Ok(views.html.status.statusFragment(Seq.empty, Seq.empty))
      }
    }
  }
} 
Example 163
Source File: GraphDataSpec.scala    From cave   with MIT License 5 votes vote down vote up
package controllers

import org.joda.time.{DateTime, Period}
import org.scalatest.{BeforeAndAfter, FlatSpec, Matchers}

class GraphDataSpec extends FlatSpec with Matchers with BeforeAndAfter {

  "Metric Time Range" should "find the first data point timestamp" in {
    val graphs = new Graphs
    val now = new DateTime()

    val period = Period.minutes(3)
    val firstResultTimestampFromDb = now.minusDays(1)
    val startTimeRange = now.minusDays(2)

    val start = graphs.findStartDate(firstResultTimestampFromDb, startTimeRange, period)

    println(s"FIRST RESULT TIME=      $firstResultTimestampFromDb")
    println(s"START TIME RANGE=       $startTimeRange")
    println(s"CALCULATED START TIME=  $start")

    assert(firstResultTimestampFromDb.toDate.getTime >= startTimeRange.toDate.getTime, "FIRST RESULT Start time is NOT after expected Start time range")
    assert(firstResultTimestampFromDb.toDate.getTime >= start.toDate.getTime, "FIRST RESULT Start time is NOT after expected CALCULATED Start time")

    assert(start.toDate.getTime >= startTimeRange.toDate.getTime, "Start time is NOT after expected CALCULATED Start time")
    assert(start.minus(period).toDate.getTime <= startTimeRange.toDate.getTime, "Start time MINUS PERIOD is NOT before expected Start time")

  }

  it should "find the first data point timestamp when the first DB result timestamp is the same as the beginning of the time range" in {
    val graphs = new Graphs
    val now = new DateTime()

    val period = Period.minutes(3)
    val firstResultTimestampFromDb = now.minusDays(1)
    val startTimeRange = firstResultTimestampFromDb

    val start = graphs.findStartDate(firstResultTimestampFromDb, startTimeRange, period)

    println(s"FIRST RESULT TIME=      $firstResultTimestampFromDb")
    println(s"START TIME RANGE=       $startTimeRange")
    println(s"CALCULATED START TIME=  $start")

    assert(firstResultTimestampFromDb.toDate.getTime >= startTimeRange.toDate.getTime, "FIRST RESULT Start time is NOT after expected Start time range")
    assert(firstResultTimestampFromDb.toDate.getTime >= start.toDate.getTime, "FIRST RESULT Start time is NOT after expected CALCULATED Start time")

    assert(start.toDate.getTime >= startTimeRange.toDate.getTime, "Start time is NOT after expected CALCULATED Start time")
    assert(start.minus(period).toDate.getTime <= startTimeRange.toDate.getTime, "Start time MINUS PERIOD is NOT before expected Start time")
    assert(start.isEqual(startTimeRange))
  }

  it should "find the first expected result time when the first result date is the same as the start" in {
    val graphs = new Graphs
    val now = new DateTime()

    val period = Period.minutes(3)
    val firstResultTimestampFromDb = now.minusDays(1)
    val startTimeRange = firstResultTimestampFromDb.plus(period)

    val start = graphs.findStartDate(firstResultTimestampFromDb, startTimeRange, period)

    println(s"FIRST RESULT TIME=      $firstResultTimestampFromDb")
    println(s"START TIME RANGE=       $startTimeRange")
    println(s"CALCULATED START TIME=  $start")

    assert(firstResultTimestampFromDb.toDate.getTime >= start.toDate.getTime, "FIRST RESULT Start time is NOT after expected CALCULATED Start time")
    assert(start.minus(period).toDate.getTime <= startTimeRange.toDate.getTime, "Start time MINUS PERIOD is NOT before expected Start time")
    assert(start.isEqual(firstResultTimestampFromDb))
  }

} 
Example 164
Source File: DeleteOrganizationMetricsApiSpec.scala    From cave   with MIT License 5 votes vote down vote up
import com.cave.metrics.data.Role
import data.UserData
import org.joda.time.DateTime
import org.mockito.Matchers._
import org.mockito.{Matchers, Mockito}
import org.mockito.Mockito._
import play.api.mvc.Results
import play.api.test.{FakeRequest, FakeApplication, PlaySpecification}
import scala.concurrent.{Future, ExecutionContext}
import scala.Some
import scala.util.Success

class DeleteOrganizationMetricsApiSpec extends PlaySpecification with Results with AbstractMetricsApiSpec with UserData {

  val MetricName = "metric"
  val organization = GiltOrg
  val user = SOME_USER

  "DELETE /organizations/:name/metric-names/:metric" should {
    "respond with 204 when deletion succeeds" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Admin)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockClient.deleteMetric(s"${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(true))

      val result = new TestController().deleteOrganizationMetric(organization.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN))
      status(result) must equalTo(NO_CONTENT)
      contentAsString(result) must equalTo("")
    }

    "respond with 404 when metric doesn't exist" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Admin)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockClient.deleteMetric(s"${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(false))

      val result = new TestController().deleteOrganizationMetric(organization.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN))
      status(result) must equalTo(NOT_FOUND)
    }

    "respond with 403 when it's not an admin user" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Member)))

      val result = new TestController().deleteOrganizationMetric(organization.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN))
      status(result) must equalTo(FORBIDDEN)
    }
  }
} 
Example 165
Source File: DeleteOrganizationMetricsShortcutApiSpec.scala    From cave   with MIT License 5 votes vote down vote up
import com.cave.metrics.data.Role
import data.UserData
import org.joda.time.DateTime
import org.mockito.Matchers._
import org.mockito.{Matchers, Mockito}
import org.mockito.Mockito._
import play.api.mvc.Results
import play.api.test.{FakeRequest, FakeApplication, PlaySpecification}
import scala.concurrent.{Future, ExecutionContext}
import scala.Some
import scala.util.Success

class DeleteOrganizationMetricsShortcutApiSpec extends PlaySpecification with Results with AbstractMetricsApiSpec with UserData {

  val MetricName = "metric"
  val organization = GiltOrg
  val user = SOME_USER

  "DELETE /metric-names/:metric" should {
    "respond with 204 when metric exists" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Admin)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockClient.deleteMetric(s"${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(true))

      val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName").
        withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${organization.name}.$BaseUrl"))
      status(result) must equalTo(NO_CONTENT)
      contentAsString(result) must equalTo("")
    }

    "respond with 404 when metric doesn't exist" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Admin)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockClient.deleteMetric(s"${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(false))

      val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName").
        withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${organization.name}.$BaseUrl"))
      status(result) must equalTo(NOT_FOUND)
    }

    "respond with 403 when it's not an admin user" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Member)))

      val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName").
        withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${organization.name}.$BaseUrl"))
      status(result) must equalTo(FORBIDDEN)
    }
  }
} 
Example 166
Source File: DeleteTeamMetricsShortcutApiSpec.scala    From cave   with MIT License 5 votes vote down vote up
import com.cave.metrics.data.Role
import data.UserData
import org.joda.time.DateTime
import org.mockito.Matchers._
import org.mockito.{Matchers, Mockito}
import org.mockito.Mockito._
import play.api.mvc.Results
import play.api.test.{FakeRequest, FakeApplication, PlaySpecification}
import scala.concurrent.{Future, ExecutionContext}
import scala.Some
import scala.util.Success

class DeleteTeamMetricsShortcutApiSpec extends PlaySpecification with Results with AbstractMetricsApiSpec with UserData {

  val MetricName = "metric"
  val organization = GiltOrg
  val team = GiltTeam
  val user = SOME_USER

  "DELETE /metric-names/:metric" should {
    "respond with 204 when metric exists" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team)))
      when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Admin)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockClient.deleteMetric(s"${team.name}.${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(true))

      val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName").
        withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${team.name}.${organization.name}.$BaseUrl"))
      status(result) must equalTo(NO_CONTENT)
      contentAsString(result) must equalTo("")
    }

    "respond with 404 metric doesn't exist" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team)))
      when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Admin)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockClient.deleteMetric(s"${team.name}.${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(false))

      val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName").
        withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${team.name}.${organization.name}.$BaseUrl"))
      status(result) must equalTo(NOT_FOUND)
    }

    "work for org admins" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team)))
      when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Member)))
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Admin)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockClient.deleteMetric(s"${team.name}.${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(true))

      val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName").
        withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${team.name}.${organization.name}.$BaseUrl"))
      status(result) must equalTo(NO_CONTENT)
    }

    "respond with 403 when it's not an admin user" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team)))
      when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Member)))
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Member)))

      val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName").
        withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${team.name}.${organization.name}.$BaseUrl"))
      status(result) must equalTo(FORBIDDEN)
    }
  }
} 
Example 167
Source File: DeleteTeamMetricsApiSpec.scala    From cave   with MIT License 5 votes vote down vote up
import com.cave.metrics.data.Role
import data.UserData
import org.joda.time.DateTime
import org.mockito.Matchers._
import org.mockito.{Matchers, Mockito}
import org.mockito.Mockito._
import play.api.mvc.Results
import play.api.test.{FakeRequest, FakeApplication, PlaySpecification}
import scala.concurrent.{Future, ExecutionContext}
import scala.Some
import scala.util.Success

class DeleteTeamMetricsApiSpec extends PlaySpecification with Results with AbstractMetricsApiSpec with UserData {

  val MetricName = "metric"
  val organization = GiltOrg
  val team = GiltTeam
  val user = SOME_USER

  "DELETE /organizations/:name/teams/:team/metric-names/:metric" should {
    "respond with 204 when deletion succeeds" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team)))
      when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Admin)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockClient.deleteMetric(s"${team.name}.${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(true))

      val result = new TestController().deleteTeamMetric(organization.name, team.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/teams/${team.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN))
      status(result) must equalTo(NO_CONTENT)
      contentAsString(result) must equalTo("")
    }

    "respond with 404 when metric doesn't exist" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team)))
      when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Admin)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockClient.deleteMetric(s"${team.name}.${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(false))

      val result = new TestController().deleteTeamMetric(organization.name, team.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/teams/${team.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN))
      status(result) must equalTo(NOT_FOUND)
    }

    "work for org admins" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team)))
      when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Member)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Admin)))
      when(mockClient.deleteMetric(s"${team.name}.${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(true))

      val result = new TestController().deleteTeamMetric(organization.name, team.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/teams/${team.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN))
      status(result) must equalTo(NO_CONTENT)
    }

    "respond with 403 when it's not an admin user" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team)))
      when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Member)))
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Member)))

      val result = new TestController().deleteTeamMetric(organization.name, team.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/teams/${team.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN))
      status(result) must equalTo(FORBIDDEN)
    }
  }
} 
Example 168
Source File: Scheduler.scala    From cave   with MIT License 5 votes vote down vote up
package actors

import java.util.concurrent.{Executor, TimeUnit}

import akka.actor.{Actor, ActorLogging}
import akka.pattern.ask
import akka.util.Timeout
import com.cave.metrics.data.evaluator.AlertParser
import com.cave.metrics.data.{Check, Schedule}
import init.{AwsWrapper, Init}
import org.joda.time.format.ISODateTimeFormat
import org.joda.time.{Minutes, LocalTime, DateTime, DateTimeZone}

import scala.concurrent.ExecutionContext
import scala.concurrent.duration._

object Scheduler {
  object DoWork
  object Die
  case class NotificationUrlChange(newUrl: String)
}
class Scheduler(schedule: Schedule, awsWrapper: AwsWrapper) extends Actor with ActorLogging with AlertParser {

  private[actors] def leader = Init.leader
  var notificationUrl: String = schedule.notificationUrl
  implicit val timeout = Timeout(2, TimeUnit.SECONDS)

  val (waitTime, period) = getSchedule(schedule.alert.period)

  val Formatter = ISODateTimeFormat.dateTimeNoMillis()

  implicit val executor = context.dispatcher.asInstanceOf[Executor with ExecutionContext]
  private val queueCheckSchedule = context.system.scheduler.schedule(waitTime, period, self, Scheduler.DoWork)

  override def receive = {
    case Scheduler.DoWork =>
      leader ? Leadership.IsLeader onComplete {
        case scala.util.Success(imLeader: Boolean) =>
          if (imLeader) {
            awsWrapper.sendMessage(Check(Schedule(schedule.orgName, schedule.teamName, schedule.clusterName, notificationUrl, schedule.alert), now()))
          }

        case scala.util.Success(e) =>
          log.error("Unexpected result returned by the leader actor: " + e)

        case scala.util.Failure(t) =>
          log.error("Failed to query the leader actor, error was " + t)
      }


    case Scheduler.NotificationUrlChange(url) =>
      log.debug(s"Updating the notification URL, from $notificationUrl to $url.")
      notificationUrl = url

    case Scheduler.Die =>
      context stop self
  }

  override def postStop(): Unit = queueCheckSchedule.cancel()

  
  private[actors] def getSchedule(alertPeriod: String): (FiniteDuration, FiniteDuration) =
    parseAll(duration, alertPeriod) match {
      case Success(p, _) => (0.minutes, p)

      case NoSuccess(_, message) =>
        parseAll(daily, alertPeriod) match {
          case Success(time, _) => (getWait(nowLocal(), time), 1.day)

          case NoSuccess(_, message2) =>
            sys.error(s"Unexpected alert period $alertPeriod. Not a duration ($message) and not a daily scheduler ($message2).")
        }
    }

  private[actors] def getWait(now: LocalTime, until: LocalTime): FiniteDuration = {
    val wait = Minutes.minutesBetween(now, until).getMinutes
    val minutes = if (wait < 0) 1440 + wait else wait
    minutes.minutes
  }
} 
Example 169
Source File: ConditionEvaluator.scala    From cave   with MIT License 5 votes vote down vote up
package com.cave.metrics.data.evaluator

import com.cave.metrics.data.influxdb.InfluxClientFactory
import com.cave.metrics.data.{MetricCheckRequest, MetricData, MetricDataBulk}
import org.joda.time.{DateTime, Period}

import scala.concurrent.duration.FiniteDuration
import scala.concurrent.{ExecutionContext, Future}

class ConditionEvaluator(clusterName: Option[String], databaseName: String, request: MetricCheckRequest) extends AbstractEvaluator(request.condition) {

  def evaluate(clientFactory: InfluxClientFactory)(implicit ec: ExecutionContext): Future[Option[MetricDataBulk]] = {

    val fetcher = new DataFetcher(clientFactory)
    val step = Period.minutes(request.interval)
    val dateRange = Iterator.iterate(request.start)(_.plus(step)).takeWhile(!_.isAfter(request.end))

    def evaluateOnce(rangeStartDate: DateTime): Future[Option[MetricData]] = {
      val rangeEndDate = rangeStartDate.plus(step).minusSeconds(1)

      evaluateRange(clusterName, databaseName, rangeEndDate)(fetcher, ec) map {
        case util.Success(value) =>
          Some(MetricData(rangeStartDate, if (value) 1.0 else 0.0))
        case _ => None
      }
    }

    // If the result of one evaluation is None, it means the metric does not exist!
    // In that case, there's no point in evaluating any other dates in the range.
    evaluateOnce(dateRange.next()) flatMap {
      case Some(value) =>
        val results = dateRange map evaluateOnce
        Future.sequence(results) map(seq => Some(MetricDataBulk(value +: seq.flatten.toSeq)))

      case None =>
        Future.successful(None)
    }
  }

  override def getData(clusterName: Option[String], databaseName: String, metricName: String,
                       metricTags: Map[String, String], repeats: Int, delay: FiniteDuration, end: DateTime)
                      (implicit fetcher: DataFetcher, ec: ExecutionContext): Future[Option[List[Double]]] =
    fetcher.fetchData(clusterName, databaseName, metricName, metricTags, repeats, delay, end)(ec)

  override def getData(clusterName: Option[String], databaseName: String, metricName: String,
                       metricTags: Map[String, String], duration: FiniteDuration, end: DateTime)
                      (implicit fetcher: DataFetcher, ec: ExecutionContext): Future[Option[List[Double]]] =
    fetcher.fetchData(clusterName, databaseName, metricName, metricTags, duration, end)(ec)

  override def getData(clusterName: Option[String], databaseName: String, agg: AggregatedSource, repeats: Int, delay: FiniteDuration, end: DateTime)
                      (implicit fetcher: DataFetcher, ec: ExecutionContext): Future[Option[List[Double]]] =
    fetcher.fetchData(clusterName, databaseName, Aggregator.toInflux(agg.aggregator),
      agg.duration, agg.metricSource.metric, agg.metricSource.tags, repeats, delay, end)(ec)
} 
Example 170
Source File: Engine.scala    From pio-template-fpm   with Apache License 2.0 5 votes vote down vote up
package org.template.fpm



import org.apache.predictionio.controller.{Engine,EngineFactory}
import org.joda.time.DateTime

case class Query(
  val items: Array[String]
) extends Serializable

case class PredictedResult(
  consequentItems: Array[ConsequentItem]
) extends Serializable {
  override def toString: String = consequentItems.mkString(",")
}

case class ConsequentItem(
  items: Array[String],
  confidence: Double
) extends Serializable

object FPMEngine extends EngineFactory {
  def apply() = {
    new Engine(
      classOf[DataSource],
      classOf[Preparator],
      Map("fpg" -> classOf[FPGAlgorithm]),
      	classOf[Serving])
  }
} 
Example 171
Source File: DateTimeSerializer.scala    From scaladex   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package ch.epfl.scala.index
package data

import org.json4s._

import org.joda.time.DateTime
import org.joda.time.format.ISODateTimeFormat


object DateTimeSerializer
    extends CustomSerializer[DateTime](
      format =>
        (
          {
            case JString(dateTime) => {
              val parser = ISODateTimeFormat.dateTimeParser
              parser.parseDateTime(dateTime)
            }
          }, {
            case dateTime: DateTime => {
              val formatter = ISODateTimeFormat.dateTime
              JString(formatter.print(dateTime))
            }
          }
      )
    ) 
Example 172
Source File: Meta.scala    From scaladex   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package ch.epfl.scala.index
package data

import java.nio.charset.StandardCharsets
import java.nio.file.Files

import ch.epfl.scala.index.model.Descending
import com.github.nscala_time.time.Imports._
import jawn.support.json4s.Parser
import org.joda.time.DateTime
import org.json4s._
import org.json4s.native.Serialization.{write => swrite}

case class Meta(
    sha1: String,
    path: String,
    created: DateTime
)

object Meta {

  
  object MetaSerializer
      extends CustomSerializer[Meta](
        format =>
          (
            {
              case in: JValue => {
                implicit val formats = DefaultFormats ++ Seq(
                  DateTimeSerializer
                )
                in.extract[Meta]
              }
            }, {
              case meta: Meta => {
                implicit val formats = DefaultFormats ++ Seq(
                  DateTimeSerializer
                )
                JObject(
                  JField("created", Extraction.decompose(meta.created)),
                  JField("path", Extraction.decompose(meta.path)),
                  JField("sha1", Extraction.decompose(meta.sha1))
                )
              }
            }
        )
      )

  implicit val formats = DefaultFormats ++ Seq(DateTimeSerializer,
                                               MetaSerializer)
  implicit val serialization = native.Serialization

  def load(paths: DataPaths, repository: LocalPomRepository): List[Meta] = {
    assert(
      repository == LocalPomRepository.MavenCentral ||
        repository == LocalPomRepository.UserProvided
    )

    val metaPath = paths.meta(repository)
    val metaRaw = new String(Files.readAllBytes(metaPath))

    metaRaw
      .split('\n')
      .toList
      .filter(_ != "")
      .map(json => Parser.parseUnsafe(json).extract[Meta])
      .sortBy(_.created)(Descending)
  }

  def append(paths: DataPaths,
             meta: Meta,
             repository: LocalPomRepository): Unit = {
    val all = load(paths, repository)
    write(paths, meta :: all, repository)
  }

  def write(paths: DataPaths,
            metas: List[Meta],
            repository: LocalPomRepository): Unit = {
    val sorted = metas.sortBy(_.created)(Descending)
    val jsonPerLine =
      sorted
        .map(s => swrite(s))
        .mkString("", "\n", "\n")

    val metaPath = paths.meta(repository)

    if (Files.exists(metaPath)) {
      Files.delete(metaPath)
    }

    Files.write(metaPath, jsonPerLine.getBytes(StandardCharsets.UTF_8))
    ()
  }
} 
Example 173
Source File: BintrayProtocol.scala    From scaladex   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package ch.epfl.scala.index
package data
package bintray

import org.json4s._
import org.joda.time.DateTime

case class BintraySearch(
    sha1: String,
    sha256: Option[String],
    `package`: String,
    name: String,
    path: String,
    size: Int,
    version: String,
    owner: String,
    repo: String,
    created: String
) {
  def isJCenter = repo == "jcenter" && owner == "bintray"
}


  object BintraySearchSerializer
      extends CustomSerializer[BintraySearch](
        format =>
          (
            {
              case in: JValue => {
                implicit val formats = DefaultFormats ++ Seq(
                  DateTimeSerializer
                )
                in.extract[BintraySearch]
              }
            }, {
              case search: BintraySearch => {
                implicit val formats = DefaultFormats ++ Seq(
                  DateTimeSerializer
                )
                JObject(
                  JField("created", Extraction.decompose(search.created)),
                  JField("package", Extraction.decompose(search.`package`)),
                  JField("owner", Extraction.decompose(search.owner)),
                  JField("repo", Extraction.decompose(search.repo)),
                  JField("sha1", Extraction.decompose(search.sha1)),
                  JField("sha256", Extraction.decompose(search.sha256)),
                  JField("name", Extraction.decompose(search.name)),
                  JField("path", Extraction.decompose(search.path)),
                  JField("size", Extraction.decompose(search.size)),
                  JField("version", Extraction.decompose(search.version))
                )
              }
            }
        )
      )
} 
Example 174
Source File: SbtPluginsData.scala    From scaladex   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package ch.epfl.scala.index.data.bintray

import java.nio.file.{Files, Path}

import ch.epfl.scala.index.data.LocalRepository
import ch.epfl.scala.index.data.LocalRepository.BintraySbtPlugins
import ch.epfl.scala.index.data.maven._
import jawn.support.json4s.Parser
import org.apache.ivy.core.module.descriptor.ModuleDescriptor
import org.joda.time.DateTime
import org.json4s.native.Serialization.write

case class SbtPluginsData(ivysData: Path) extends BintrayProtocol {

   None,
          exclusions = dependency.getAllExcludeRules
            .map(_.getId.getModuleId)
            .map(rule => Exclusion(rule.getOrganisation, rule.getName))
            .toSet
        )
      },
      sbtPluginTarget = Some(
        SbtPluginTarget(scalaVersion, sbtVersion)
      )
    )

    val publicationDate = new DateTime(descriptor.getPublicationDate).toString
    new SbtPluginReleaseModel(releaseModel, publicationDate, sha1)
  }

} 
Example 175
Source File: PublishData.scala    From scaladex   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package ch.epfl.scala.index
package server
package routes
package api
package impl

import data.{DataPaths, LocalPomRepository}
import data.github
import ch.epfl.scala.index.model.misc.Sha1
import org.joda.time.DateTime
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Path, Paths}

import org.slf4j.LoggerFactory

import scala.util.control.NonFatal


  private def tmpPath(sha1: String): Path = {
    val tmpDir =
      Files.createTempDirectory(Paths.get(Server.config.tempDirPath), sha1)
    Files.createTempFile(tmpDir, "", "")
  }
} 
Example 176
Source File: Models.scala    From swagger-finatra   with Apache License 2.0 5 votes vote down vote up
package com.github.xiaodongw.swagger.finatra

import com.twitter.finagle.http.Request
import com.twitter.finatra.request.{QueryParam, RouteParam}
import io.swagger.annotations.{ApiModel, ApiModelProperty}
import javax.inject.Inject
import org.joda.time.{DateTime, LocalDate}

@ApiModel(value="AddressModel", description="Sample address model for documentation")
case class Address(street: String, zip: String)

case class Student(firstName: String, lastName: String, gender: Gender, birthday: LocalDate, grade: Int, address: Option[Address])

case class StudentWithRoute(
  @RouteParam
  @ApiModelProperty(name = "student_id", value = "Id of the student")
  id: String,
  @Inject request: Request,
  firstName: String,
  lastName: String,
  gender: Gender,
  birthday: LocalDate,
  grade: Int,
  emails: Array[String],
  address: Option[Address]
)

case class StringWithRequest(
  @Inject request: Request,
  firstName: String
)

object CourseType extends Enumeration {
  val LEC, LAB = Value
}

case class Course(time: DateTime,
                  name: String,
                  @ApiModelProperty(required = false, example = "[math,stem]")
                  tags: Seq[String],
                  @ApiModelProperty(dataType = "string", allowableValues = "LEC,LAB")
                  typ: CourseType.Value,
                  @ApiModelProperty(readOnly = true)
                  capacity: Int,
                  @ApiModelProperty(dataType = "double", required = true)
                  cost: BigDecimal) 
Example 177
Source File: HatSignup.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.resourceManagement.models

import java.util.UUID

import org.joda.time.DateTime
import play.api.libs.json.Json

case class DatabaseInstance(id: UUID, name: String, password: String)

case class DatabaseServer(id: Int, host: String, port: Int, dateCreated: DateTime, databases: Seq[DatabaseInstance])

case class HatKeys(
    privateKey: String,
    publicKey: String)

case class HatSignup(
    id: UUID,
    fullName: String,
    username: String,
    email: String,
    pass: String,
    dbPass: String,
    created: Boolean,
    registerTime: DateTime,
    database: Option[DatabaseInstance],
    databaseServer: Option[DatabaseServer],
    keys: Option[HatKeys])

object HatSignup {
  import play.api.libs.json.JodaWrites._
  import play.api.libs.json.JodaReads._

  implicit val databaseInstanceFormat = Json.format[DatabaseInstance]
  implicit val databaseServerFormat = Json.format[DatabaseServer]
  implicit val hatKeysFormat = Json.format[HatKeys]
  implicit val hatSignupFormat = Json.format[HatSignup]
} 
Example 178
Source File: FunctionExecutable.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.she.models

import org.hatdex.hat.api.models.EndpointDataBundle
import org.joda.time.DateTime

import scala.concurrent.Future

trait FunctionExecutable {
  val configuration: FunctionConfiguration
  val namespace: String
  val endpoint: String
  def execute(configuration: FunctionConfiguration, request: Request): Future[Seq[Response]]
  def bundleFilterByDate(fromDate: Option[DateTime], untilDate: Option[DateTime]): Future[EndpointDataBundle] = {
    // Explicitly ignore the parameters - compiler complains about unused parameters
    (fromDate, untilDate)
    Future.successful(configuration.dataBundle)
  }
}

class SHEException(message: String = "", cause: Throwable = None.orNull) extends RuntimeException(message, cause)
case class SHEFunctionNotAvailableException(message: String = "", cause: Throwable = None.orNull) extends SHEException(message, cause)
case class SHEFunctionBusyExecutingException(message: String = "", cause: Throwable = None.orNull) extends SHEException(message, cause)
case class SHEFunctionExecutionFailureException(message: String = "", cause: Throwable = None.orNull) extends SHEException(message, cause) 
Example 179
Source File: UberMappers.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.she.mappers

import java.util.UUID

import org.hatdex.hat.api.models.{ EndpointQuery, EndpointQueryFilter, FilterOperator, PropertyQuery }
import org.hatdex.hat.api.models.applications.{ DataFeedItem, DataFeedItemContent, DataFeedItemLocation, DataFeedItemTitle, LocationGeo }
import org.hatdex.hat.she.models.StaticDataValues
import org.joda.time.DateTime
import play.api.libs.json.{ JsError, JsSuccess, JsValue, Json }

import scala.util.Try

class UberRidesMapper extends DataEndpointMapper {
  override protected val dataDeduplicationField: Option[String] = Some("request_id")

  def dataQueries(fromDate: Option[DateTime], untilDate: Option[DateTime]): Seq[PropertyQuery] = {
    val unixDateFilter = fromDate.flatMap { _ =>
      Some(FilterOperator.Between(Json.toJson(fromDate.map(t => t.getMillis / 1000)), Json.toJson(untilDate.map(t => t.getMillis / 1000))))
    }

    Seq(PropertyQuery(
      List(EndpointQuery("uber/rides", None,
        unixDateFilter.map(f ⇒ Seq(EndpointQueryFilter("start_time", None, f))), None)), Some("start_time"), Some("descending"), None))
  }

  def mapDataRecord(recordId: UUID, content: JsValue, tailRecordId: Option[UUID] = None, tailContent: Option[JsValue] = None): Try[DataFeedItem] = {
    logger.debug(s"uber content: $content")
    for {
      distance <- Try((content \ "distance").asOpt[Double].getOrElse(0.doubleValue()).toString)
      startDate <- Try(new DateTime((content \ "start_time").as[Long] * 1000.longValue()))
      durationSeconds ← Try((content \ "end_time").asOpt[Int].getOrElse(0) - (content \ "start_time").asOpt[Int].getOrElse(0))
      duration <- Try {
        val m = (durationSeconds / 60) % 60
        val h = (durationSeconds / 60 / 60) % 24
        "%02d h %02d min".format(h, m)
      }
      title ← Try(DataFeedItemTitle(s"Your trip on ${startDate.toString("dd/MM/YYYY")}", None, None))
      itemContent ← Try(DataFeedItemContent(
        Some(
          s"""${(content \ "start_city" \ "display_name").asOpt[String].getOrElse("Unknown City")},
             |${BigDecimal.decimal(distance.toFloat).setScale(1, BigDecimal.RoundingMode.HALF_UP).toDouble} miles,
             |${duration}""".stripMargin),
        None,
        None,
        None))
      latitude <- Try((content \ "start_city" \ "latitude").asOpt[Double].getOrElse(0.doubleValue()))
      longitude <- Try((content \ "start_city" \ "longitude").asOpt[Double].getOrElse(0.doubleValue()))
      location <- Try(DataFeedItemLocation(Some(LocationGeo(longitude, latitude)), None, None))
    } yield DataFeedItem("uber", startDate, Seq(), Some(title), Some(itemContent), Some(location))
  }
}

class UberProfileStaticDataMapper extends StaticDataEndpointMapper {
  def dataQueries(): Seq[PropertyQuery] = {
    Seq(PropertyQuery(
      List(
        EndpointQuery("uber/profile", None, None, None)), Some("dateCreated"), Some("descending"), Some(1)))
  }

  def mapDataRecord(recordId: UUID, content: JsValue, endpoint: String): Seq[StaticDataValues] = {
    val eventualData = content.validate[Map[String, JsValue]]
    eventualData match {
      case JsSuccess(value, _) =>
        val lastPartOfEndpointString = endpoint.split("/").last

        Seq(StaticDataValues(lastPartOfEndpointString, value))
      case e: JsError =>
        logger.error(s"Couldn't validate static data JSON for $endpoint. $e")
        Seq()
    }
  }
} 
Example 180
Source File: GoogleCalendarMappers.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.she.mappers

import java.util.UUID

import org.hatdex.hat.api.models.{ EndpointQuery, EndpointQueryFilter, FilterOperator, PropertyQuery }
import org.hatdex.hat.api.models.applications.{ DataFeedItem, DataFeedItemContent, DataFeedItemLocation, DataFeedItemTitle, LocationAddress }
import org.joda.time.{ DateTime, DateTimeZone }
import play.api.libs.json.{ JsValue, Json }

import scala.util.Try

class GoogleCalendarMapper extends DataEndpointMapper {
  override protected val dataDeduplicationField: Option[String] = Some("id")

  def dataQueries(fromDate: Option[DateTime], untilDate: Option[DateTime]): Seq[PropertyQuery] = {
    val eventDateTimePropertyQuery = PropertyQuery(
      List(
        EndpointQuery("calendar/google/events", None, Some(Seq(
          dateFilter(fromDate, untilDate).map(f ⇒ EndpointQueryFilter("start.dateTime", None, f))).flatten), None)),
      Some("start.dateTime"), Some("descending"), None)

    val dateOnlyFilter = if (fromDate.isDefined) {
      Some(FilterOperator.Between(Json.toJson(fromDate.map(_.toString("yyyy-MM-dd"))), Json.toJson(untilDate.map(_.toString("yyyy-MM-dd")))))
    }
    else {
      None
    }

    val eventDatePropertyQuery = PropertyQuery(
      List(
        EndpointQuery("calendar/google/events", None, Some(Seq(
          dateOnlyFilter.map(f ⇒ EndpointQueryFilter("start.date", None, f))).flatten), None)),
      Some("start.date"), Some("descending"), None)

    Seq(eventDateTimePropertyQuery, eventDatePropertyQuery)
  }

  def cleanHtmlTags(input: String): String = {
    input.replaceAll("<br/?>", "\n")
      .replaceAll("&nbsp;", " ")
      .replaceAll("<a [^>]*>([^<]*)</a>", "$1")
  }

  def mapDataRecord(recordId: UUID, content: JsValue, tailRecordId: Option[UUID] = None, tailContent: Option[JsValue] = None): Try[DataFeedItem] = {
    for {
      startDate ← Try((content \ "start" \ "dateTime").asOpt[DateTime]
        .getOrElse((content \ "start" \ "date").as[DateTime])
        .withZone((content \ "start" \ "timeZone").asOpt[String].flatMap(z ⇒ Try(DateTimeZone.forID(z)).toOption).getOrElse(DateTimeZone.getDefault)))
      endDate ← Try((content \ "end" \ "dateTime").asOpt[DateTime]
        .getOrElse((content \ "end" \ "date").as[DateTime])
        .withZone((content \ "end" \ "timeZone").asOpt[String].flatMap(z ⇒ Try(DateTimeZone.forID(z)).toOption).getOrElse(DateTimeZone.getDefault)))
      timeIntervalString ← Try(eventTimeIntervalString(startDate, Some(endDate)))
      itemContent ← Try(DataFeedItemContent(
        (content \ "description").asOpt[String].map(cleanHtmlTags), None, None, None))
      location ← Try(DataFeedItemLocation(
        geo = None,
        address = (content \ "location").asOpt[String].map(l ⇒ LocationAddress(None, None, Some(l), None, None)), // TODO integrate with geocoding API for full location information?
        tags = None))
    } yield {
      val title = DataFeedItemTitle(s"${(content \ "summary").as[String]}", Some(s"${timeIntervalString._1} ${timeIntervalString._2.getOrElse("")}"), Some("event"))
      val loc = Some(location).filter(l ⇒ l.address.isDefined || l.geo.isDefined || l.tags.isDefined)
      DataFeedItem("google", startDate, Seq("event"),
        Some(title), Some(itemContent), loc)
    }
  }
} 
Example 181
Source File: SpotifyMappers.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.she.mappers

import java.util.UUID

import org.hatdex.hat.api.models.{ EndpointQuery, EndpointQueryFilter, PropertyQuery }
import org.hatdex.hat.api.models.applications.{ DataFeedItem, DataFeedItemContent, DataFeedItemMedia, DataFeedItemTitle }
import org.hatdex.hat.she.models.StaticDataValues
import org.joda.time.DateTime
import play.api.libs.json.{ JsError, JsNumber, JsObject, JsResult, JsSuccess, JsValue, __ }

import scala.util.Try

class SpotifyFeedMapper extends DataEndpointMapper {
  def dataQueries(fromDate: Option[DateTime], untilDate: Option[DateTime]): Seq[PropertyQuery] = {
    Seq(PropertyQuery(
      List(EndpointQuery("spotify/feed", None,
        dateFilter(fromDate, untilDate).map(f ⇒ Seq(EndpointQueryFilter("played_at", None, f))), None)), Some("played_at"), Some("descending"), None))
  }

  def mapDataRecord(recordId: UUID, content: JsValue, tailRecordId: Option[UUID] = None, tailContent: Option[JsValue] = None): Try[DataFeedItem] = {
    for {
      durationSeconds ← Try((content \ "track" \ "duration_ms").as[Int] / 1000)
      title ← Try(
        DataFeedItemTitle("You listened", None, Some(s"${"%02d".format(durationSeconds / 60)}:${"%02d".format(durationSeconds % 60)}")))
      itemContent ← Try(DataFeedItemContent(
        Some(
          s"""${(content \ "track" \ "name").as[String]},
             |${(content \ "track" \ "artists").as[Seq[JsObject]].map(a ⇒ (a \ "name").as[String]).mkString(", ")},
             |${(content \ "track" \ "album" \ "name").as[String]}""".stripMargin),
        None,
        Some(
          Seq(DataFeedItemMedia((content \ "track" \ "album" \ "images" \ 0 \ "url").asOpt[String], (content \ "track" \ "album" \ "images" \ 0 \ "url").asOpt[String]))),
        None))
      date ← Try((content \ "played_at").as[DateTime])
    } yield DataFeedItem("spotify", date, Seq(), Some(title), Some(itemContent), None)
  }
}

class SpotifyProfileStaticDataMapper extends StaticDataEndpointMapper {
  def dataQueries(): Seq[PropertyQuery] = {
    Seq(PropertyQuery(
      List(
        EndpointQuery("spotify/profile", None, None, None)), Some("dateCreated"), Some("descending"), Some(1)))
  }

  def mapDataRecord(recordId: UUID, content: JsValue, endpoint: String): Seq[StaticDataValues] = {
    val eventualData = content.validate[JsObject]
    eventualData match {
      case JsSuccess(value, _) =>

        val lastPartOfEndpointString = endpoint.split("/").last
        val maybeTransformedData = transformData(value).flatMap(item => item.validate[Map[String, JsValue]])
        maybeTransformedData match {
          case JsSuccess(data, _) =>

            Seq(StaticDataValues(lastPartOfEndpointString, (data - "images" - "external_urls")))
          case e: JsError =>

            logger.error(s"Couldn't validate static data JSON for $endpoint. $e")
            Seq()
        }
      case e: JsError =>
        logger.error(s"Couldn't validate static data JSON for $endpoint. $e")
        Seq()
    }
  }

  private def transformData(rawData: JsObject): JsResult[JsValue] = {
    val transformation = __.json.update(
      __.read[JsObject].map(profile => {
        val followers = (profile \ "followers" \ "total").asOpt[JsNumber].getOrElse(JsNumber(0))

        profile ++ JsObject(Map(
          "followers" -> followers))
      }))

    rawData.transform(transformation)
  }
} 
Example 182
Source File: NotablesMappers.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.she.mappers

import java.util.UUID

import org.hatdex.hat.api.models.{ EndpointQuery, EndpointQueryFilter, PropertyQuery }
import org.hatdex.hat.api.models.applications.{ DataFeedItem, DataFeedItemContent, DataFeedItemLocation, DataFeedItemMedia, DataFeedItemTitle, LocationGeo }
import org.joda.time.DateTime
import play.api.libs.json.JsValue

import scala.util.Try

class NotablesFeedMapper extends DataEndpointMapper {
  def dataQueries(fromDate: Option[DateTime], untilDate: Option[DateTime]): Seq[PropertyQuery] = {
    Seq(PropertyQuery(
      List(EndpointQuery("rumpel/notablesv1", None,
        dateFilter(fromDate, untilDate).map(f ⇒ Seq(EndpointQueryFilter("created_time", None, f))), None)), Some("created_time"), Some("descending"), None))
  }

  def mapDataRecord(recordId: UUID, content: JsValue, tailRecordId: Option[UUID] = None, tailContent: Option[JsValue] = None): Try[DataFeedItem] = {
    for {
      title ← Try(if ((content \ "currently_shared").as[Boolean]) {
        DataFeedItemTitle("You posted", None, Some("public"))
      }
      else {
        DataFeedItemTitle("You posted", None, Some("private"))
      })
      itemContent ← Try(if ((content \ "photov1").isDefined && (content \ "photov1" \ "link").as[String].nonEmpty) {
        DataFeedItemContent(Some((content \ "message").as[String]), None, Some(Seq(
          DataFeedItemMedia(Some((content \ "photov1" \ "link").as[String]), Some((content \ "photov1" \ "link").as[String])))), None)
      }
      else {
        DataFeedItemContent(Some((content \ "message").as[String]), None, None, None)
      })
      location ← Try(if ((content \ "locationv1").isDefined) {
        Some(DataFeedItemLocation(Some(LocationGeo(
          (content \ "locationv1" \ "longitude").as[Double],
          (content \ "locationv1" \ "latitude").as[Double])), None, None))
      }
      else {
        None
      })
      date ← Try((content \ "created_time").as[DateTime])
      tags ← Try((content \ "shared_on").as[Seq[String]])
    } yield DataFeedItem("notables", date, tags, Some(title), Some(itemContent), location)
  }
} 
Example 183
Source File: EndpointSubscriberService.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.api.service.monitoring

import org.hatdex.hat.api.models._
import org.hatdex.hat.api.service.richData.JsonDataTransformer
import org.joda.time.DateTime
import play.api.Logger
import play.api.libs.json.Reads._
import play.api.libs.json.{ JsArray, JsValue, Json, _ }

case class EndpointQueryException(message: String = "", cause: Throwable = None.orNull)
  extends Exception(message, cause)

object EndpointSubscriberService {
  private val logger = Logger(this.getClass)

  def matchesBundle(data: EndpointData, bundle: EndpointDataBundle): Boolean = {
    val endpointQueries = bundle.flatEndpointQueries
      .filter(_.endpoint == data.endpoint)

    endpointQueries collectFirst {
      case q if q.filters.isEmpty                             => true
      case q if q.filters.exists(dataMatchesFilters(data, _)) => true
    } getOrElse {
      false
    }
  }

  private implicit val dateReads: Reads[DateTime] = JodaReads.jodaDateReads("yyyy-MM-dd'T'HH:mm:ssZ")

  private def dataMatchesFilters(data: EndpointData, filters: Seq[EndpointQueryFilter]): Boolean = {
    logger.debug("Checking if data matches provided filters")
    filters.exists { f =>
      data.data.transform(JsonDataTransformer.parseJsPath(f.field).json.pick).fold(
        invalid = {
          _ => false
        },
        valid = {
          fieldData =>
            val data = f.transformation map {
              case _: FieldTransformation.Identity =>
                fieldData
              case trans: FieldTransformation.DateTimeExtract =>
                Json.toJson(dateTimeExtractPart(fieldData.as[DateTime](dateReads), trans.part))
              case trans: FieldTransformation.TimestampExtract =>
                Json.toJson(dateTimeExtractPart(new DateTime(fieldData.as[Long] * 1000L), trans.part))
              case trans =>
                throw EndpointQueryException(s"Invalid field transformation `${trans.getClass.getName}` for ongoing tracking")
            } getOrElse {
              fieldData
            }
            f.operator match {
              case op: FilterOperator.In       => jsContains(op.value, data)
              case op: FilterOperator.Contains => jsContains(data, op.value)
              case op: FilterOperator.Between  => jsLessThanOrEqual(op.lower, data) && jsLessThanOrEqual(data, op.upper)
              case op                          => throw EndpointQueryException(s"Invalid match operator `${op.getClass.getName}` for ongoing tracking")
            }

        })
    }
  }

  private def dateTimeExtractPart(d: DateTime, part: String): Int = {
    part match {
      case "milliseconds" => d.getMillisOfSecond
      case "second"       => d.getSecondOfMinute
      case "minute"       => d.getMinuteOfDay
      case "hour"         => d.getHourOfDay
      case "day"          => d.getDayOfMonth
      case "week"         => d.getWeekOfWeekyear
      case "month"        => d.getMonthOfYear
      case "year"         => d.getYear
      case "decade"       => d.getYear / 10
      case "century"      => d.getCenturyOfEra
      case "dow"          => d.getDayOfWeek
      case "doy"          => d.getDayOfYear
      case "epoch"        => (d.getMillis / 1000).toInt
    }
  }

  private def jsContains(contains: JsValue, contained: JsValue): Boolean = {
    (contains, contained) match {
      case (a: JsObject, b: JsObject) => b.fieldSet.subsetOf(a.fieldSet)
      case (a: JsArray, b: JsArray)   => a.value.containsSlice(b.value)
      case (a: JsArray, b: JsValue)   => a.value.contains(b)
      case (a: JsValue, b: JsValue)   => a == b
      case _                          => false
    }
  }

  private def jsLessThanOrEqual(a: JsValue, b: JsValue): Boolean = {
    (a, b) match {
      case (aa: JsNumber, bb: JsNumber) => aa.value <= bb.value
      case (aa: JsString, bb: JsString) => aa.value <= bb.value
      case _                            => false
    }
  }
} 
Example 184
Source File: FieldTransformable.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.api.service.richData

import com.github.tminglei.slickpg.TsVector
import org.hatdex.hat.api.models._
import org.hatdex.libs.dal.HATPostgresProfile.api._
import org.joda.time.DateTime
import play.api.libs.json._

trait FieldTransformable[In] {
  type Out
  def apply(in: In): Out
}

object FieldTransformable {
  type Aux[I, O] = FieldTransformable[I] { type Out = O }

  import FieldTransformation._

  implicit val generateIdentityTranslation: Aux[Identity, Rep[JsValue] => Rep[JsValue]] =
    new FieldTransformable[Identity] {
      type Out = Rep[JsValue] => Rep[JsValue]

      def apply(in: Identity): Rep[JsValue] => Rep[JsValue] = {
        value: Rep[JsValue] => value
      }
    }

  implicit val generateDateTimeExtractTranslation: Aux[DateTimeExtract, Rep[JsValue] => Rep[JsValue]] =
    new FieldTransformable[DateTimeExtract] {
      type Out = Rep[JsValue] => Rep[JsValue]

      def apply(in: DateTimeExtract): Rep[JsValue] => Rep[JsValue] = {
        value => toJson(datePart(in.part, value.asColumnOf[String].asColumnOf[DateTime]))
      }
    }

  implicit val generateTimestampExtractTranslation: Aux[TimestampExtract, Rep[JsValue] => Rep[JsValue]] =
    new FieldTransformable[TimestampExtract] {
      type Out = Rep[JsValue] => Rep[JsValue]

      def apply(in: TimestampExtract): Rep[JsValue] => Rep[JsValue] = {
        value => toJson(datePartTimestamp(in.part, toTimestamp(value.asColumnOf[String].asColumnOf[Double])))
      }
    }

  implicit val generateSearchableTranslation: Aux[Searchable, Rep[JsValue] => Rep[TsVector]] =
    new FieldTransformable[Searchable] {
      type Out = Rep[JsValue] => Rep[TsVector]

      def apply(in: Searchable): Rep[JsValue] => Rep[TsVector] = {
        value => toTsVector(value.asColumnOf[String])
      }
    }

  def process[I](in: I)(implicit p: FieldTransformable[I]): p.Out = p(in)
} 
Example 185
Source File: MailTokenUser.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.phata.models

import java.util.UUID

import org.joda.time.DateTime

trait MailToken {
  def id: String
  def email: String
  def expirationTime: DateTime
  def isExpired: Boolean = expirationTime.isBeforeNow
}

case class MailTokenUser(id: String, email: String, expirationTime: DateTime, isSignUp: Boolean) extends MailToken

object MailTokenUser {
  private val mailTokenValidityHours = 24

  def apply(email: String, isSignUp: Boolean): MailTokenUser =
    MailTokenUser(UUID.randomUUID().toString, email, new DateTime().plusHours(mailTokenValidityHours), isSignUp)
}

object MailClaimTokenUser {
  private val mailClaimTokenValidityDays = 7

  def apply(email: String): MailTokenUser =
    MailTokenUser(UUID.randomUUID().toString, email, new DateTime().plusDays(mailClaimTokenValidityDays), isSignUp = true)
} 
Example 186
Source File: HatDatabaseProviderSpec.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.resourceManagement

import java.util.UUID

import org.hatdex.hat.resourceManagement.models.{ DatabaseInstance, DatabaseServer, HatKeys, HatSignup }
import org.joda.time.DateTime
import play.api.test.PlaySpecification

import scala.concurrent.duration._

class HatDatabaseProviderSpec extends PlaySpecification with HatServerProviderContext {
  "The `signupDatabaseConfig` method" should {
    "Return a parsed database configuration" in {
      val service = application.injector.instanceOf[HatDatabaseProviderMilliner]
      val signup = HatSignup(
        UUID.randomUUID(),
        "Bob ThePlumber", "bobtheplumber", "[email protected]",
        "testing", "testing", true,
        DateTime.now(),
        Some(DatabaseInstance(UUID.randomUUID(), "testhatdb1", "testing")),
        Some(DatabaseServer(0, "localhost", 5432, DateTime.now(), Seq())),
        Some(HatKeys("", "")))

      val config = service.signupDatabaseConfig(signup)
      config.getLong("idleTimeout") must be equalTo 30.seconds.toMillis
      config.getString("properties.user") must be equalTo "testhatdb1"
      config.getString("properties.databaseName") must be equalTo "testhatdb1"
      config.getString("properties.portNumber") must be equalTo "5432"
    }
  }
} 
Example 187
Source File: HatDataStatsProcessorSpec.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.api.service.monitoring

import java.util.UUID

import akka.stream.Materializer
import com.google.inject.AbstractModule
import net.codingwell.scalaguice.ScalaModule
import org.hatdex.hat.api.models.{ EndpointData, Owner }
import org.hatdex.hat.api.service.applications.{ TestApplicationProvider, TrustedApplicationProvider }
import org.hatdex.hat.api.service.monitoring.HatDataEventBus.DataCreatedEvent
import org.hatdex.hat.authentication.models.HatUser
import org.hatdex.hat.dal.ModelTranslation
import org.hatdex.hat.resourceManagement.FakeHatConfiguration
import org.joda.time.DateTime
import org.specs2.mock.Mockito
import org.specs2.specification.Scope
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.libs.json.{ JsValue, Json }
import play.api.test.PlaySpecification
import play.api.{ Application, Logger }

class HatDataStatsProcessorSpec extends PlaySpecification with Mockito with HatDataStatsProcessorContext {

  val logger = Logger(this.getClass)

  sequential

  "The `computeInboundStats` method" should {
    "Correctly count numbers of values for simple objects" in {
      val service = application.injector.instanceOf[HatDataStatsProcessor]
      val stats = service.computeInboundStats(simpleDataCreatedEvent)

      import org.hatdex.hat.api.json.DataStatsFormat._
      logger.debug(s"Got back stats: ${Json.prettyPrint(Json.toJson(stats))}")

      stats.logEntry must be equalTo "test item"
      stats.statsType must be equalTo "inbound"
      stats.stats.length must be equalTo 1
      val endpointStats = stats.stats.head
      endpointStats.endpoint must be equalTo "testendpoint"

      endpointStats.propertyStats("field") must equalTo(1)
      endpointStats.propertyStats("date") must equalTo(1)
      endpointStats.propertyStats("date_iso") must equalTo(1)
      endpointStats.propertyStats("anotherField") must equalTo(1)
      endpointStats.propertyStats("object.objectField") must equalTo(1)
      endpointStats.propertyStats("object.objectFieldArray[]") must equalTo(3)
      endpointStats.propertyStats("object.objectFieldObjectArray[].subObjectName") must equalTo(2)
      endpointStats.propertyStats("object.objectFieldObjectArray[].subObjectName2") must equalTo(2)
    }
  }

}

trait HatDataStatsProcessorContext extends Scope {
  import scala.concurrent.ExecutionContext.Implicits.global
  // Setup default users for testing
  val owner = HatUser(UUID.randomUUID(), "hatuser", Some("pa55w0rd"), "hatuser", Seq(Owner()), enabled = true)

  class ExtrasModule extends AbstractModule with ScalaModule {
    override def configure(): Unit = {
      bind[TrustedApplicationProvider].toInstance(new TestApplicationProvider(Seq()))
    }
  }

  lazy val application: Application = new GuiceApplicationBuilder()
    .configure(FakeHatConfiguration.config)
    .overrides(new ExtrasModule)
    .build()

  implicit lazy val materializer: Materializer = application.materializer

  val simpleJson: JsValue = Json.parse(
    """
      | {
      |   "field": "value",
      |   "date": 1492699047,
      |   "date_iso": "2017-04-20T14:37:27+00:00",
      |   "anotherField": "anotherFieldValue",
      |   "object": {
      |     "objectField": "objectFieldValue",
      |     "objectFieldArray": ["objectFieldArray1", "objectFieldArray2", "objectFieldArray3"],
      |     "objectFieldObjectArray": [
      |       {"subObjectName": "subObject1", "subObjectName2": "subObject1-2"},
      |       {"subObjectName": "subObject2", "subObjectName2": "subObject2-2"}
      |     ]
      |   }
      | }
    """.stripMargin)

  val simpleDataCreatedEvent = DataCreatedEvent(
    "testhat.hubofallthings.net",
    ModelTranslation.fromInternalModel(owner).clean,
    DateTime.now(), "test item",
    Seq(
      EndpointData("testendpoint", Option(UUID.randomUUID()), None, None, simpleJson, None)))
} 
Example 188
Source File: OAuthAuthorizationTokensDal.scala    From slick-akka-http-oauth2   with Apache License 2.0 5 votes vote down vote up
package persistence.dals

import java.security.SecureRandom
import java.sql.Timestamp

import org.joda.time.DateTime
import persistence.entities.SlickTables.OauthAccessTokenTable
import persistence.entities.{Account, OAuthAccessToken, OAuthClient}
import slick.driver.H2Driver.api._
import slick.driver.JdbcProfile
import utils.{Configuration, PersistenceModule}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.util.Random


trait OAuthAccessTokensDal extends BaseDalImpl[OauthAccessTokenTable,OAuthAccessToken]{
  def create(account: Account, client: OAuthClient): Future[OAuthAccessToken]
  def delete(account: Account, client: OAuthClient): Future[Int]
  def refresh(account: Account, client: OAuthClient): Future[OAuthAccessToken]
  def findByAccessToken(accessToken: String): Future[Option[OAuthAccessToken]]
  def findByAuthorized(account: Account, clientId: String): Future[Option[OAuthAccessToken]]
  def findByRefreshToken(refreshToken: String): Future[Option[OAuthAccessToken]]
}

class OAuthAccessTokensDalImpl (modules: Configuration with PersistenceModule)(implicit override val db: JdbcProfile#Backend#Database) extends OAuthAccessTokensDal {
  override def create(account: Account, client: OAuthClient): Future[OAuthAccessToken] = {
    def randomString(length: Int) = new Random(new SecureRandom()).alphanumeric.take(length).mkString
    val accessToken = randomString(40)
    val refreshToken = randomString(40)
    val createdAt = new Timestamp(new DateTime().getMillis)
    val oauthAccessToken = new OAuthAccessToken(
      id = 0,
      accountId = account.id,
      oauthClientId = client.id,
      accessToken = accessToken,
      refreshToken = refreshToken,
      createdAt = createdAt
    )
    insert(oauthAccessToken).map(id => oauthAccessToken.copy(id = id))
  }

  override def delete(account: Account, client: OAuthClient): Future[Int] = {
    deleteByFilter( oauthToken => oauthToken.accountId === account.id && oauthToken.oauthClientId === client.id)
  }

  override def refresh(account: Account, client: OAuthClient): Future[OAuthAccessToken] = {
    delete(account, client)
    create(account, client)
  }

  override def findByAuthorized(account: Account, clientId: String): Future[Option[OAuthAccessToken]] = {
    val query = for {
      oauthClient <- modules.oauthClientsDal.tableQ
      token <- tableQ if oauthClient.id === token.oauthClientId && oauthClient.clientId === clientId && token.accountId === account.id
    } yield token
    db.run(query.result).map(_.headOption)
  }

  override def findByAccessToken(accessToken: String): Future[Option[OAuthAccessToken]] = {
    findByFilter(_.accessToken === accessToken).map(_.headOption)
  }

  override def findByRefreshToken(refreshToken: String): Future[Option[OAuthAccessToken]] = {
    val expireAt = new Timestamp(new DateTime().minusMonths(1).getMillis)
    findByFilter( token => token.refreshToken === refreshToken && token.createdAt > expireAt).map(_.headOption)

  }
} 
Example 189
Source File: OAuthAuthorizationCodesDal.scala    From slick-akka-http-oauth2   with Apache License 2.0 5 votes vote down vote up
package persistence.dals

import java.sql.Timestamp

import org.joda.time.DateTime
import persistence.entities.OAuthAuthorizationCode
import persistence.entities.SlickTables.OauthAuthorizationCodeTable
import slick.driver.H2Driver.api._
import slick.driver.JdbcProfile

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future


trait OAuthAuthorizationCodesDal extends BaseDalImpl[OauthAuthorizationCodeTable,OAuthAuthorizationCode]{
  def findByCode(code: String): Future[Option[OAuthAuthorizationCode]]
  def delete(code: String): Future[Int]
}

class OAuthAuthorizationCodesDalImpl()(implicit override val db: JdbcProfile#Backend#Database) extends OAuthAuthorizationCodesDal {
  override def findByCode(code: String): Future[Option[OAuthAuthorizationCode]] = {
    val expireAt = new Timestamp(new DateTime().minusMinutes(30).getMillis)
    findByFilter(authCode => authCode.code === code && authCode.createdAt > expireAt).map(_.headOption)
  }

  override def delete(code: String): Future[Int] = deleteByFilter(_.code === code)

} 
Example 190
Source File: Boot.scala    From slick-akka-http-oauth2   with Apache License 2.0 5 votes vote down vote up
import java.sql.Timestamp

import akka.http.scaladsl.Http
import akka.http.scaladsl.server.RouteConcatenation
import akka.stream.ActorMaterializer
import org.joda.time.DateTime
import persistence.entities.{Account, OAuthClient}
import rest.OAuthRoutes
import utils._

object Main extends App with RouteConcatenation {
  // configuring modules for application, cake pattern for DI
  val modules = new ConfigurationModuleImpl  with ActorModuleImpl with PersistenceModuleImpl
  implicit val system = modules.system
  implicit val materializer = ActorMaterializer()
  implicit val ec = modules.system.dispatcher

  modules.generateDDL()

  for {
    createAccounts <- modules.accountsDal.insert(Seq(
      Account(0, "[email protected]", "48181acd22b3edaebc8a447868a7df7ce629920a", new Timestamp(new DateTime().getMillis)) // password:bob
    ))
    createOauthClients <- modules.oauthClientsDal.insert(Seq(
      OAuthClient(0, 1, "client_credentials", "bob_client_id", "bob_client_secret", Some("redirectUrl"), new Timestamp(new DateTime().getMillis))))
  } yield {
    println(s"Database initialized with default values for bob and alice")
  }

  val bindingFuture = Http().bindAndHandle(
    new OAuthRoutes(modules).routes, "localhost", 8080)

  println(s"Server online at http://localhost:8080/")

} 
Example 191
Source File: Utils.scala    From spark-datetime   with Apache License 2.0 5 votes vote down vote up
package org.sparklinedata.spark.dateTime

import org.joda.time.{DateTime, Period, Interval}

import scala.collection.mutable.ArrayBuffer


object Utils {

  def intervalToSeq(i : Interval, p : Period) : Seq[DateTime] = {
    import com.github.nscala_time.time.Imports._
    val b = new ArrayBuffer[DateTime]
    var d = i.getStart
    while(d < i.getEnd) {
      b += d
      d = d + p
    }
    b.toSeq
  }
} 
Example 192
Source File: TestableTime.scala    From graphcool-framework   with Apache License 2.0 5 votes vote down vote up
package cool.graph.shared.externalServices

import org.joda.time.DateTime

trait TestableTime {
  def DateTime: org.joda.time.DateTime
}

class TestableTimeImplementation extends TestableTime {
  override def DateTime: DateTime = org.joda.time.DateTime.now
}


class TestableTimeMock extends TestableTime {
  var cache                           = org.joda.time.DateTime.now
  def setDateTime(dateTime: DateTime) = cache = dateTime
  override def DateTime: DateTime     = cache
} 
Example 193
Source File: Metrics.scala    From graphcool-framework   with Apache License 2.0 5 votes vote down vote up
package cool.graph.client

import java.util.concurrent.TimeUnit

import akka.actor.Actor
import cool.graph.cuid.Cuid
import cool.graph.shared.externalServices.KinesisPublisher
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import spray.json.{JsArray, JsBoolean, JsNumber, JsObject, JsString}

import scala.collection.mutable
import scala.concurrent.duration.FiniteDuration
import scala.util.control.NonFatal

object FeatureMetric extends Enumeration {
  type FeatureMetric = Value
  val Subscriptions           = Value("backend/api/subscriptions")
  val Filter                  = Value("backend/feature/filter")
  val NestedMutations         = Value("backend/feature/nested-mutation")
  val ApiSimple               = Value("backend/api/simple")
  val ApiRelay                = Value("backend/api/relay")
  val ApiFiles                = Value("backend/api/files")
  val ServersideSubscriptions = Value("backend/feature/sss")
  val RequestPipeline         = Value("backend/feature/rp") // add this!
  val PermissionQuery         = Value("backend/feature/permission-queries") // add this!
  val Authentication          = Value("backend/feature/authentication")
  val Algolia                 = Value("backend/feature/algolia") // add this!
  val Auth0                   = Value("backend/feature/integration-auth0")
  val Digits                  = Value("backend/feature/integration-digits")
}

case class ApiFeatureMetric(ip: String,
                            date: DateTime,
                            projectId: String,
                            clientId: String,
                            usedFeatures: List[String],
                            // Should be false when we can't determine. This is the case for subscriptions.
                            // Is always false for File api.
                            isFromConsole: Boolean)

class FeatureMetricActor(
    metricsPublisher: KinesisPublisher,
    interval: Int
) extends Actor {
  import context.dispatcher

  val metrics = mutable.Buffer.empty[ApiFeatureMetric]
  val FLUSH   = "FLUSH"
  val tick = context.system.scheduler.schedule(
    initialDelay = FiniteDuration(interval, TimeUnit.SECONDS),
    interval = FiniteDuration(interval, TimeUnit.SECONDS),
    receiver = self,
    message = FLUSH
  )

  override def postStop() = tick.cancel()

  def receive = {
    case metric: ApiFeatureMetric =>
      metrics += metric

    case FLUSH =>
      flushMetrics()
  }

  def flushMetrics() = {
    val byProject = metrics.groupBy(_.projectId) map {
      case (projectId, metrics) =>
        JsObject(
          "requestCount"        -> JsNumber(metrics.length),
          "projectId"           -> JsString(projectId),
          "usedIps"             -> JsArray(metrics.map(_.ip).distinct.take(10).toVector.map(JsString(_))),
          "features"            -> JsArray(metrics.flatMap(_.usedFeatures).distinct.toVector.map(JsString(_))),
          "date"                -> JsString(metrics.head.date.toString(DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z").withZoneUTC())),
          "version"             -> JsString("1"),
          "justConsoleRequests" -> JsBoolean(metrics.forall(_.isFromConsole))
        )
    }

    byProject.foreach { json =>
      try {
        metricsPublisher.putRecord(json.toString, shardId = Cuid.createCuid())
      } catch {
        case NonFatal(e) => println(s"Putting kinesis FeatureMetric failed: ${e.getMessage} ${e.toString}")
      }
    }
    metrics.clear()
  }
} 
Example 194
Source File: FunctionLogsErrorShovel.scala    From graphcool-framework   with Apache License 2.0 5 votes vote down vote up
package cool.graph.worker.helpers

import java.util.concurrent.atomic.AtomicInteger

import cool.graph.bugsnag.BugSnaggerImpl
import cool.graph.messagebus.Conversions.ByteUnmarshaller
import cool.graph.messagebus.queue.rabbit.RabbitQueue
import cool.graph.worker.payloads.{JsonConversions, LogItem}
import cool.graph.worker.utils.Utils
import org.joda.time.DateTime
import play.api.libs.json.{JsObject, Json}

import scala.concurrent.{Await, Future}
import scala.util.{Failure, Success, Try}


object FunctionLogsErrorShovel extends App {
  import JsonConversions._

  import scala.concurrent.ExecutionContext.Implicits.global
  import scala.concurrent.duration._

  case class OldLogItem(
      id: String,
      projectId: String,
      functionId: String,
      requestId: String,
      status: String,
      duration: Long,
      timestamp: String,
      message: String
  ) {
    def toLogItem: LogItem = {
      status match {
        case "SUCCESS" => LogItem(id, projectId, functionId, requestId, status, duration, timestamp, Json.parse(message).as[JsObject])
        case "FAILURE" => LogItem(id, projectId, functionId, requestId, status, duration, timestamp, Json.obj("error" -> message))
      }
    }
  }

  implicit val bugsnagger       = BugSnaggerImpl("")
  implicit val oldLogItemFormat = Json.format[OldLogItem]

  val amqpUri = sys.env("RABBITMQ_URI")

  val faultTolerantUnmarshaller: ByteUnmarshaller[LogItem] = { bytes =>
    Try { logItemUnmarshaller(bytes) }.orElse(fromOldLogItemFormat(bytes)) match {
      case Success(logItem) => logItem.copy(timestamp = correctLogTimestamp(logItem.timestamp))
      case Failure(err)     => throw err
    }
  }

  val marshaller      = JsonConversions.logItemMarshaller
  val targetPublisher = RabbitQueue.publisher[LogItem](amqpUri, "function-logs")
  val counter         = new AtomicInteger(0)

  val consumeFn = { msg: LogItem =>
    println(s"[FunctionLogsErrorShovel][${counter.incrementAndGet()}]] Re-processing: $msg")
    targetPublisher.publish(msg)
    Future.successful(())
  }

  val plainErrConsumer =
    RabbitQueue.plainConsumer[LogItem](amqpUri, "function-logs-error", "function-logs", autoDelete = false)(bugsnagger, faultTolerantUnmarshaller)

  def fromOldLogItemFormat(bytes: Array[Byte]): Try[LogItem] = Try { Json.parse(bytes).as[OldLogItem].toLogItem }

  def correctLogTimestamp(timestamp: String): String = {
    val dt     = DateTime.parse(timestamp)
    val newTst = Utils.msqlDateFormatter.print(dt)

    println(s"[FunctionLogsErrorShovel]\t$timestamp\t->\t$newTst")
    newTst
  }

  plainErrConsumer.withConsumer(consumeFn)

  println("Press enter to terminate...")
  scala.io.StdIn.readLine()
  println("Terminating.")

  plainErrConsumer.shutdown
  targetPublisher.shutdown
} 
Example 195
Source File: UpdateClient.scala    From graphcool-framework   with Apache License 2.0 5 votes vote down vote up
package cool.graph.system.mutactions.internal

import java.sql.SQLIntegrityConstraintViolationException

import com.github.tototoshi.slick.MySQLJodaSupport._
import cool.graph._
import cool.graph.shared.errors.UserInputErrors.ClientEmailInUse
import cool.graph.shared.models.Client
import cool.graph.system.database.tables.ClientTable
import org.joda.time.DateTime
import slick.jdbc.MySQLProfile.api._
import slick.lifted.TableQuery

import scala.concurrent.Future

case class UpdateClient(oldClient: Client, client: Client) extends SystemSqlMutaction {
  override def execute: Future[SystemSqlStatementResult[Any]] = {

    val clients = TableQuery[ClientTable]

    Future.successful(SystemSqlStatementResult(sqlAction = DBIO.seq({
      val q = for { c <- clients if c.id === client.id } yield (c.name, c.email, c.updatedAt)
      q.update((client.name, client.email, DateTime.now()))
    })))
  }

  override def rollback: Some[Future[SystemSqlStatementResult[Any]]] = Some(UpdateClient(oldClient, oldClient).execute)

  override def handleErrors =
    Some({
      // https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html#error_er_dup_entry
      case e: SQLIntegrityConstraintViolationException if e.getErrorCode == 1062 => ClientEmailInUse()
    })
} 
Example 196
Source File: CreateClient.scala    From graphcool-framework   with Apache License 2.0 5 votes vote down vote up
package cool.graph.system.mutactions.internal

import java.sql.SQLIntegrityConstraintViolationException

import cool.graph.shared.errors.UserInputErrors.ClientEmailInUse
import cool.graph._
import cool.graph.client.database.DataResolver
import cool.graph.system.database.tables.{ClientTable, RelayIdTable}
import cool.graph.shared.models.Client
import org.joda.time.DateTime
import slick.jdbc.MySQLProfile.api._
import slick.lifted.TableQuery

import scala.concurrent.Future
import scala.util.{Success, Try}

case class CreateClient(client: Client) extends SystemSqlMutaction {
  override def execute: Future[SystemSqlStatementResult[Any]] = {
    val clients  = TableQuery[ClientTable]
    val relayIds = TableQuery[RelayIdTable]

    Future.successful(
      SystemSqlStatementResult(
        sqlAction = DBIO.seq(
          clients += cool.graph.system.database.tables.Client(
            id = client.id,
            auth0Id = client.auth0Id,
            isAuth0IdentityProviderEmail = client.isAuth0IdentityProviderEmail,
            name = client.name,
            email = client.email,
            password = client.hashedPassword,
            resetPasswordToken = client.resetPasswordSecret,
            source = client.source,
            createdAt = DateTime.now(),
            updatedAt = DateTime.now()
          ),
          relayIds += cool.graph.system.database.tables
            .RelayId(client.id, "Client")
        )))
  }

  override def rollback = Some(DeleteClient(client).execute)

  override def verify(): Future[Try[MutactionVerificationSuccess]] = {
    // todo: check valid email, valid password
    // todo: make  email column in sql unique

    Future.successful(Success(MutactionVerificationSuccess()))
  }

  override def handleErrors =
    // https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html#error_er_dup_entry
    Some({ case e: SQLIntegrityConstraintViolationException if e.getErrorCode == 1062 => ClientEmailInUse() })
} 
Example 197
Source File: RootToken.scala    From graphcool-framework   with Apache License 2.0 5 votes vote down vote up
package cool.graph.system.database.tables

import org.joda.time.DateTime
import slick.jdbc.MySQLProfile.api._
import com.github.tototoshi.slick.MySQLJodaSupport._

case class RootToken(
    id: String,
    projectId: String,
    token: String,
    name: String,
    created: DateTime
)

class RootTokenTable(tag: Tag) extends Table[RootToken](tag, "PermanentAuthToken") {

  def id        = column[String]("id", O.PrimaryKey)
  def token     = column[String]("token")
  def name      = column[String]("name")
  def created   = column[DateTime]("created")
  def projectId = column[String]("projectId")
  def project =
    foreignKey("systemtoken_projectid_foreign", projectId, Tables.Projects)(_.id)

  def * =
    (id, projectId, token, name, created) <> ((RootToken.apply _).tupled, RootToken.unapply)
} 
Example 198
Source File: MutationLog.scala    From graphcool-framework   with Apache License 2.0 5 votes vote down vote up
package cool.graph.system.database.tables

import com.github.tototoshi.slick.MySQLJodaSupport._
import cool.graph.shared.models.MutationLogStatus
import cool.graph.shared.models.MutationLogStatus.MutationLogStatus
import org.joda.time.DateTime
import slick.jdbc.MySQLProfile.api._

case class MutationLog(
    id: String,
    name: String,
    status: MutationLogStatus.Value,
    failedMutaction: Option[String],
    input: String,
    startedAt: DateTime,
    finishedAt: Option[DateTime],
    projectId: Option[String],
    clientId: Option[String]
)

class MutationLogTable(tag: Tag) extends Table[MutationLog](tag, "MutationLog") {
  implicit val mutationLogStatusMapper = MutationLog.mutationLogStatusMapper

  def id              = column[String]("id", O.PrimaryKey)
  def name            = column[String]("name")
  def status          = column[MutationLogStatus]("status")
  def failedMutaction = column[Option[String]]("failedMutaction")
  def input           = column[String]("input")
  def startedAt       = column[DateTime]("startedAt")
  def finishedAt      = column[Option[DateTime]]("finishedAt")

  def projectId = column[Option[String]]("projectId")
  def project =
    foreignKey("mutationlog_projectid_foreign", projectId, Tables.Projects)(_.id.?)

  def clientId = column[Option[String]]("clientId")
  def client =
    foreignKey("mutationlog_clientid_foreign", clientId, Tables.Clients)(_.id.?)

  def * =
    (id, name, status, failedMutaction, input, startedAt, finishedAt, projectId, clientId) <> ((MutationLog.apply _).tupled, MutationLog.unapply)
}

object MutationLog {
  implicit val mutationLogStatusMapper = MappedColumnType.base[MutationLogStatus, String](
    e => e.toString,
    s => MutationLogStatus.withName(s)
  )
} 
Example 199
Source File: Log.scala    From graphcool-framework   with Apache License 2.0 5 votes vote down vote up
package cool.graph.system.database.tables

import com.github.tototoshi.slick.MySQLJodaSupport._
import cool.graph.shared.models.LogStatus
import org.joda.time.DateTime
import slick.jdbc.MySQLProfile.api._

case class Log(
    id: String,
    projectId: String,
    functionId: String,
    requestId: Option[String],
    status: LogStatus.Value,
    duration: Int,
    timestamp: DateTime,
    message: String
)

class LogTable(tag: Tag) extends Table[Log](tag, "Log") {

  implicit val statusMapper =
    MappedColumnType.base[LogStatus.Value, String](
      e => e.toString,
      s => LogStatus.withName(s)
    )

  def id         = column[String]("id", O.PrimaryKey)
  def projectId  = column[String]("projectId")
  def functionId = column[String]("functionId")
  def requestId  = column[Option[String]]("requestId")
  def status     = column[LogStatus.Value]("status")
  def duration   = column[Int]("duration")
  def timestamp  = column[DateTime]("timestamp")
  def message    = column[String]("message")

  def * =
    (id, projectId, functionId, requestId, status, duration, timestamp, message) <> ((Log.apply _).tupled, Log.unapply)
} 
Example 200
Source File: MutationLogMutaction.scala    From graphcool-framework   with Apache License 2.0 5 votes vote down vote up
package cool.graph.system.database.tables

import slick.jdbc.MySQLProfile.api._
import cool.graph.shared.models.{MutationLogStatus}
import org.joda.time.DateTime
import com.github.tototoshi.slick.MySQLJodaSupport._
import cool.graph.shared.models.MutationLogStatus.MutationLogStatus

case class MutationLogMutaction(
    id: String,
    name: String,
    index: Int,
    status: MutationLogStatus.Value,
    input: String,
    finishedAt: Option[DateTime],
    error: Option[String],
    rollbackError: Option[String],
    mutationLogId: String
)

class MutationLogMutactionTable(tag: Tag) extends Table[MutationLogMutaction](tag, "MutationLogMutaction") {
  implicit val mutationLogStatusMapper = MutationLog.mutationLogStatusMapper

  def id            = column[String]("id", O.PrimaryKey)
  def name          = column[String]("name")
  def index         = column[Int]("index")
  def status        = column[MutationLogStatus.Value]("status")
  def input         = column[String]("input")
  def finishedAt    = column[Option[DateTime]]("finishedAt")
  def error         = column[Option[String]]("error")
  def rollbackError = column[Option[String]]("rollbackError")

  def mutationLogId = column[String]("mutationLogId")
  def mutationLog =
    foreignKey("mutationlogmutaction_mutationlogid_foreign", mutationLogId, Tables.MutationLogs)(_.id)

  def * =
    (id, name, index, status, input, finishedAt, error, rollbackError, mutationLogId) <> ((MutationLogMutaction.apply _).tupled, MutationLogMutaction.unapply)
}