java.util.UUID Scala Examples

The following examples show how to use java.util.UUID. 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: PulsarSinkTask.scala    From stream-reactor   with Apache License 2.0 7 votes vote down vote up
package com.datamountaineer.streamreactor.connect.pulsar.sink

import java.util
import java.util.UUID

import com.datamountaineer.streamreactor.connect.errors.ErrorPolicyEnum
import com.datamountaineer.streamreactor.connect.pulsar.config.{PulsarConfigConstants, PulsarSinkConfig, PulsarSinkSettings}
import com.datamountaineer.streamreactor.connect.utils.{JarManifest, ProgressCounter}
import com.typesafe.scalalogging.StrictLogging
import org.apache.kafka.clients.consumer.OffsetAndMetadata
import org.apache.kafka.common.TopicPartition
import org.apache.kafka.connect.sink.{SinkRecord, SinkTask}

import scala.collection.JavaConverters._



  override def stop(): Unit = {
    logger.info("Stopping Pulsar sink.")
    writer.foreach(w => w.close)
    progressCounter.empty
  }

  override def flush(map: util.Map[TopicPartition, OffsetAndMetadata]): Unit = {
    require(writer.nonEmpty, "Writer is not set!")
    writer.foreach(w => w.flush)
  }

  override def version: String = manifest.version()
} 
Example 2
Source File: PostgresDDLGeneratorTest.scala    From maha   with Apache License 2.0 6 votes vote down vote up
// Copyright 2017, Yahoo Holdings Inc.
// Licensed under the terms of the Apache License 2.0. Please see LICENSE file in project root for terms.
package com.yahoo.maha.core.ddl

import java.util.UUID

import com.yahoo.maha.core._
import com.yahoo.maha.jdbc.JdbcConnection
import com.zaxxer.hikari.{HikariConfig, HikariDataSource}



class PostgresDDLGeneratorTest extends BaseDDLGeneratorTest {

  val postgresDDLGenerator = new PostgresDDLGenerator

  private var dataSource: HikariDataSource = null
  private var jdbcConnection: JdbcConnection = null

  override protected def beforeAll(): Unit = {
    val config = new HikariConfig()
    config.setJdbcUrl("jdbc:h2:mem:" + UUID.randomUUID().toString.replace("-",
      "") + ";MODE=PostgreSQL;DB_CLOSE_DELAY=-1")
    config.setUsername("sa")
    config.setPassword("sa")
    config.setMaximumPoolSize(1)
    dataSource = new HikariDataSource(config)
    jdbcConnection = new JdbcConnection(dataSource)
  }

  override protected def afterAll(): Unit = {
    dataSource.close()
  }

  def removePartitionBy(ddl : String) : String = {
    val partitionString1 = """PARTITION BY LIST(stats_date)
                             |( PARTITION p_default VALUES(TO_DATE('01-JAN-1970 00:00:00', 'DD-MON-YYYY HH24:MI:SS'))
                             |)
                             |;""".stripMargin
    ddl.replace(partitionString1, ";")
  }

  test("test ddl for fact") {
    val postgresFacts = pubFact.factList.filter(f => f.engine.equals(PostgresEngine))
    val ddlMap : Map[String, String] = postgresFacts.map(fact => fact.name -> removePartitionBy(postgresDDLGenerator.toDDL(fact))).toMap
    assert(ddlMap.keySet.contains("pg_ad_k_stats"),
      "Postgres DDL Generator should generate ddl for postgres table cb_ad_k_stats")
    assert(!ddlMap.keySet.contains("ad_k_stats"),
      "Postgres DDL Generator should not generate ddl for hive table ad_k_stats")

    ddlMap.foreach {
      case(fact, ddl) =>
        val result = jdbcConnection.execute(ddl)
        assert(result.isSuccess && result.toOption.get === false, result.failed.toString)
    }
  }

  test("test ddl for dimension") {
    val postgresDims = pubDim.dimList.filter(d => d.engine.equals(PostgresEngine))
    val ddlMap : Map[String, String] = postgresDims.map(dim => dim.name -> removePartitionBy(postgresDDLGenerator.toDDL(dim))).toMap
    assert(ddlMap.keySet.contains("postgres_advertiser"),
      "Postgres DDL Generator should generate ddl for postgres table postgres_advertiser")
    assert(!ddlMap.keySet.contains("cache_advertiser"),
      "Postgres DDL Generator should not generate ddl for hive table cache_advertiser")

    ddlMap.foreach {
      case(dim, ddl) =>
        val result = jdbcConnection.execute(ddl)
        assert(result.isSuccess && result.toOption.get === false, result.failed.toString)
    }
  }



} 
Example 3
Source File: WarcHeaders.scala    From ArchiveSpark   with MIT License 6 votes vote down vote up
package org.archive.archivespark.sparkling.warc

import java.nio.charset.Charset
import java.util.UUID

import org.archive.archivespark.sparkling.Sparkling
import org.archive.archivespark.sparkling.util.DigestUtil
import org.joda.time.Instant
import org.joda.time.format.{DateTimeFormat, DateTimeFormatter, ISODateTimeFormat}

object WarcHeaders {
  val UTF8: Charset = Charset.forName(Sparkling.DefaultCharset)
  val ArcDateTimeFormat: DateTimeFormatter = DateTimeFormat.forPattern("yyyyMMddHHmmss").withZoneUTC
  val WarcDateTimeFormat: DateTimeFormatter = ISODateTimeFormat.dateTimeNoMillis

  val Br = "\r\n"

  def arcFile(info: WarcFileMeta, filename: String): Array[Byte] = {
    val header = StringBuilder.newBuilder
    header.append("filedesc://")
    header.append(filename)
    header.append(" 0.0.0.0 ")
    header.append(ArcDateTimeFormat.print(info.created))
    header.append(" text/plain ")

    val headerBody = StringBuilder.newBuilder
    // Internet Archive: Name of gathering organization with no white space (http://archive.org/web/researcher/ArcFileFormat.php)
    headerBody.append("1 0 " + info.publisher.replace(" ", "")).append(Br)
    headerBody.append("URL IP-address Archive-date Content-type Archive-length").append(Br)

    val headerBodyStr: String = headerBody.toString
    val headerBodyBlob: Array[Byte] = headerBodyStr.getBytes(UTF8)

    header.append(headerBodyBlob.length).append(Br)
    header.append(headerBodyStr).append(Br)

    header.toString().getBytes(UTF8)
  }

  def warcFile(meta: WarcFileMeta, filename: String): Array[Byte] = {
    val header = StringBuilder.newBuilder
    header.append("WARC/1.0").append(Br)
    header.append("WARC-Type: warcinfo").append(Br)
    header.append("WARC-Date: " + WarcDateTimeFormat.print(Instant.now)).append(Br)
    header.append("WARC-Filename: " + filename).append(Br)
    header.append("WARC-Record-ID: " + newRecordID()).append(Br)
    header.append("Content-Type: application/warc-fields").append(Br)

    val headerBody = StringBuilder.newBuilder
    headerBody.append("software: " + meta.software).append(Br)
    headerBody.append("format: WARC File Format 1.0").append(Br)
    headerBody.append("conformsTo: http://bibnum.bnf.fr/WARC/WARC_ISO_28500_version1_latestdraft.pdf").append(Br)
    headerBody.append("publisher: " + meta.publisher).append(Br)
    headerBody.append("created: " + WarcDateTimeFormat.print(meta.created)).append(Br)
    headerBody.append(Br * 3)

    val headerBodyStr = headerBody.toString()
    val headerBodyBlob = headerBodyStr.getBytes(UTF8)

    header.append("Content-Length: " + headerBodyBlob.length).append(Br)
    header.append(Br)
    header.append(headerBodyStr)

    header.toString().getBytes(UTF8)
  }

  def warcResponseRecord(meta: WarcRecordMeta, content: Array[Byte], payload: Array[Byte]): Array[Byte] = {
    val header = StringBuilder.newBuilder
    header.append("WARC/1.0").append(Br)
    header.append("WARC-Type: response").append(Br)
    header.append("WARC-Target-URI: " + meta.url).append(Br)
    header.append("WARC-Date: " + WarcDateTimeFormat.print(meta.timestamp)).append(Br)
    header.append("WARC-Payload-Digest: sha1:" + DigestUtil.sha1Base32(payload)).append(Br)
    if (meta.ip.isDefined) header.append("WARC-IP-Address: " + meta.ip.get).append(Br)
    header.append("WARC-Record-ID: " + meta.recordId.getOrElse(newRecordID())).append(Br)
    header.append("Content-Type: application/http; msgtype=response").append(Br)
    header.append("Content-Length: " + content.length).append(Br)
    header.append(Br)

    header.toString().getBytes(UTF8)
  }

  def http(statusLine: String, headers: Map[String, String]): Array[Byte] = {
    val header = StringBuilder.newBuilder
    header.append(statusLine).append(Br)
    for ((key, value) <- headers) {
      header.append(s"$key: $value").append(Br)
    }
    header.append(Br)
    header.toString().getBytes(UTF8)
  }

  private def newRecordID(): String = "<urn:uuid:" + UUID.randomUUID() + ">"
} 
Example 4
Source File: SessionIdFilter.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package filters

import java.util.UUID

import akka.stream.Materializer
import com.google.inject.Inject
import play.api.mvc._
import play.api.mvc.request.{Cell, RequestAttrKey}
import uk.gov.hmrc.http.{SessionKeys, HeaderNames => HMRCHeaderNames}

import scala.concurrent.{ExecutionContext, Future}

class SessionIdFilter(
  override val mat: Materializer,
  uuid: => UUID,
  implicit val ec: ExecutionContext
) extends Filter {

  @Inject
  def this(mat: Materializer, ec: ExecutionContext) {
    this(mat, UUID.randomUUID(), ec)
  }

  override def apply(f: RequestHeader => Future[Result])(rh: RequestHeader): Future[Result] = {

    lazy val sessionId: String = s"session-$uuid"

    if (rh.session.get(SessionKeys.sessionId).isEmpty) {

      val headers = rh.headers.add(
        HMRCHeaderNames.xSessionId -> sessionId
      )

      val session = rh.session + (SessionKeys.sessionId -> sessionId)

      f(rh.withHeaders(headers).addAttr(RequestAttrKey.Session, Cell(session))).map { result =>
        val updatedSession = if (result.session(rh).get(SessionKeys.sessionId).isDefined) {
          result.session(rh)
        } else {
          result.session(rh) + (SessionKeys.sessionId -> sessionId)
        }

        result.withSession(updatedSession)
      }
    } else {
      f(rh)
    }
  }
} 
Example 5
Source File: ClientUtil.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package com.daml.quickstart.iou

import java.util.UUID

import akka.stream.Materializer
import akka.stream.scaladsl.{Sink, Source}
import akka.{Done, NotUsed}
import com.daml.ledger.api.domain.LedgerId
import com.daml.ledger.api.refinements.ApiTypes.{ApplicationId, WorkflowId}
import com.daml.ledger.api.v1.command_submission_service.SubmitRequest
import com.daml.ledger.api.v1.commands.{Command, Commands}
import com.daml.ledger.api.v1.ledger_offset.LedgerOffset
import com.daml.ledger.api.v1.transaction.Transaction
import com.daml.ledger.api.v1.transaction_filter.{Filters, TransactionFilter}
import com.daml.ledger.client.LedgerClient
import com.daml.quickstart.iou.FutureUtil.toFuture
import com.google.protobuf.empty.Empty

import scala.concurrent.{ExecutionContext, Future}

class ClientUtil(
    client: LedgerClient,
    applicationId: ApplicationId,
) {

  import ClientUtil._

  private val ledgerId = client.ledgerId
  private val packageClient = client.packageClient
  private val commandClient = client.commandClient
  private val transactionClient = client.transactionClient

  def listPackages(implicit ec: ExecutionContext): Future[Set[String]] =
    packageClient.listPackages().map(_.packageIds.toSet)

  def ledgerEnd(implicit ec: ExecutionContext): Future[LedgerOffset] =
    transactionClient.getLedgerEnd().flatMap(response => toFuture(response.offset))

  def submitCommand(party: String, workflowId: WorkflowId, cmd: Command.Command): Future[Empty] = {
    val commands = Commands(
      ledgerId = LedgerId.unwrap(ledgerId),
      workflowId = WorkflowId.unwrap(workflowId),
      applicationId = ApplicationId.unwrap(applicationId),
      commandId = uniqueId,
      party = party,
      commands = Seq(Command(cmd)),
    )

    commandClient.submitSingleCommand(SubmitRequest(Some(commands), None))
  }

  def nextTransaction(party: String, offset: LedgerOffset)(
      implicit mat: Materializer): Future[Transaction] =
    transactionClient
      .getTransactions(offset, None, transactionFilter(party))
      .take(1L)
      .runWith(Sink.head)

  def subscribe(party: String, offset: LedgerOffset, max: Option[Long])(f: Transaction => Unit)(
      implicit mat: Materializer): Future[Done] = {
    val source: Source[Transaction, NotUsed] =
      transactionClient.getTransactions(offset, None, transactionFilter(party))
    max.fold(source)(n => source.take(n)) runForeach f
  }

  override lazy val toString: String = s"ClientUtil{ledgerId=$ledgerId}"
}

object ClientUtil {
  def transactionFilter(parties: String*): TransactionFilter =
    TransactionFilter(parties.map((_, Filters.defaultInstance)).toMap)

  def uniqueId: String = UUID.randomUUID.toString

  def workflowIdFromParty(p: String): WorkflowId =
    WorkflowId(s"$p Workflow")
} 
Example 6
Source File: ClientUtil.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package com.daml.quickstart.iou

import java.util.UUID

import akka.stream.Materializer
import akka.stream.scaladsl.{Sink, Source}
import akka.{Done, NotUsed}
import com.daml.ledger.api.refinements.ApiTypes.{ApplicationId, WorkflowId}
import com.daml.ledger.api.v1.command_submission_service.SubmitRequest
import com.daml.ledger.api.v1.commands.Commands
import com.daml.ledger.api.v1.ledger_offset.LedgerOffset
import com.daml.ledger.api.v1.transaction.Transaction
import com.daml.ledger.api.v1.transaction_filter.{Filters, TransactionFilter}
import com.daml.ledger.client.LedgerClient
import com.daml.ledger.client.binding.{Primitive => P}
import com.daml.quickstart.iou.FutureUtil.toFuture
import com.google.protobuf.empty.Empty

import scalaz.syntax.tag._

import scala.concurrent.{ExecutionContext, Future}

class ClientUtil(
    client: LedgerClient,
    applicationId: ApplicationId,
) {

  import ClientUtil._

  private val ledgerId = client.ledgerId
  private val commandClient = client.commandClient
  private val transactionClient = client.transactionClient

  def ledgerEnd(implicit ec: ExecutionContext): Future[LedgerOffset] =
    transactionClient.getLedgerEnd().flatMap(response => toFuture(response.offset))

  def submitCommand[T](
      sender: P.Party,
      workflowId: WorkflowId,
      command: P.Update[P.ContractId[T]]): Future[Empty] = {
    commandClient.submitSingleCommand(submitRequest(sender, workflowId, command))
  }

  def submitRequest[T](
      party: P.Party,
      workflowId: WorkflowId,
      seq: P.Update[P.ContractId[T]]*): SubmitRequest = {
    val commands = Commands(
      ledgerId = ledgerId.unwrap,
      workflowId = WorkflowId.unwrap(workflowId),
      applicationId = ApplicationId.unwrap(applicationId),
      commandId = uniqueId,
      party = P.Party.unwrap(party),
      commands = seq.map(_.command)
    )
    SubmitRequest(Some(commands), None)
  }

  def nextTransaction(party: P.Party, offset: LedgerOffset)(
      implicit mat: Materializer): Future[Transaction] =
    transactionClient
      .getTransactions(offset, None, transactionFilter(party))
      .take(1L)
      .runWith(Sink.head)

  def subscribe(party: P.Party, offset: LedgerOffset, max: Option[Long])(f: Transaction => Unit)(
      implicit mat: Materializer): Future[Done] = {
    val source: Source[Transaction, NotUsed] =
      transactionClient.getTransactions(offset, None, transactionFilter(party))
    max.fold(source)(n => source.take(n)) runForeach f
  }

  override lazy val toString: String = s"ClientUtil{ledgerId=$ledgerId}"
}

object ClientUtil {
  def transactionFilter(ps: P.Party*): TransactionFilter =
    TransactionFilter(P.Party.unsubst(ps).map((_, Filters.defaultInstance)).toMap)

  def uniqueId: String = UUID.randomUUID.toString

  def workflowIdFromParty(p: P.Party): WorkflowId =
    WorkflowId(s"${P.Party.unwrap(p): String} Workflow")
} 
Example 7
Source File: ClientUtil.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package com.daml.quickstart.iou

import java.util.UUID

import akka.stream.Materializer
import akka.stream.scaladsl.{Sink, Source}
import akka.{Done, NotUsed}
import com.daml.ledger.api.refinements.ApiTypes.{ApplicationId, WorkflowId}
import com.daml.ledger.api.v1.command_submission_service.SubmitRequest
import com.daml.ledger.api.v1.commands.Commands
import com.daml.ledger.api.v1.ledger_offset.LedgerOffset
import com.daml.ledger.api.v1.transaction.Transaction
import com.daml.ledger.api.v1.transaction_filter.{Filters, TransactionFilter}
import com.daml.ledger.client.LedgerClient
import com.daml.ledger.client.binding.{Primitive => P}
import com.daml.quickstart.iou.FutureUtil.toFuture
import com.google.protobuf.empty.Empty

import scalaz.syntax.tag._

import scala.concurrent.{ExecutionContext, Future}

class ClientUtil(
    client: LedgerClient,
    applicationId: ApplicationId,
) {

  import ClientUtil._

  private val ledgerId = client.ledgerId
  private val commandClient = client.commandClient
  private val transactionClient = client.transactionClient

  def ledgerEnd(implicit ec: ExecutionContext): Future[LedgerOffset] =
    transactionClient.getLedgerEnd().flatMap(response => toFuture(response.offset))

  def submitCommand[T](
      sender: P.Party,
      workflowId: WorkflowId,
      command: P.Update[P.ContractId[T]]): Future[Empty] = {
    commandClient.submitSingleCommand(submitRequest(sender, workflowId, command))
  }

  def submitRequest[T](
      party: P.Party,
      workflowId: WorkflowId,
      seq: P.Update[P.ContractId[T]]*): SubmitRequest = {
    val commands = Commands(
      ledgerId = ledgerId.unwrap,
      workflowId = WorkflowId.unwrap(workflowId),
      applicationId = ApplicationId.unwrap(applicationId),
      commandId = uniqueId,
      party = P.Party.unwrap(party),
      commands = seq.map(_.command)
    )
    SubmitRequest(Some(commands), None)
  }

  def nextTransaction(party: P.Party, offset: LedgerOffset)(
      implicit mat: Materializer): Future[Transaction] =
    transactionClient
      .getTransactions(offset, None, transactionFilter(party))
      .take(1L)
      .runWith(Sink.head)

  def subscribe(party: P.Party, offset: LedgerOffset, max: Option[Long])(f: Transaction => Unit)(
      implicit mat: Materializer): Future[Done] = {
    val source: Source[Transaction, NotUsed] =
      transactionClient.getTransactions(offset, None, transactionFilter(party))
    max.fold(source)(n => source.take(n)) runForeach f
  }

  override lazy val toString: String = s"ClientUtil{ledgerId=$ledgerId}"
}

object ClientUtil {
  def transactionFilter(ps: P.Party*): TransactionFilter =
    TransactionFilter(P.Party.unsubst(ps).map((_, Filters.defaultInstance)).toMap)

  def uniqueId: String = UUID.randomUUID.toString

  def workflowIdFromParty(p: P.Party): WorkflowId =
    WorkflowId(s"${P.Party.unwrap(p): String} Workflow")
} 
Example 8
Source File: EventLoopGroupOwner.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.platform.apiserver

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

import com.daml.resources.{Resource, ResourceOwner}
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.nio.{NioServerSocketChannel, NioSocketChannel}
import io.netty.channel.{Channel, EventLoopGroup, ServerChannel}
import io.netty.util.concurrent.DefaultThreadFactory

import scala.concurrent.{ExecutionContext, Future, Promise}
import scala.util.Try

final class EventLoopGroupOwner(threadPoolName: String, parallelism: Int)
    extends ResourceOwner[EventLoopGroup] {

  override def acquire()(implicit executionContext: ExecutionContext): Resource[EventLoopGroup] =
    Resource(
      Future(new NioEventLoopGroup(
        parallelism,
        new DefaultThreadFactory(s"$threadPoolName-grpc-event-loop-${UUID.randomUUID()}", true))))(
      group => {
        val promise = Promise[Unit]()
        val future = group.shutdownGracefully(0, 0, MILLISECONDS)
        future.addListener((f: io.netty.util.concurrent.Future[_]) =>
          promise.complete(Try(f.get).map(_ => ())))
        promise.future
      }
    )
}

object EventLoopGroupOwner {

  val clientChannelType: Class[_ <: Channel] = classOf[NioSocketChannel]

  val serverChannelType: Class[_ <: ServerChannel] = classOf[NioServerSocketChannel]

} 
Example 9
Source File: ExecutionSequencerFactoryOwner.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.platform.apiserver

import java.util.UUID

import akka.actor.ActorSystem
import com.daml.grpc.adapter.{AkkaExecutionSequencerPool, ExecutionSequencerFactory}
import com.daml.resources.{Resource, ResourceOwner}

import scala.concurrent.{ExecutionContext, Future}

final class ExecutionSequencerFactoryOwner(implicit actorSystem: ActorSystem)
    extends ResourceOwner[ExecutionSequencerFactory] {
  // NOTE: Pick a unique pool name as we want to allow multiple LedgerApiServer instances,
  // and it's pretty difficult to wait for the name to become available again.
  // The name deregistration is asynchronous and the close method does not wait, and it isn't
  // trivial to implement.
  // https://doc.akka.io/docs/akka/2.5/actors.html#graceful-stop
  private val poolName = s"ledger-api-server-rs-grpc-bridge-${UUID.randomUUID}"

  private val ActorCount = Runtime.getRuntime.availableProcessors() * 8

  override def acquire()(
      implicit executionContext: ExecutionContext
  ): Resource[ExecutionSequencerFactory] =
    Resource(Future(new AkkaExecutionSequencerPool(poolName, ActorCount)))(_.closeAsync())
} 
Example 10
Source File: ServiceCallWithMainActorAuthTests.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.platform.sandbox.auth

import java.time.Duration
import java.util.UUID

trait ServiceCallWithMainActorAuthTests extends ServiceCallAuthTests {

  protected val mainActor: String = UUID.randomUUID.toString

  private val signedIncorrectly =
    Option(toHeader(readWriteToken(mainActor), UUID.randomUUID.toString))

  it should "deny calls authorized to read/write as the wrong party" in {
    expectPermissionDenied(serviceCallWithToken(canActAsRandomParty))
  }
  it should "deny calls authorized to read-only as the wrong party" in {
    expectPermissionDenied(serviceCallWithToken(canReadAsRandomParty))
  }
  it should "deny calls with an invalid signature" in {
    expectUnauthenticated(serviceCallWithToken(signedIncorrectly))
  }

  protected val canReadAsMainActor =
    Option(toHeader(readOnlyToken(mainActor)))
  protected val canReadAsMainActorExpired =
    Option(toHeader(expiringIn(Duration.ofDays(-1), readOnlyToken(mainActor))))
  protected val canReadAsMainActorExpiresTomorrow =
    Option(toHeader(expiringIn(Duration.ofDays(1), readOnlyToken(mainActor))))

  protected val canActAsMainActor =
    Option(toHeader(readWriteToken(mainActor)))
  protected val canActAsMainActorExpired =
    Option(toHeader(expiringIn(Duration.ofDays(-1), readWriteToken(mainActor))))
  protected val canActAsMainActorExpiresTomorrow =
    Option(toHeader(expiringIn(Duration.ofDays(1), readWriteToken(mainActor))))

  // Note: lazy val, because the ledger ID is only known after the sandbox start
  protected lazy val canReadAsMainActorActualLedgerId =
    Option(toHeader(forLedgerId(unwrappedLedgerId, readOnlyToken(mainActor))))
  protected val canReadAsMainActorRandomLedgerId =
    Option(toHeader(forLedgerId(UUID.randomUUID.toString, readOnlyToken(mainActor))))
  protected val canReadAsMainActorActualParticipantId =
    Option(toHeader(forParticipantId("sandbox-participant", readOnlyToken(mainActor))))
  protected val canReadAsMainActorRandomParticipantId =
    Option(toHeader(forParticipantId(UUID.randomUUID.toString, readOnlyToken(mainActor))))
  protected val canReadAsMainActorActualApplicationId =
    Option(toHeader(forApplicationId(serviceCallName, readOnlyToken(mainActor))))
  protected val canReadAsMainActorRandomApplicationId =
    Option(toHeader(forApplicationId(UUID.randomUUID.toString, readOnlyToken(mainActor))))

  // Note: lazy val, because the ledger ID is only known after the sandbox start
  protected lazy val canActAsMainActorActualLedgerId =
    Option(toHeader(forLedgerId(unwrappedLedgerId, readWriteToken(mainActor))))
  protected val canActAsMainActorRandomLedgerId =
    Option(toHeader(forLedgerId(UUID.randomUUID.toString, readWriteToken(mainActor))))
  protected val canActAsMainActorActualParticipantId =
    Option(toHeader(forParticipantId("sandbox-participant", readWriteToken(mainActor))))
  protected val canActAsMainActorRandomParticipantId =
    Option(toHeader(forParticipantId(UUID.randomUUID.toString, readWriteToken(mainActor))))
  protected val canActAsMainActorActualApplicationId =
    Option(toHeader(forApplicationId(serviceCallName, readWriteToken(mainActor))))
  protected val canActAsMainActorRandomApplicationId =
    Option(toHeader(forApplicationId(UUID.randomUUID.toString, readWriteToken(mainActor))))

} 
Example 11
Source File: AdminServiceCallAuthTests.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.platform.sandbox.auth

import java.util.UUID

trait AdminServiceCallAuthTests extends ServiceCallAuthTests {

  private val signedIncorrectly = Option(toHeader(adminToken, UUID.randomUUID.toString))

  it should "deny calls with an invalid signature" in {
    expectUnauthenticated(serviceCallWithToken(signedIncorrectly))
  }
  it should "deny calls with an expired admin token" in {
    expectUnauthenticated(serviceCallWithToken(canReadAsAdminExpired))
  }
  it should "deny calls with a read-only token" in {
    expectPermissionDenied(serviceCallWithToken(canReadAsRandomParty))
  }
  it should "deny calls with a read/write token" in {
    expectPermissionDenied(serviceCallWithToken(canActAsRandomParty))
  }
  it should "allow calls with explicitly non-expired admin token" in {
    expectSuccess(serviceCallWithToken(canReadAsAdminExpiresTomorrow))
  }
  it should "allow calls with admin token without expiration" in {
    expectSuccess(serviceCallWithToken(canReadAsAdmin))
  }

  it should "allow calls with the correct ledger ID" in {
    expectSuccess(serviceCallWithToken(canReadAsAdminActualLedgerId))
  }
  it should "deny calls with a random ledger ID" in {
    expectPermissionDenied(serviceCallWithToken(canReadAsAdminRandomLedgerId))
  }
  it should "allow calls with the correct participant ID" in {
    expectSuccess(serviceCallWithToken(canReadAsAdminActualParticipantId))
  }
  it should "deny calls with a random participant ID" in {
    expectPermissionDenied(serviceCallWithToken(canReadAsAdminRandomParticipantId))
  }

} 
Example 12
Source File: SandboxFixtureWithAuth.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.platform.sandbox.services

import java.time.{Duration, Instant}
import java.util.UUID

import com.daml.jwt.domain.DecodedJwt
import com.daml.jwt.{HMAC256Verifier, JwtSigner}
import com.daml.ledger.api.auth.{AuthServiceJWT, AuthServiceJWTCodec, AuthServiceJWTPayload}
import com.daml.platform.sandbox.config.SandboxConfig
import org.scalatest.Suite
import scalaz.syntax.tag.ToTagOps

trait SandboxFixtureWithAuth extends SandboxFixture { self: Suite =>

  val emptyToken = AuthServiceJWTPayload(
    ledgerId = None,
    participantId = None,
    applicationId = None,
    exp = None,
    admin = false,
    actAs = Nil,
    readAs = Nil
  )

  val adminToken: AuthServiceJWTPayload = emptyToken.copy(admin = true)

  def readOnlyToken(party: String): AuthServiceJWTPayload =
    emptyToken.copy(readAs = List(party))

  def readWriteToken(party: String): AuthServiceJWTPayload =
    emptyToken.copy(actAs = List(party))

  def expiringIn(t: Duration, p: AuthServiceJWTPayload): AuthServiceJWTPayload =
    p.copy(exp = Option(Instant.now().plusNanos(t.toNanos)))

  def forLedgerId(id: String, p: AuthServiceJWTPayload): AuthServiceJWTPayload =
    p.copy(ledgerId = Some(id))

  def forParticipantId(id: String, p: AuthServiceJWTPayload): AuthServiceJWTPayload =
    p.copy(participantId = Some(id))

  def forApplicationId(id: String, p: AuthServiceJWTPayload): AuthServiceJWTPayload =
    p.copy(applicationId = Some(id))

  override protected def config: SandboxConfig =
    super.config.copy(
      authService = Some(
        AuthServiceJWT(HMAC256Verifier(jwtSecret)
          .getOrElse(sys.error("Failed to create HMAC256 verifier")))))

  protected lazy val wrappedLedgerId = ledgerId(Some(toHeader(adminToken)))
  protected lazy val unwrappedLedgerId = wrappedLedgerId.unwrap

  private val jwtHeader = """{"alg": "HS256", "typ": "JWT"}"""
  private val jwtSecret = UUID.randomUUID.toString

  private def signed(payload: AuthServiceJWTPayload, secret: String): String =
    JwtSigner.HMAC256
      .sign(DecodedJwt(jwtHeader, AuthServiceJWTCodec.compactPrint(payload)), secret)
      .getOrElse(sys.error("Failed to generate token"))
      .value

  def toHeader(payload: AuthServiceJWTPayload, secret: String = jwtSecret): String =
    signed(payload, secret)
} 
Example 13
Source File: SandboxBackend.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.platform.sandbox
import java.util.UUID

import com.daml.platform.sandbox.services.DbInfo
import com.daml.platform.store.DbType
import com.daml.resources.ResourceOwner
import com.daml.testing.postgresql.PostgresResource

import scala.util.Success

object SandboxBackend {

  trait Postgresql { this: AbstractSandboxFixture =>
    override protected final def database: Option[ResourceOwner[DbInfo]] =
      Some(PostgresResource.owner().map(database => DbInfo(database.url, DbType.Postgres)))
  }

  trait H2Database { this: AbstractSandboxFixture =>
    private def randomDatabaseName = UUID.randomUUID().toString
    private[this] def jdbcUrl = s"jdbc:h2:mem:$randomDatabaseName;db_close_delay=-1"
    override protected final def database: Option[ResourceOwner[DbInfo]] =
      Some(ResourceOwner.forTry(() => Success(DbInfo(jdbcUrl, DbType.H2Database))))
  }

} 
Example 14
Source File: GenMissingString.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.platform.api.checks.pkg

import java.util.UUID

object GenMissingString {
  def apply(collection: Set[String]): String = {
    var candidate = UUID.randomUUID().toString
    while (collection.contains(candidate)) {
      candidate = UUID.randomUUID().toString
    }
    candidate
  }

} 
Example 15
Source File: KeyValueParticipantStateWriter.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.ledger.participant.state.kvutils.api

import java.util.UUID
import java.util.concurrent.CompletionStage

import com.daml.daml_lf_dev.DamlLf
import com.daml.ledger.api.health.HealthStatus
import com.daml.ledger.participant.state.kvutils.DamlKvutils.DamlSubmission
import com.daml.ledger.participant.state.kvutils.{Envelope, KeyValueSubmission}
import com.daml.ledger.participant.state.v1._
import com.daml.lf.data.{Ref, Time}
import com.daml.metrics.Metrics

import scala.compat.java8.FutureConverters

class KeyValueParticipantStateWriter(writer: LedgerWriter, metrics: Metrics) extends WriteService {

  private val keyValueSubmission = new KeyValueSubmission(metrics)

  override def submitTransaction(
      submitterInfo: SubmitterInfo,
      transactionMeta: TransactionMeta,
      transaction: SubmittedTransaction,
      estimatedInterpretationCost: Long,
  ): CompletionStage[SubmissionResult] = {
    val submission =
      keyValueSubmission.transactionToSubmission(
        submitterInfo,
        transactionMeta,
        transaction,
      )
    val metadata = SimpleCommitMetadata(
      estimatedInterpretationCost = Some(estimatedInterpretationCost))
    commit(correlationId = submitterInfo.commandId, submission = submission, metadata = metadata)
  }

  override def uploadPackages(
      submissionId: SubmissionId,
      archives: List[DamlLf.Archive],
      sourceDescription: Option[String]): CompletionStage[SubmissionResult] = {
    val submission = keyValueSubmission
      .archivesToSubmission(
        submissionId,
        archives,
        sourceDescription.getOrElse(""),
        writer.participantId)
    commit(submissionId, submission)
  }

  override def submitConfiguration(
      maxRecordTime: Time.Timestamp,
      submissionId: SubmissionId,
      config: Configuration): CompletionStage[SubmissionResult] = {
    val submission =
      keyValueSubmission
        .configurationToSubmission(maxRecordTime, submissionId, writer.participantId, config)
    commit(submissionId, submission)
  }

  override def allocateParty(
      hint: Option[Party],
      displayName: Option[String],
      submissionId: SubmissionId): CompletionStage[SubmissionResult] = {
    val party = hint.getOrElse(generateRandomParty())
    val submission =
      keyValueSubmission.partyToSubmission(
        submissionId,
        Some(party),
        displayName,
        writer.participantId)
    commit(submissionId, submission)
  }

  override def currentHealth(): HealthStatus = writer.currentHealth()

  private def generateRandomParty(): Ref.Party =
    Ref.Party.assertFromString(s"party-${UUID.randomUUID().toString.take(8)}")

  private def commit(
      correlationId: String,
      submission: DamlSubmission,
      metadata: CommitMetadata = CommitMetadata.Empty,
  ): CompletionStage[SubmissionResult] =
    FutureConverters.toJava(writer.commit(correlationId, Envelope.enclose(submission), metadata))
} 
Example 16
Source File: ExtractorConfig.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.extractor.config

import java.nio.file.Path
import java.util.UUID

import scalaz.{OneAnd, Order}
import scalaz.syntax.foldable._
import scalaz.syntax.functor._
import scalaz.std.list._
import scalaz.std.string._
import com.daml.lf.data.Ref.Party
import com.daml.ledger.api.v1.ledger_offset.LedgerOffset
import com.daml.ledger.api.tls.TlsConfiguration
import com.daml.ports.Port

sealed abstract class SnapshotEndSetting
object SnapshotEndSetting {
  case object Head extends SnapshotEndSetting
  case object Follow extends SnapshotEndSetting
  final case class Until(offset: String) extends SnapshotEndSetting
}

final case class ExtractorConfig(
    ledgerHost: String,
    ledgerPort: Port,
    ledgerInboundMessageSizeMax: Int,
    from: LedgerOffset,
    to: SnapshotEndSetting,
    parties: ExtractorConfig.Parties,
    templateConfigs: Set[TemplateConfig],
    tlsConfig: TlsConfiguration,
    accessTokenFile: Option[Path],
    appId: String = s"Extractor-${UUID.randomUUID().toString}"
) {
  def partySpec: String = parties.widen[String] intercalate ","
}

object ExtractorConfig {
  type Parties = OneAnd[List, Party]
}

final case class TemplateConfig(moduleName: String, entityName: String)

object TemplateConfig {
  implicit val templateConfigOrdering: Ordering[TemplateConfig] =
    Ordering.by(TemplateConfig.unapply)

  implicit val templateConfigOrder: Order[TemplateConfig] =
    Order.fromScalaOrdering
} 
Example 17
Source File: ClientUtil.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package com.daml.http.util

import java.util.UUID

import com.daml.ledger.api.refinements.ApiTypes.{CommandId, Party}
import com.daml.ledger.api.v1.transaction_filter.{Filters, TransactionFilter}
import com.daml.ledger.api.{v1 => lav1}

object ClientUtil {
  def uniqueId(): String = UUID.randomUUID.toString

  def uniqueCommandId(): CommandId = CommandId(uniqueId())

  def transactionFilter(ps: Party*): TransactionFilter =
    TransactionFilter(Party.unsubst(ps).map((_, Filters.defaultInstance)).toMap)

  def boxedRecord(a: lav1.value.Record): lav1.value.Value =
    lav1.value.Value(lav1.value.Value.Sum.Record(a))
} 
Example 18
Source File: package.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.ledger

import java.time.Clock
import java.util.UUID

import com.daml.lf.data.Ref
import com.daml.ledger.api.auth.{
  AuthServiceStatic,
  Authorizer,
  Claim,
  ClaimActAsParty,
  ClaimAdmin,
  ClaimPublic,
  ClaimReadAsParty,
  Claims
}

package object rxjava {

  private[rxjava] def untestedEndpoint: Nothing =
    throw new UnsupportedOperationException("Untested endpoint, implement if needed")

  private[rxjava] val authorizer =
    new Authorizer(() => Clock.systemUTC().instant(), "testLedgerId", "testParticipantId")

  private[rxjava] val emptyToken = "empty"
  private[rxjava] val publicToken = "public"
  private[rxjava] val adminToken = "admin"

  private[rxjava] val someParty = UUID.randomUUID.toString
  private[rxjava] val somePartyReadToken = UUID.randomUUID.toString
  private[rxjava] val somePartyReadWriteToken = UUID.randomUUID.toString

  private[rxjava] val someOtherParty = UUID.randomUUID.toString
  private[rxjava] val someOtherPartyReadToken = UUID.randomUUID.toString
  private[rxjava] val someOtherPartyReadWriteToken = UUID.randomUUID.toString

  private[rxjava] val mockedAuthService =
    AuthServiceStatic {
      case `emptyToken` => Claims(Nil)
      case `publicToken` => Claims(Seq[Claim](ClaimPublic))
      case `adminToken` => Claims(Seq[Claim](ClaimAdmin))
      case `somePartyReadToken` =>
        Claims(Seq[Claim](ClaimPublic, ClaimReadAsParty(Ref.Party.assertFromString(someParty))))
      case `somePartyReadWriteToken` =>
        Claims(Seq[Claim](ClaimPublic, ClaimActAsParty(Ref.Party.assertFromString(someParty))))
      case `someOtherPartyReadToken` =>
        Claims(
          Seq[Claim](ClaimPublic, ClaimReadAsParty(Ref.Party.assertFromString(someOtherParty))))
      case `someOtherPartyReadWriteToken` =>
        Claims(Seq[Claim](ClaimPublic, ClaimActAsParty(Ref.Party.assertFromString(someOtherParty))))
    }

} 
Example 19
Source File: CodeGenExampleSpec.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.ledger.client.binding

import java.util.UUID

import com.daml.ledger.client.binding.{Primitive => P}
import com.daml.sample.Main.PayOut
import org.scalatest.{Assertion, Matchers, WordSpec}

class CodeGenExampleSpec extends WordSpec with Matchers {
  val alice = P.Party("Alice")
  val bob = P.Party("Bob")
  val charlie = P.Party("Charlie")

  "create CallablePayout contract should compile" in {
    import com.daml.sample.Main.CallablePayout

    val createCommand: P.Update[P.ContractId[CallablePayout]] =
      CallablePayout(giver = alice, receiver = bob).create
    sendCommand(createCommand)
  }

  "exercise Call choice should compile" in {
    import com.daml.sample.Main.CallablePayout
    import com.daml.sample.Main.CallablePayout._

    val givenContractId: P.ContractId[CallablePayout] = receiveContractIdFromTheLedger
    val exerciseCommand: P.Update[P.ContractId[PayOut]] =
      givenContractId.exerciseCall(actor = alice)
    sendCommand(exerciseCommand)
  }

  "exercise Transfer choice should compile" in {
    import com.daml.sample.Main.CallablePayout
    import com.daml.sample.Main.CallablePayout._

    val givenContractId: P.ContractId[CallablePayout] = receiveContractIdFromTheLedger
    val exerciseCommand: P.Update[P.ContractId[CallablePayout]] =
      givenContractId.exerciseTransfer(actor = bob, $choice_arg = Transfer(newReceiver = charlie))
    sendCommand(exerciseCommand)
  }

  private def sendCommand[T](command: P.Update[P.ContractId[T]]): Assertion =
    command should not be null

  private def receiveContractIdFromTheLedger[T]: P.ContractId[T] =
    P.ContractId(UUID.randomUUID.toString)
} 
Example 20
Source File: CodeGenExampleSpec.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.ledger.client.binding

import java.util.UUID

import com.daml.ledger.client.binding.{Primitive => P}
import com.daml.sample.MyMain.PayOut
import org.scalatest.{Assertion, Matchers, WordSpec}

class CodeGenExampleSpec extends WordSpec with Matchers {
  val alice = P.Party("Alice")
  val bob = P.Party("Bob")
  val charlie = P.Party("Charlie")

  "create CallablePayout contract should compile" in {
    import com.daml.sample.MyMain.CallablePayout

    val createCommand: P.Update[P.ContractId[CallablePayout]] =
      CallablePayout(giver = alice, receiver = bob).create
    sendCommand(createCommand)
  }

  "exercise Call choice should compile" in {
    import com.daml.sample.MyMain.CallablePayout

    val givenContractId: P.ContractId[CallablePayout] = receiveContractIdFromTheLedger
    val exerciseCommand: P.Update[P.ContractId[PayOut]] =
      givenContractId.exerciseCall2(actor = alice)
    sendCommand(exerciseCommand)
  }

  "exercise Transfer choice should compile" in {
    import com.daml.sample.MyMain.CallablePayout

    val givenContractId: P.ContractId[CallablePayout] = receiveContractIdFromTheLedger
    val exerciseCommand: P.Update[P.ContractId[CallablePayout]] =
      givenContractId.exerciseTransfer(actor = bob, newReceiver = charlie)
    sendCommand(exerciseCommand)
  }

  "create contract with tuple should compile" in {
    import com.daml.sample.{MyMain, DA}
    val ct = MyMain.Twoples(alice, DA.Types.Tuple2(1, 2))
    val createCommand = ct.create
    sendCommand(createCommand)
  }

  private def sendCommand[T](command: P.Update[P.ContractId[T]]): Assertion =
    command should not be null

  private def receiveContractIdFromTheLedger[T]: P.ContractId[T] =
    P.ContractId(UUID.randomUUID.toString)
} 
Example 21
Source File: ClientUtil.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package com.daml.quickstart.iou

import java.util.UUID

import akka.stream.Materializer
import akka.stream.scaladsl.{Sink, Source}
import akka.{Done, NotUsed}
import com.daml.ledger.api.domain.LedgerId
import com.daml.ledger.api.refinements.ApiTypes.{ApplicationId, WorkflowId}
import com.daml.ledger.api.v1.command_submission_service.SubmitRequest
import com.daml.ledger.api.v1.commands.{Command, Commands}
import com.daml.ledger.api.v1.ledger_offset.LedgerOffset
import com.daml.ledger.api.v1.transaction.Transaction
import com.daml.ledger.api.v1.transaction_filter.{Filters, TransactionFilter}
import com.daml.ledger.client.LedgerClient
import com.daml.quickstart.iou.FutureUtil.toFuture
import com.google.protobuf.empty.Empty

import scala.concurrent.{ExecutionContext, Future}

class ClientUtil(
    client: LedgerClient,
    applicationId: ApplicationId,
) {

  import ClientUtil._

  private val ledgerId = client.ledgerId
  private val packageClient = client.packageClient
  private val commandClient = client.commandClient
  private val transactionClient = client.transactionClient

  def listPackages(implicit ec: ExecutionContext): Future[Set[String]] =
    packageClient.listPackages().map(_.packageIds.toSet)

  def ledgerEnd(implicit ec: ExecutionContext): Future[LedgerOffset] =
    transactionClient.getLedgerEnd().flatMap(response => toFuture(response.offset))

  def submitCommand(party: String, workflowId: WorkflowId, cmd: Command.Command): Future[Empty] = {
    val commands = Commands(
      ledgerId = LedgerId.unwrap(ledgerId),
      workflowId = WorkflowId.unwrap(workflowId),
      applicationId = ApplicationId.unwrap(applicationId),
      commandId = uniqueId,
      party = party,
      commands = Seq(Command(cmd)),
    )

    commandClient.submitSingleCommand(SubmitRequest(Some(commands), None))
  }

  def nextTransaction(party: String, offset: LedgerOffset)(
      implicit mat: Materializer): Future[Transaction] =
    transactionClient
      .getTransactions(offset, None, transactionFilter(party))
      .take(1L)
      .runWith(Sink.head)

  def subscribe(party: String, offset: LedgerOffset, max: Option[Long])(f: Transaction => Unit)(
      implicit mat: Materializer): Future[Done] = {
    val source: Source[Transaction, NotUsed] =
      transactionClient.getTransactions(offset, None, transactionFilter(party))
    max.fold(source)(n => source.take(n)) runForeach f
  }

  override lazy val toString: String = s"ClientUtil{ledgerId=$ledgerId}"
}

object ClientUtil {
  def transactionFilter(parties: String*): TransactionFilter =
    TransactionFilter(parties.map((_, Filters.defaultInstance)).toMap)

  def uniqueId: String = UUID.randomUUID.toString

  def workflowIdFromParty(p: String): WorkflowId =
    WorkflowId(s"$p Workflow")
} 
Example 22
Source File: ClientUtil.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package com.daml.quickstart.iou

import java.util.UUID

import akka.stream.Materializer
import akka.stream.scaladsl.{Sink, Source}
import akka.{Done, NotUsed}
import com.daml.ledger.api.refinements.ApiTypes.{ApplicationId, WorkflowId}
import com.daml.ledger.api.v1.command_submission_service.SubmitRequest
import com.daml.ledger.api.v1.commands.Commands
import com.daml.ledger.api.v1.ledger_offset.LedgerOffset
import com.daml.ledger.api.v1.transaction.Transaction
import com.daml.ledger.api.v1.transaction_filter.{Filters, TransactionFilter}
import com.daml.ledger.client.LedgerClient
import com.daml.ledger.client.binding.{Primitive => P}
import com.daml.quickstart.iou.FutureUtil.toFuture
import com.google.protobuf.empty.Empty

import scalaz.syntax.tag._

import scala.concurrent.{ExecutionContext, Future}

class ClientUtil(
    client: LedgerClient,
    applicationId: ApplicationId,
) {

  import ClientUtil._

  private val ledgerId = client.ledgerId
  private val commandClient = client.commandClient
  private val transactionClient = client.transactionClient

  def ledgerEnd(implicit ec: ExecutionContext): Future[LedgerOffset] =
    transactionClient.getLedgerEnd().flatMap(response => toFuture(response.offset))

  def submitCommand[T](
      sender: P.Party,
      workflowId: WorkflowId,
      command: P.Update[P.ContractId[T]]): Future[Empty] = {
    commandClient.submitSingleCommand(submitRequest(sender, workflowId, command))
  }

  def submitRequest[T](
      party: P.Party,
      workflowId: WorkflowId,
      seq: P.Update[P.ContractId[T]]*): SubmitRequest = {
    val commands = Commands(
      ledgerId = ledgerId.unwrap,
      workflowId = WorkflowId.unwrap(workflowId),
      applicationId = ApplicationId.unwrap(applicationId),
      commandId = uniqueId,
      party = P.Party.unwrap(party),
      commands = seq.map(_.command)
    )
    SubmitRequest(Some(commands), None)
  }

  def nextTransaction(party: P.Party, offset: LedgerOffset)(
      implicit mat: Materializer): Future[Transaction] =
    transactionClient
      .getTransactions(offset, None, transactionFilter(party))
      .take(1L)
      .runWith(Sink.head)

  def subscribe(party: P.Party, offset: LedgerOffset, max: Option[Long])(f: Transaction => Unit)(
      implicit mat: Materializer): Future[Done] = {
    val source: Source[Transaction, NotUsed] =
      transactionClient.getTransactions(offset, None, transactionFilter(party))
    max.fold(source)(n => source.take(n)) runForeach f
  }

  override lazy val toString: String = s"ClientUtil{ledgerId=$ledgerId}"
}

object ClientUtil {
  def transactionFilter(ps: P.Party*): TransactionFilter =
    TransactionFilter(P.Party.unsubst(ps).map((_, Filters.defaultInstance)).toMap)

  def uniqueId: String = UUID.randomUUID.toString

  def workflowIdFromParty(p: P.Party): WorkflowId =
    WorkflowId(s"${P.Party.unwrap(p): String} Workflow")
} 
Example 23
Source File: InMemoryTriggerDao.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.lf.engine.trigger.dao

import java.util.UUID

import com.daml.daml_lf_dev.DamlLf
import com.daml.lf.archive.Dar
import com.daml.lf.data.Ref.PackageId
import com.daml.lf.engine.trigger.{RunningTrigger, UserCredentials}

class InMemoryTriggerDao extends RunningTriggerDao {
  private var triggers: Map[UUID, RunningTrigger] = Map.empty
  private var triggersByParty: Map[UserCredentials, Set[UUID]] = Map.empty

  override def addRunningTrigger(t: RunningTrigger): Either[String, Unit] = {
    triggers += t.triggerInstance -> t
    triggersByParty += t.credentials -> (triggersByParty.getOrElse(t.credentials, Set()) + t.triggerInstance)
    Right(())
  }

  override def removeRunningTrigger(triggerInstance: UUID): Either[String, Boolean] = {
    triggers.get(triggerInstance) match {
      case None => Right(false)
      case Some(t) =>
        triggers -= t.triggerInstance
        triggersByParty += t.credentials -> (triggersByParty(t.credentials) - t.triggerInstance)
        Right(true)
    }
  }

  override def listRunningTriggers(credentials: UserCredentials): Either[String, Vector[UUID]] = {
    Right(triggersByParty.getOrElse(credentials, Set()).toVector.sorted)
  }

  // This is only possible when running with persistence. For in-memory mode we do nothing.
  override def persistPackages(dar: Dar[(PackageId, DamlLf.ArchivePayload)]): Either[String, Unit] =
    Right(())
}

object InMemoryTriggerDao {
  def apply(): InMemoryTriggerDao = new InMemoryTriggerDao
} 
Example 24
Source File: package.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.lf.engine

import java.time.Duration
import java.util.UUID

import com.daml.lf.data.Ref.Identifier
import com.daml.platform.services.time.TimeProviderType

import scala.concurrent.duration.FiniteDuration

package object trigger {

  case class LedgerConfig(
      host: String,
      port: Int,
      timeProvider: TimeProviderType,
      commandTtl: Duration,
      maxInboundMessageSize: Int,
  )

  case class TriggerRestartConfig(
      minRestartInterval: FiniteDuration,
      maxRestartInterval: FiniteDuration,
      restartIntervalRandomFactor: Double = 0.2,
  )

  final case class SecretKey(value: String)
  final case class UserCredentials(token: EncryptedToken)

  final case class RunningTrigger(
      triggerInstance: UUID,
      triggerName: Identifier,
      credentials: UserCredentials,
      // TODO(SF, 2020-0610): Add access token field here in the
      // presence of authentication.
  )
} 
Example 25
Source File: NavigatorBackend.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.navigator

import java.nio.file.{Files, Paths}
import java.util.UUID

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import com.daml.buildinfo.BuildInfo

object NavigatorBackend extends UIBackend {

  private val configFile = "frontend-config.js"
  override def customEndpoints: Set[CustomEndpoint[_]] = Set()
  override def customRoutes: List[Route] = List(frontendConfigRoute)
  override def applicationInfo: ApplicationInfo = ApplicationInfo(
    id = s"Navigator-${UUID.randomUUID().toString}",
    name = "Navigator",
    version = BuildInfo.Version,
  )
  override def banner: Option[String] =
    Some(
      raw"""   _  __          _           __
        |  / |/ /__ __  __(_)__ ____ _/ /____  ____
        | /    / _ `/ |/ / / _ `/ _ `/ __/ _ \/ __/
        |/_/|_/\_,_/|___/_/\_, /\_,_/\__/\___/_/
        |                 /___/
        |Version """.stripMargin + applicationInfo.version
    )

  
  private val frontendConfigRoute: Route = {
    path("api" / "config") {
      if (Files.exists(Paths.get(configFile)))
        getFromFile(configFile)
      else
        complete(StatusCodes.NotFound)
    }
  }
} 
Example 26
Source File: PortFilesSpec.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.ports

import java.nio.file.{Path, Paths}
import java.util.UUID

import com.daml.ports.PortFiles.FileAlreadyExists
import org.scalatest.{FreeSpec, Inside, Matchers}
import scalaz.{-\/, \/-}

class PortFilesSpec extends FreeSpec with Matchers with Inside {

  "Can create a port file with a unique file name" in {
    val path = uniquePath()
    inside(PortFiles.write(path, Port(1024))) {
      case \/-(()) =>
    }
    path.toFile.exists() shouldBe true
  }

  "Cannot create a port file with a nonunique file name" in {
    val path = uniquePath()
    inside(PortFiles.write(path, Port(1024))) {
      case \/-(()) =>
    }
    inside(PortFiles.write(path, Port(1024))) {
      case -\/(FileAlreadyExists(p)) =>
        p shouldBe path
    }
  }

  private def uniquePath(): Path = {
    val fileName = s"${this.getClass.getSimpleName}-${UUID.randomUUID().toString}.dummy"
    Paths.get(fileName)
  }
} 
Example 27
Source File: Cookie.scala    From iotchain   with MIT License 5 votes vote down vote up
package jbok.network.http.server.authentication

import java.util.UUID

import cats.effect.IO
import tsec.authentication.{
  AuthEncryptedCookie,
  AuthenticatedCookie,
  BackingStore,
  EncryptedCookieAuthenticator,
  SecuredRequestHandler,
  SignedCookieAuthenticator,
  TSecCookieSettings
}
import tsec.cipher.symmetric.jca.{AES128GCM, SecretKey}
import tsec.mac.jca.{HMACSHA256, MacSigningKey}

import scala.concurrent.duration._

object Cookie {
  val cookieStore: BackingStore[IO, UUID, AuthenticatedCookie[HMACSHA256, Long]] =
    DummyBackingStore[UUID, AuthenticatedCookie[HMACSHA256, Long]](_.id)

  val userStore: BackingStore[IO, Long, User] = DummyBackingStore[Long, User](_.id)

  val settings: TSecCookieSettings = TSecCookieSettings(
    cookieName = "jbok-auth",
    secure = false,
    expiryDuration = 10.minutes, // Absolute expiration time
    maxIdle = None // Rolling window expiration. Set this to a Finiteduration if you intend to have one
  )

  class Unencrypted(key: MacSigningKey[HMACSHA256]) {
    val cookieAuth =
      SignedCookieAuthenticator(
        settings,
        cookieStore,
        userStore,
        key
      )

    val Auth = SecuredRequestHandler(cookieAuth)

  }

  class Encrypted(key: SecretKey[AES128GCM]) {
    implicit val encryptor   = AES128GCM.genEncryptor[IO]
    implicit val gcmstrategy = AES128GCM.defaultIvStrategy[IO]

    val cookieStore: BackingStore[IO, UUID, AuthEncryptedCookie[AES128GCM, Long]] =
      DummyBackingStore[UUID, AuthEncryptedCookie[AES128GCM, Long]](_.id)

    val userStore: BackingStore[IO, Long, User] = DummyBackingStore[Long, User](_.id)

    val settings: TSecCookieSettings = TSecCookieSettings(
      cookieName = "jbok-auth",
      secure = false,
      expiryDuration = 10.minutes, // Absolute expiration time
      maxIdle = None // Rolling window expiration. Set this to a FiniteDuration if you intend to have one
    )

    val authWithBackingStore = //Instantiate a stateful authenticator
      EncryptedCookieAuthenticator.withBackingStore(
        settings,
        cookieStore,
        userStore,
        key
      )

    object stateless {
      val authenticator = EncryptedCookieAuthenticator.stateless(
        settings,
        userStore,
        key
      )

      val Auth = SecuredRequestHandler(authenticator)
    }

    object stateful {
      val authenticator = EncryptedCookieAuthenticator.withBackingStore(
        settings,
        cookieStore,
        userStore,
        key
      )

      val Auth = SecuredRequestHandler(authenticator)
    }
  }
} 
Example 28
Source File: FUUIDGen.scala    From fuuid   with MIT License 5 votes vote down vote up
package io.chrisdavenport.fuuid

import java.util.UUID
import cats.implicits._
import cats.effect.Sync


  def nameBased(namespace: FUUID, name: String): F[FUUID]
}

object FUUIDGen {
  def apply[F[_]](implicit ev: FUUIDGen[F]): FUUIDGen[F] = ev

  // Sync f => class FUUIDGen f
  implicit def instance[F[_]: Sync]: FUUIDGen[F] = new SyncFUUIDGen[F]

  private class SyncFUUIDGen[F[_]: Sync] extends FUUIDGen[F]{
    def random: F[FUUID] = FUUID.randomFUUID[F]
    def fromString(s: String): F[FUUID] = FUUID.fromStringF[F](s)
    def fromUUID(uuid: UUID): F[FUUID] = FUUID.fromUUID(uuid).pure[F]
    def nameBased(namespace: FUUID, name: String): F[FUUID] = FUUID.nameBased[F](namespace, name)
  }
} 
Example 29
Source File: FUUID.scala    From fuuid   with MIT License 5 votes vote down vote up
package io.chrisdavenport.fuuid

import cats._
import cats.implicits._
import cats.effect.Sync
import java.util.UUID

import scala.reflect.macros.blackbox

final class FUUID private (private val uuid: UUID){

  // Direct show method so people do not use toString
  def show: String = uuid.show
  // -1 less than, 0 equal to, 1 greater than
  def compare(that: FUUID): Int = this.uuid.compareTo(that.uuid)

  // Returns 0 when equal
  def eqv(that: FUUID): Boolean = compare(that) == 0

  override def equals(obj: scala.Any): Boolean = obj match {
    case that: FUUID => eqv(that)
    case _ => false
  }
  override def hashCode: Int = uuid.hashCode
  override def toString: String = uuid.toString

}

object FUUID {
  implicit val instancesFUUID: Hash[FUUID] with Order[FUUID] with Show[FUUID] =
    new Hash[FUUID] with Order[FUUID] with Show[FUUID]{
      override def show(t: FUUID): String = t.show
      override def eqv(x: FUUID, y: FUUID): Boolean = x.eqv(y)
      override def hash(x: FUUID): Int = x.hashCode
      override def compare(x: FUUID, y: FUUID): Int = x.compare(y)
    }

  def fromString(s: String): Either[Throwable, FUUID] =
    Either.catchNonFatal(new FUUID(UUID.fromString(s)))

  def fromStringOpt(s: String): Option[FUUID] = 
    fromString(s).toOption

  def fromStringF[F[_]](s: String)(implicit AE: ApplicativeError[F, Throwable]): F[FUUID] =
    fromString(s).fold(AE.raiseError, AE.pure)

  def fromUUID(uuid: UUID): FUUID = new FUUID(uuid)

  def randomFUUID[F[_]: Sync]: F[FUUID] = Sync[F].delay(
    new FUUID(UUID.randomUUID)
  )

  def fuuid(s: String): FUUID = macro Macros.fuuidLiteral

  private[FUUID] class Macros(val c: blackbox.Context) {
    import c.universe._
    def fuuidLiteral(s: c.Expr[String]): c.Expr[FUUID] =
      s.tree match {
        case Literal(Constant(s: String))=>
            fromString(s)
            .fold(
              e => c.abort(c.enclosingPosition, e.getMessage.replace("UUID", "FUUID")),
              _ => c.Expr(q"""
                @SuppressWarnings(Array("org.wartremover.warts.Throw"))
                val fuuid = _root_.io.chrisdavenport.fuuid.FUUID.fromString($s).fold(throw _, _root_.scala.Predef.identity)
                fuuid
              """)
            )
        case _ =>
          c.abort(
            c.enclosingPosition,
            s"This method uses a macro to verify that a FUUID literal is valid. Use FUUID.fromString if you have a dynamic value you want to parse as an FUUID."
          )
      }
  }

  
  object Unsafe {
    def toUUID(fuuid: FUUID): UUID = fuuid.uuid
    def withUUID[A](fuuid: FUUID)(f: UUID => A): A = f(fuuid.uuid)
  }

} 
Example 30
Source File: FUUIDSpec.scala    From fuuid   with MIT License 5 votes vote down vote up
package io.chrisdavenport.fuuid

import java.util.UUID
import cats.effect.IO
import org.specs2._

class FUUIDSpec extends mutable.Specification with ScalaCheck {

  "FUUID.fromString" should {
    "Fail when parsing an invalid string" in {
      FUUID.fromString("What up yo!")
        .isLeft must_=== true
    }
    "Fail when parsing invalid uuid" in {
      FUUID.fromString("2630147c-4a18-4866-9bbd-b2d89acef83z").isLeft must_=== true
    }
    "Succeed when parsing a valid UUID" in {
      FUUID.randomFUUID[IO]
        .map(_.toString)
        .map(FUUID.fromString)
        .map(_.isRight)
        .unsafeRunSync must_=== true
    }
  }

  "FUUID.hashCode" should {
    "have same hashcode as uuid" in {
      val baseString = "00000000-075b-cd15-0000-0000075bcd15"
      // Easy in for testing
      val uuid = UUID.fromString(baseString)
      val fuuid = FUUID.fromUUID(uuid)
      fuuid.hashCode must_=== uuid.hashCode
    }
  }

  "FUUID.equals" should {
    "be equal for the same FUUID" in {
      val baseString = "00000000-075b-cd15-0000-0000075bcd15"
      // Easy in for testing
      val uuid = UUID.fromString(baseString)
      val fuuid = FUUID.fromUUID(uuid)
      fuuid.equals(fuuid) must_=== true
    }
  }

  "FUUID.eqv" should {
    "be equal for the same FUUID" in {
      val baseString = "00000000-075b-cd15-0000-0000075bcd15"
      // Easy in for testing
      val uuid = UUID.fromString(baseString)
      val fuuid = FUUID.fromUUID(uuid)
      fuuid.eqv(fuuid) must_=== true
    }
  }

  "FUUID.fuuid" should {
    "compile for a literal" in {
      FUUID.fuuid("00000000-075b-cd15-0000-0000075bcd15")
      ok
    }
  }

  // FUUID.fuuid("kasdfasd")



} 
Example 31
Source File: PlatformSpecificMethods.scala    From fuuid   with MIT License 5 votes vote down vote up
package io.chrisdavenport.fuuid

import cats._
import cats.implicits._
import java.util.UUID
import java.security.MessageDigest

object PlatformSpecificMethods {
  def nameBased[F[_]]: (FUUID, String, ApplicativeError[F, Throwable]) => F[FUUID] = (namespace, name, AE) =>
    Either
      .catchNonFatal(
        MessageDigest
          .getInstance("SHA-1")
          .digest(
            uuidBytes(namespace) ++
              name.getBytes("UTF-8")
          )
      )
      .map { bs =>
        val cs = bs.take(16) // Truncate 160 bits (20 bytes) SHA-1 to fit into our 128 bits of space
        cs(6) = (cs(6) & 0x0f).asInstanceOf[Byte] 
        cs
      }
      .flatMap(
        bs =>
          Either.catchNonFatal {
            val bb = java.nio.ByteBuffer.allocate(java.lang.Long.BYTES)
            bb.put(bs, 0, 8)
            bb.flip
            val most = bb.getLong
            bb.flip
            bb.put(bs, 8, 8)
            bb.flip
            val least = bb.getLong
            FUUID.fromUUID(new UUID(most, least))
          }
      )
      .liftTo[F](AE)

  private def uuidBytes(fuuid: FUUID): Array[Byte] = {
    val bb = java.nio.ByteBuffer.allocate(2 * java.lang.Long.BYTES)
    val uuid = FUUID.Unsafe.toUUID(fuuid)
    bb.putLong(uuid.getMostSignificantBits)
    bb.putLong(uuid.getLeastSignificantBits)
    bb.array
  }
} 
Example 32
Source File: IOEncryptionSuite.scala    From drizzle-spark   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.deploy.yarn

import java.io._
import java.nio.charset.StandardCharsets
import java.security.PrivilegedExceptionAction
import java.util.UUID

import org.apache.hadoop.security.{Credentials, UserGroupInformation}
import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach, Matchers}

import org.apache.spark._
import org.apache.spark.deploy.SparkHadoopUtil
import org.apache.spark.internal.config._
import org.apache.spark.serializer._
import org.apache.spark.storage._

class IOEncryptionSuite extends SparkFunSuite with Matchers with BeforeAndAfterAll
  with BeforeAndAfterEach {
  private[this] val blockId = new TempShuffleBlockId(UUID.randomUUID())
  private[this] val conf = new SparkConf()
  private[this] val ugi = UserGroupInformation.createUserForTesting("testuser", Array("testgroup"))
  private[this] val serializer = new KryoSerializer(conf)

  override def beforeAll(): Unit = {
    System.setProperty("SPARK_YARN_MODE", "true")
    ugi.doAs(new PrivilegedExceptionAction[Unit]() {
      override def run(): Unit = {
        conf.set(IO_ENCRYPTION_ENABLED, true)
        val creds = new Credentials()
        SecurityManager.initIOEncryptionKey(conf, creds)
        SparkHadoopUtil.get.addCurrentUserCredentials(creds)
      }
    })
  }

  override def afterAll(): Unit = {
    SparkEnv.set(null)
    System.clearProperty("SPARK_YARN_MODE")
  }

  override def beforeEach(): Unit = {
    super.beforeEach()
  }

  override def afterEach(): Unit = {
    super.afterEach()
    conf.set("spark.shuffle.compress", false.toString)
    conf.set("spark.shuffle.spill.compress", false.toString)
  }

  test("IO encryption read and write") {
    ugi.doAs(new PrivilegedExceptionAction[Unit] {
      override def run(): Unit = {
        conf.set(IO_ENCRYPTION_ENABLED, true)
        conf.set("spark.shuffle.compress", false.toString)
        conf.set("spark.shuffle.spill.compress", false.toString)
        testYarnIOEncryptionWriteRead()
      }
    })
  }

  test("IO encryption read and write with shuffle compression enabled") {
    ugi.doAs(new PrivilegedExceptionAction[Unit] {
      override def run(): Unit = {
        conf.set(IO_ENCRYPTION_ENABLED, true)
        conf.set("spark.shuffle.compress", true.toString)
        conf.set("spark.shuffle.spill.compress", true.toString)
        testYarnIOEncryptionWriteRead()
      }
    })
  }

  private[this] def testYarnIOEncryptionWriteRead(): Unit = {
    val plainStr = "hello world"
    val outputStream = new ByteArrayOutputStream()
    val serializerManager = new SerializerManager(serializer, conf)
    val wrappedOutputStream = serializerManager.wrapStream(blockId, outputStream)
    wrappedOutputStream.write(plainStr.getBytes(StandardCharsets.UTF_8))
    wrappedOutputStream.close()

    val encryptedBytes = outputStream.toByteArray
    val encryptedStr = new String(encryptedBytes)
    assert(plainStr !== encryptedStr)

    val inputStream = new ByteArrayInputStream(encryptedBytes)
    val wrappedInputStream = serializerManager.wrapStream(blockId, inputStream)
    val decryptedBytes = new Array[Byte](1024)
    val len = wrappedInputStream.read(decryptedBytes)
    val decryptedStr = new String(decryptedBytes, 0, len, StandardCharsets.UTF_8)
    assert(decryptedStr === plainStr)
  }
} 
Example 33
Source File: BlockId.scala    From drizzle-spark   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.storage

import java.util.UUID

import org.apache.spark.annotation.DeveloperApi


  def apply(id: String): BlockId = id match {
    case RDD(rddId, splitIndex) =>
      RDDBlockId(rddId.toInt, splitIndex.toInt)
    case SHUFFLE(shuffleId, mapId, reduceId) =>
      ShuffleBlockId(shuffleId.toInt, mapId.toInt, reduceId.toInt)
    case SHUFFLE_DATA(shuffleId, mapId, reduceId) =>
      ShuffleDataBlockId(shuffleId.toInt, mapId.toInt, reduceId.toInt)
    case SHUFFLE_INDEX(shuffleId, mapId, reduceId) =>
      ShuffleIndexBlockId(shuffleId.toInt, mapId.toInt, reduceId.toInt)
    case BROADCAST(broadcastId, field) =>
      BroadcastBlockId(broadcastId.toLong, field.stripPrefix("_"))
    case TASKRESULT(taskId) =>
      TaskResultBlockId(taskId.toLong)
    case STREAM(streamId, uniqueId) =>
      StreamBlockId(streamId.toInt, uniqueId.toLong)
    case TEST(value) =>
      TestBlockId(value)
    case _ =>
      throw new IllegalStateException("Unrecognized BlockId: " + id)
  }
} 
Example 34
Source File: JsonSpec.scala    From kanadi   with MIT License 5 votes vote down vote up
package org.zalando.kanadi
package api

import java.util.UUID

import cats.syntax.either._
import cats.instances.either._
import org.specs2.Specification
import org.specs2.specification.core.SpecStructure
import io.circe._
import io.circe.parser._
import io.circe.syntax._
import org.zalando.kanadi.models.{EventId, SpanCtx}
import java.time.OffsetDateTime

import io.circe.CursorOp.DownField

class JsonSpec extends Specification {
  override def is: SpecStructure = s2"""
    Parse business events         $businessEvent
    Parse data events             $dataEvent
    Parse undefined events        $undefinedEvent
    SpanCtx decoding example      $decodeSpnCtx
    SpanCtx encoding example      $encodeSpnCtx
    SpanCtx fail decoding example $badDecodeSpnCtx
    """

  val uuid      = UUID.randomUUID()
  val testEvent = SomeEvent("Bart", "Simpson", uuid)
  val now       = OffsetDateTime.now()
  val md        = Metadata(eid = EventId("4ae5011e-eb01-11e5-8b4a-1c6f65464fc6"), occurredAt = now)

  val coreEventJson = s"""
    "first_name": "Bart",
    "last_name": "Simpson",
    "uuid": "${uuid.toString}"
  """

  val metadata =
    s""""eid": "4ae5011e-eb01-11e5-8b4a-1c6f65464fc6", "occurred_at": ${now.asJson}"""

  val businessEventJson = s"""{
    "metadata": {$metadata},
    $coreEventJson
  }"""

  val dataEventJson = s"""{
    "metadata": {$metadata},
    "data_op": "C",
    "data": {$coreEventJson},
    "data_type": "blah"
  }"""

  val undefinedEventJson = s"{$coreEventJson}"

  def businessEvent =
    decode[Event[SomeEvent]](businessEventJson) must beRight(Event.Business(testEvent, md))

  def dataEvent =
    decode[Event[SomeEvent]](dataEventJson) must beRight(Event.DataChange(testEvent, "blah", DataOperation.Create, md))

  def undefinedEvent =
    decode[Event[SomeEvent]](undefinedEventJson) must beRight(Event.Undefined(testEvent))

  // Sample data is taken from official Nakadi source at https://github.com/zalando/nakadi/blob/effb2ed7e95bd329ab73ce06b2857aa57510e539/src/test/java/org/zalando/nakadi/validation/JSONSchemaValidationTest.java

  val spanCtxJson =
    """{"eid":"5678","occurred_at":"1992-08-03T10:00:00Z","span_ctx":{"ot-tracer-spanid":"b268f901d5f2b865","ot-tracer-traceid":"e9435c17dabe8238","ot-baggage-foo":"bar"}}"""

  val spanCtxBadJson =
    """{"eid":"5678","occurred_at":"1992-08-03T10:00:00Z","span_ctx":{"ot-tracer-spanid":"b268f901d5f2b865","ot-tracer-traceid":42,"ot-baggage-foo":"bar"}}"""

  val spanCtxEventMetadata = Metadata(
    eid = EventId("5678"),
    occurredAt = OffsetDateTime.parse("1992-08-03T10:00:00Z"),
    spanCtx = Some(
      SpanCtx(
        Map(
          "ot-tracer-spanid"  -> "b268f901d5f2b865",
          "ot-tracer-traceid" -> "e9435c17dabe8238",
          "ot-baggage-foo"    -> "bar"
        )))
  )

  def decodeSpnCtx =
    decode[Metadata](spanCtxJson) must beRight(spanCtxEventMetadata)

  def encodeSpnCtx =
    spanCtxEventMetadata.asJson.pretty(Printer.noSpaces.copy(dropNullValues = true)) mustEqual spanCtxJson

  def badDecodeSpnCtx =
    decode[Metadata](spanCtxBadJson) must beLeft(
      DecodingFailure("String", List(DownField("ot-tracer-traceid"), DownField("span_ctx"))))
} 
Example 35
Source File: SomeEvent.scala    From kanadi   with MIT License 5 votes vote down vote up
package org.zalando.kanadi

import java.util.UUID

import io.circe.{Decoder, Encoder}

case class SomeEvent(firstName: String, lastName: String, uuid: UUID)

object SomeEvent {
  implicit val someEventEncoder: Encoder[SomeEvent] = Encoder.forProduct3(
    "first_name",
    "last_name",
    "uuid"
  )(x => SomeEvent.unapply(x).get)
  implicit val someEventDecoder: Decoder[SomeEvent] = Decoder.forProduct3(
    "first_name",
    "last_name",
    "uuid"
  )(SomeEvent.apply)
} 
Example 36
Source File: SubscriptionsSpec.scala    From kanadi   with MIT License 5 votes vote down vote up
package org.zalando.kanadi

import java.util.UUID

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import com.typesafe.config.ConfigFactory
import org.mdedetrich.webmodels.FlowId
import org.specs2.Specification
import org.specs2.concurrent.ExecutionEnv
import org.specs2.specification.core.SpecStructure
import org.specs2.specification.{AfterAll, BeforeAll}
import org.zalando.kanadi.api.{Category, EventType, EventTypes, Events, Subscription, Subscriptions}
import org.zalando.kanadi.models.{EventTypeName, SubscriptionId}

import scala.collection.parallel.mutable
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}

class SubscriptionsSpec(implicit ec: ExecutionEnv) extends Specification with Config with BeforeAll with AfterAll {
  override def is: SpecStructure = sequential ^ s2"""
      Create enough subscriptions to ensure that pagination is used $createEnoughSubscriptionsToUsePagination
    """

  val config = ConfigFactory.load()

  implicit val system       = ActorSystem()
  implicit val http         = Http()
  implicit val materializer = ActorMaterializer()

  val eventTypeName         = EventTypeName(s"Kanadi-Test-Event-${UUID.randomUUID().toString}")
  val OwningApplication     = "KANADI"
  val consumerGroup: String = UUID.randomUUID().toString
  val subscriptionsClient =
    Subscriptions(nakadiUri, None)
  val eventsClient = Events(nakadiUri, None)
  val eventsTypesClient =
    EventTypes(nakadiUri, None)
  val subscriptionIds: mutable.ParSet[SubscriptionId] = mutable.ParSet.empty

  eventTypeName.pp
  s"Consumer Group: $consumerGroup".pp

  def createEventType = eventsTypesClient.create(EventType(eventTypeName, OwningApplication, Category.Business))

  override def beforeAll =
    Await.result(createEventType, 10 seconds)

  override def afterAll = {
    Await.result(
      for {
        res1 <- Future.sequence(subscriptionIds.toList.map(s => subscriptionsClient.delete(s)))
        res2 <- eventsTypesClient.delete(eventTypeName)
      } yield (res1, res2),
      10 seconds
    )
    ()
  }

  def createEnoughSubscriptionsToUsePagination = (name: String) => {
    implicit val flowId: FlowId = Utils.randomFlowId()
    flowId.pp(name)

    val createdSubscriptions = Future.sequence(for {
      _ <- 1 to 22
      subscription = subscriptionsClient.create(
        Subscription(None, s"$OwningApplication-${UUID.randomUUID().toString}", Some(List(eventTypeName))))
    } yield {
      subscription.foreach { s =>
        subscriptionIds += s.id.get
      }
      subscription
    })

    val retrievedSubscriptions = (for {
      subscriptions <- createdSubscriptions
      retrievedSubscription = Future.sequence(subscriptions.map { subscription =>
        subscriptionsClient.createIfDoesntExist(subscription)
      })
    } yield retrievedSubscription).flatMap(a => a)

    Await.result(createdSubscriptions, 10 seconds) mustEqual Await.result(retrievedSubscriptions, 10 seconds)
  }

} 
Example 37
Source File: EncryptedKeyJsonCodec.scala    From mantis   with Apache License 2.0 5 votes vote down vote up
package io.iohk.ethereum.keystore

import java.util.UUID

import akka.util.ByteString
import io.iohk.ethereum.domain.Address
import io.iohk.ethereum.keystore.EncryptedKey._
import org.json4s.JsonAST.{JObject, JString, JValue}
import org.json4s.JsonDSL._
import org.json4s.native.JsonMethods._
import org.json4s.{CustomSerializer, DefaultFormats, Extraction, JField}
import org.spongycastle.util.encoders.Hex

import scala.util.Try

object EncryptedKeyJsonCodec {

  private val byteStringSerializer = new CustomSerializer[ByteString](_ => (
    { case JString(s) => ByteString(Hex.decode(s)) },
    { case bs: ByteString => JString(Hex.toHexString(bs.toArray)) }
  ))

  private implicit val formats = DefaultFormats + byteStringSerializer

  private def asHex(bs: ByteString): String =
    Hex.toHexString(bs.toArray)

  def toJson(encKey: EncryptedKey): String = {
    import encKey._
    import cryptoSpec._

    val json =
      ("id" -> id.toString) ~
      ("address" -> asHex(address.bytes)) ~
      ("version" -> version) ~
      ("crypto" -> (
        ("cipher" -> cipher) ~
        ("ciphertext" -> asHex(ciphertext)) ~
        ("cipherparams" -> ("iv" -> asHex(iv))) ~
        encodeKdf(kdfParams) ~
        ("mac" -> asHex(mac))
      ))

    pretty(render(json))
  }

  def fromJson(jsonStr: String): Either[String, EncryptedKey] = Try {
    val json = parse(jsonStr).transformField { case JField(k, v) => JField(k.toLowerCase, v) }

    val uuid = UUID.fromString((json \ "id").extract[String])
    val address = Address((json \ "address").extract[String])
    val version = (json \ "version").extract[Int]

    val crypto = json \ "crypto"
    val cipher = (crypto \ "cipher").extract[String]
    val ciphertext = (crypto \ "ciphertext").extract[ByteString]
    val iv = (crypto \ "cipherparams" \ "iv").extract[ByteString]
    val mac = (crypto \ "mac").extract[ByteString]

    val kdfParams = extractKdf(crypto)
    val cryptoSpec = CryptoSpec(cipher, ciphertext, iv, kdfParams, mac)
    EncryptedKey(uuid, address, cryptoSpec, version)

  }.fold(ex => Left(ex.toString), encKey => Right(encKey))

  private def encodeKdf(kdfParams: KdfParams): JObject =
    kdfParams match {
      case ScryptParams(salt, n, r, p, dklen) =>
        ("kdf" -> Scrypt) ~
        ("kdfparams" -> Extraction.decompose(kdfParams))

      case Pbkdf2Params(salt, prf, c, dklen) =>
        ("kdf" -> Pbkdf2) ~
        ("kdfparams" -> Extraction.decompose(kdfParams))
    }

  private def extractKdf(crypto: JValue): KdfParams = {
    val kdf = (crypto \ "kdf").extract[String]
    kdf.toLowerCase match {
      case Scrypt =>
        (crypto \ "kdfparams").extract[ScryptParams]

      case Pbkdf2 =>
        (crypto \ "kdfparams").extract[Pbkdf2Params]
    }
  }

} 
Example 38
Source File: EncryptedKey.scala    From mantis   with Apache License 2.0 5 votes vote down vote up
package io.iohk.ethereum.keystore

import java.security.SecureRandom
import java.util.UUID

import akka.util.ByteString
import io.iohk.ethereum.crypto
import io.iohk.ethereum.crypto.SymmetricCipher
import io.iohk.ethereum.domain.Address
import io.iohk.ethereum.keystore.EncryptedKey._

object EncryptedKey {
  val AES128CTR = "aes-128-ctr"
  val AES128CBC = "aes-128-cbc"
  val Scrypt = "scrypt"
  val Pbkdf2 = "pbkdf2"

  sealed trait KdfParams
  case class ScryptParams(salt: ByteString, n: Int, r: Int, p: Int, dklen: Int) extends KdfParams
  case class Pbkdf2Params(salt: ByteString, prf: String, c: Int, dklen: Int) extends KdfParams

  case class CryptoSpec(
    cipher: String,
    ciphertext: ByteString,
    iv: ByteString,
    kdfParams: KdfParams,
    mac: ByteString)

  def apply(prvKey: ByteString, passphrase: String, secureRandom: SecureRandom): EncryptedKey = {
    val version = 3
    val uuid = UUID.randomUUID()
    val pubKey = crypto.pubKeyFromPrvKey(prvKey)
    val address = Address(crypto.kec256(pubKey))

    val salt = crypto.secureRandomByteString(secureRandom, 32)
    val kdfParams = ScryptParams(salt, 1 << 18, 8, 1, 32) //params used by Geth
    val dk = deriveKey(passphrase, kdfParams)

    val cipherName = AES128CTR
    val iv = crypto.secureRandomByteString(secureRandom, 16)
    val secret = dk.take(16)
    val ciphertext = getCipher(cipherName).encrypt(secret, iv, prvKey)

    val mac = createMac(dk, ciphertext)

    val cryptoSpec = CryptoSpec(cipherName, ciphertext, iv, kdfParams, mac)
    EncryptedKey(uuid, address, cryptoSpec, version)
  }

  private def getCipher(cipherName: String): SymmetricCipher =
    Map(AES128CBC -> crypto.AES_CBC, AES128CTR -> crypto.AES_CTR)(cipherName.toLowerCase)

  private def deriveKey(passphrase: String, kdfParams: KdfParams): ByteString =
    kdfParams match {
      case ScryptParams(salt, n, r, p, dklen) =>
        crypto.scrypt(passphrase, salt, n, r, p, dklen)

      case Pbkdf2Params(salt, prf, c, dklen) =>
        // prf is currently ignored, only hmac sha256 is used
        crypto.pbkdf2HMacSha256(passphrase, salt, c, dklen)
    }

  private def createMac(dk: ByteString, ciphertext: ByteString): ByteString =
    crypto.kec256(dk.slice(16, 32) ++ ciphertext)
}


case class EncryptedKey(
  id: UUID,
  address: Address,
  cryptoSpec: CryptoSpec,
  version: Int
) {

  def decrypt(passphrase: String): Either[String, ByteString] = {
    val dk = deriveKey(passphrase, cryptoSpec.kdfParams)
    val secret = dk.take(16)
    val decrypted = getCipher(cryptoSpec.cipher).decrypt(secret, cryptoSpec.iv, cryptoSpec.ciphertext)
    decrypted
      .filter(_ => createMac(dk, cryptoSpec.ciphertext) == cryptoSpec.mac)
      .map(Right(_))
      .getOrElse(Left("Couldn't decrypt key with given passphrase"))
  }
} 
Example 39
Source File: TodoRepositoryAPIImpl.scala    From scala-json-rpc   with MIT License 5 votes vote down vote up
package io.github.shogowada.scala.jsonrpc.example.e2e.websocket

import java.util.UUID

import io.github.shogowada.scala.jsonrpc.DisposableFunction1

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class TodoRepositoryAPIImpl extends TodoRepositoryAPI {

  var todos: Seq[Todo] = Seq()
  var observersById: Map[String, DisposableFunction1[TodoEvent, Future[Unit]]] = Map()

  override def add(description: String): Future[Todo] = this.synchronized {
    val todo = Todo(id = UUID.randomUUID().toString, description)
    todos = todos :+ todo

    notify(TodoEvent(todo, TodoEventTypes.Add))

    Future(todo)
  }

  override def remove(id: String): Future[Unit] = this.synchronized {
    val index = todos.indexWhere(todo => todo.id == id)
    if (index >= 0) {
      val todo = todos(index)
      todos = todos.patch(index, Seq(), 1)
      notify(TodoEvent(todo, TodoEventTypes.Remove))
    }
    Future()
  }

  override def register(observer: DisposableFunction1[TodoEvent, Future[Unit]]): Future[String] = this.synchronized {
    val id = UUID.randomUUID().toString
    observersById = observersById + (id -> observer)

    todos.map(todo => TodoEvent(todo, TodoEventTypes.Add))
        .foreach(todoEvent => notify(id, observer, todoEvent))

    Future(id)
  }

  override def unregister(observerId: String): Future[Unit] = this.synchronized {
    observersById.get(observerId).foreach(observer => {
      observersById = observersById - observerId
      observer.dispose()
    })
    Future()
  }

  private def notify(todoEvent: TodoEvent): Unit = {
    observersById.foreach {
      case (id, observer) => notify(id, observer, todoEvent)
    }
  }

  private def notify(observerId: String, observer: DisposableFunction1[TodoEvent, Future[Unit]], todoEvent: TodoEvent): Unit = {
    observer(todoEvent)
        .failed // Probably connection is lost.
        .foreach(_ => unregister(observerId))
  }
} 
Example 40
Source File: DisposableFunctionMethodNameRepository.scala    From scala-json-rpc   with MIT License 5 votes vote down vote up
package io.github.shogowada.scala.jsonrpc.client

import java.util.UUID

import io.github.shogowada.scala.jsonrpc.{Constants, DisposableFunction}

class DisposableFunctionMethodNameRepository {

  private var identifierToMethodNameMap: Map[Any, String] = Map.empty
  private var methodNameToIdentifierMap: Map[String, Any] = Map.empty

  def getOrAddAndNotify(disposableFunction: DisposableFunction, notify: (String) => Unit): String = this.synchronized {
    val identifier = disposableFunction.identifier
    if (!identifierToMethodNameMap.contains(identifier)) {
      val methodName = Constants.FunctionMethodNamePrefix + UUID.randomUUID().toString
      identifierToMethodNameMap = identifierToMethodNameMap + (identifier -> methodName)
      methodNameToIdentifierMap = methodNameToIdentifierMap + (methodName -> identifier)
      notify(methodName)
      methodName
    } else {
      identifierToMethodNameMap(identifier)
    }
  }

  def remove(methodName: String): Unit = this.synchronized {
    methodNameToIdentifierMap.get(methodName)
        .foreach(identifier => {
          identifierToMethodNameMap = identifierToMethodNameMap - identifier
          methodNameToIdentifierMap = methodNameToIdentifierMap - methodName
        })
  }
} 
Example 41
Source File: UserServiceImpl.scala    From play-silhouette-4.0-slick-postgres-seed   with Apache License 2.0 5 votes vote down vote up
package models.services

import java.util.UUID
import javax.inject.Inject

import com.mohiva.play.silhouette.api.LoginInfo
import com.mohiva.play.silhouette.impl.providers.CommonSocialProfile
import models.User
import models.daos.UserDAO
import play.api.libs.concurrent.Execution.Implicits._

import scala.concurrent.Future


  def save(profile: CommonSocialProfile) = {
    userDAO.find(profile.loginInfo).flatMap {
      case Some(user) => // Update user with profile
        userDAO.save(user.copy(
          firstName = profile.firstName,
          lastName = profile.lastName,
          fullName = profile.fullName,
          email = profile.email,
          avatarURL = profile.avatarURL
        ))
      case None => // Insert a new user
        userDAO.save(User(
          userID = UUID.randomUUID(),
          loginInfo = profile.loginInfo,
          firstName = profile.firstName,
          lastName = profile.lastName,
          fullName = profile.fullName,
          email = profile.email,
          avatarURL = profile.avatarURL,
          activated = true
        ))
    }
  }
} 
Example 42
Source File: ResetPasswordController.scala    From play-silhouette-4.0-slick-postgres-seed   with Apache License 2.0 5 votes vote down vote up
package controllers.auth

import java.util.UUID
import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.util.{ PasswordHasherRegistry, PasswordInfo }
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import controllers.{ WebJarAssets, auth }
import forms.auth.ResetPasswordForm
import models.services.{ AuthTokenService, UserService }
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.{ Action, AnyContent, Controller }
import utils.auth.DefaultEnv

import scala.concurrent.Future


  def submit(token: UUID): Action[AnyContent] = silhouette.UnsecuredAction.async { implicit request =>
    authTokenService.validate(token).flatMap {
      case Some(authToken) =>
        ResetPasswordForm.form.bindFromRequest.fold(
          form => Future.successful(BadRequest(views.html.auth.resetPassword(form, token))),
          password => userService.retrieve(authToken.userID).flatMap {
            case Some(user) if user.loginInfo.providerID == CredentialsProvider.ID =>
              val passwordInfo = passwordHasherRegistry.current.hash(password)
              authInfoRepository.update[PasswordInfo](user.loginInfo, passwordInfo).map { _ =>
                Redirect(auth.routes.SignInController.view()).flashing("success" -> Messages("password.reset"))
              }
            case _ => Future.successful(Redirect(auth.routes.SignInController.view()).flashing("error" -> Messages("invalid.reset.link")))
          }
        )
      case None => Future.successful(Redirect(auth.routes.SignInController.view()).flashing("error" -> Messages("invalid.reset.link")))
    }
  }
} 
Example 43
Source File: SignUpController.scala    From play-silhouette-4.0-slick-postgres-seed   with Apache License 2.0 5 votes vote down vote up
package controllers.auth

import java.util.UUID
import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.services.AvatarService
import com.mohiva.play.silhouette.api.util.PasswordHasherRegistry
import com.mohiva.play.silhouette.impl.providers._
import controllers.{ WebJarAssets, auth }
import forms.auth.SignUpForm
import models.User
import models.services.{ AuthTokenService, UserService }
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.libs.mailer.{ Email, MailerClient }
import play.api.mvc.{ Action, AnyContent, Controller }
import utils.auth.DefaultEnv

import scala.concurrent.Future


  def submit: Action[AnyContent] = silhouette.UnsecuredAction.async { implicit request =>
    SignUpForm.form.bindFromRequest.fold(
      form => Future.successful(BadRequest(views.html.auth.signUp(form))),
      data => {
        val result = Redirect(auth.routes.SignUpController.view()).flashing("info" -> Messages("sign.up.email.sent", data.email))
        val loginInfo = LoginInfo(CredentialsProvider.ID, data.email)
        userService.retrieve(loginInfo).flatMap {
          case Some(user) =>
            val url = auth.routes.SignInController.view().absoluteURL()
            mailerClient.send(Email(
              subject = Messages("email.already.signed.up.subject"),
              from = Messages("email.from"),
              to = Seq(data.email),
              bodyText = Some(views.txt.emails.alreadySignedUp(user, url).body),
              bodyHtml = Some(views.html.emails.alreadySignedUp(user, url).body)
            ))

            Future.successful(result)
          case None =>
            val authInfo = passwordHasherRegistry.current.hash(data.password)
            val user = User(
              userID = UUID.randomUUID(),
              loginInfo = loginInfo,
              firstName = Some(data.firstName),
              lastName = Some(data.lastName),
              fullName = Some(data.firstName + " " + data.lastName),
              email = Some(data.email),
              avatarURL = None,
              activated = false
            )
            for {
              avatar <- avatarService.retrieveURL(data.email)
              user <- userService.save(user.copy(avatarURL = avatar))
              authInfo <- authInfoRepository.add(loginInfo, authInfo)
              authToken <- authTokenService.create(user.userID)
            } yield {
              val url = auth.routes.ActivateAccountController.activate(authToken.id).absoluteURL()
              mailerClient.send(Email(
                subject = Messages("email.sign.up.subject"),
                from = Messages("email.from"),
                to = Seq(data.email),
                bodyText = Some(views.txt.emails.signUp(user, url).body),
                bodyHtml = Some(views.html.emails.signUp(user, url).body)
              ))

              silhouette.env.eventBus.publish(SignUpEvent(user, request))
              result
            }
        }
      }
    )
  }
} 
Example 44
Source File: ActivateAccountController.scala    From play-silhouette-4.0-slick-postgres-seed   with Apache License 2.0 5 votes vote down vote up
package controllers.auth

import java.net.URLDecoder
import java.util.UUID
import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import controllers.{ WebJarAssets, auth }
import models.services.{ AuthTokenService, UserService }
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.libs.mailer.{ Email, MailerClient }
import play.api.mvc.{ Action, AnyContent, Controller }
import utils.auth.DefaultEnv

import scala.concurrent.Future
import scala.language.postfixOps


  def activate(token: UUID): Action[AnyContent] = silhouette.UnsecuredAction.async { implicit request =>
    authTokenService.validate(token).flatMap {
      case Some(authToken) => userService.retrieve(authToken.userID).flatMap {
        case Some(user) if user.loginInfo.providerID == CredentialsProvider.ID =>
          userService.save(user.copy(activated = true)).map { _ =>
            Redirect(auth.routes.SignInController.view()).flashing("success" -> Messages("account.activated"))
          }
        case _ => Future.successful(Redirect(auth.routes.SignInController.view()).flashing("error" -> Messages("invalid.activation.link")))
      }
      case None => Future.successful(Redirect(auth.routes.SignInController.view()).flashing("error" -> Messages("invalid.activation.link")))
    }
  }
} 
Example 45
Source File: SequenceRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.Sequence
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class SequenceRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.SequenceRepository[Sequence , Int]
    with SequenceMapping {

  def getById(id: Int): Future[Sequence] = {
    Future(run(querySequence.filter(_.sequenceId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[Sequence] = {
    Future(run(querySequence.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getBySequenceId(id : Int) : Future[List[Sequence]] = {
    Future(run(querySequence))
  }

  def getAll() : Future[List[Sequence]] = {
    Future(run(querySequence))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[Sequence]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countSequence()
      elements <- if (offset > count) Future.successful(Nil)
      else selectSequence(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countSequence() = {
    Future(run(querySequence.size).toInt)
  }


  private def selectSequence(offset: Int, limit: Int): Future[Seq[Sequence]] = {
    Future(run(querySequence).drop(offset).take(limit).toSeq)
  }
} 
Example 46
Source File: PrintFontRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.PrintFont
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class PrintFontRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.PrintFontRepository[PrintFont , Int]
    with PrintFontMapping {

  def getById(id: Int): Future[PrintFont] = {
    Future(run(queryPrintFont.filter(_.printFontId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[PrintFont] = {
    Future(run(queryPrintFont.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByPrintFontId(id : Int) : Future[List[PrintFont]] = {
    Future(run(queryPrintFont))
  }

  def getAll() : Future[List[PrintFont]] = {
    Future(run(queryPrintFont))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[PrintFont]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countPrintFont()
      elements <- if (offset > count) Future.successful(Nil)
      else selectPrintFont(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countPrintFont() = {
    Future(run(queryPrintFont.size).toInt)
  }

  private def selectPrintFont(offset: Int, limit: Int): Future[Seq[PrintFont]] = {
    Future(run(queryPrintFont).drop(offset).take(limit).toSeq)
  }
} 
Example 47
Source File: WindowAccessRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.WindowAccess
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class WindowAccessRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.WindowAccessRepository[WindowAccess , Int]
    with WindowAccessMapping {

  def getById(id: Int): Future[WindowAccess] = {
    getByRole(id , 0)
  }

  def getByRole(id: Int , role : Int): Future[WindowAccess] = {
    Future(run(queryWindowAccess.filter(windowAccess => windowAccess.windowId == lift(id)
      && windowAccess.roleId == lift(role))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[WindowAccess] = {
    Future(run(queryWindowAccess.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByWindowAccessId(id : Int) : Future[List[WindowAccess]] = {
    Future(run(queryWindowAccess))
  }

  def getAll() : Future[List[WindowAccess]] = {
    Future(run(queryWindowAccess))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[WindowAccess]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countWindowAccess()
      elements <- if (offset > count) Future.successful(Nil)
      else selectWindowAccess(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countWindowAccess() = {
    Future(run(queryWindowAccess.size).toInt)
  }


  private def selectWindowAccess(offset: Int, limit: Int): Future[Seq[WindowAccess]] = {
    Future(run(queryWindowAccess).drop(offset).take(limit).toSeq)
  }
} 
Example 48
Source File: UserDefinedFieldRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.UserDefinedField
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class UserDefinedFieldRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.UserDefinedFieldRepository[UserDefinedField , Int]
    with UserDefinedFieldMapping {

  def getById(id: Int): Future[UserDefinedField] = {
    Future(run(queryUserDefinedField.filter(_.userDefinedFieldId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[UserDefinedField] = {
    Future(run(queryUserDefinedField.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByUserDefinedFieldId(id : Int) : Future[List[UserDefinedField]] = {
    Future(run(queryUserDefinedField))
  }

  def getAll() : Future[List[UserDefinedField]] = {
    Future(run(queryUserDefinedField))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[UserDefinedField]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countUserDefinedField()
      elements <- if (offset > count) Future.successful(Nil)
      else selectUserDefinedField(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countUserDefinedField() = {
    Future(run(queryUserDefinedField.size).toInt)
  }


  private def selectUserDefinedField(offset: Int, limit: Int): Future[Seq[UserDefinedField]] = {
    Future(run(queryUserDefinedField).drop(offset).take(limit).toSeq)
  }
} 
Example 49
Source File: BrowseRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.Browse
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class BrowseRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.BrowseRepository[Browse , Int]
    with BrowseMapping {

  def getById(id: Int): Future[Browse] = {
    Future(run(queryBrowse.filter(_.browseId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[Browse] = {
    Future(run(queryBrowse.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByBrowseId(id : Int) : Future[List[Browse]] = {
    Future(run(queryBrowse))
  }

  def getAll() : Future[List[Browse]] = {
    Future(run(queryBrowse))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[Browse]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countBrowse()
      elements <- if (offset > count) Future.successful(Nil)
      else selectBrowse(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countBrowse() = {
    Future(run(queryBrowse.size).toInt)
  }

  private def selectBrowse(offset: Int, limit: Int): Future[Seq[Browse]] = {
    Future(run(queryBrowse).drop(offset).take(limit).toSeq)
  }
} 
Example 50
Source File: TreeFavoriteNodeRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.TreeFavoriteNode
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class TreeFavoriteNodeRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.TreeFavoriteNodeRepository[TreeFavoriteNode , Int]
    with TreeFavoriteNodeMapping {

  def getById(id: Int): Future[TreeFavoriteNode] = {
    Future(run(queryTreeFavoriteNode.filter(_.treeFavoriteNodeId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[TreeFavoriteNode] = {
    Future(run(queryTreeFavoriteNode.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByTreeFavoriteNodeId(id : Int) : Future[List[TreeFavoriteNode]] = {
    Future(run(queryTreeFavoriteNode))
  }

  def getAll() : Future[List[TreeFavoriteNode]] = {
    Future(run(queryTreeFavoriteNode))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[TreeFavoriteNode]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countTreeFavoriteNode()
      elements <- if (offset > count) Future.successful(Nil)
      else selectTreeFavoriteNode(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countTreeFavoriteNode() = {
    Future(run(queryTreeFavoriteNode.size).toInt)
  }


  private def selectTreeFavoriteNode(offset: Int, limit: Int): Future[Seq[TreeFavoriteNode]] = {
    Future(run(queryTreeFavoriteNode).drop(offset).take(limit).toSeq)
  }
} 
Example 51
Source File: WorkflowProcessDataRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.WorkflowProcessData
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class WorkflowProcessDataRepository(session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.WorkflowProcessDataRepository[WorkflowProcessData , Int]
    with WorkflowProcessDataMapping {

  def getById(id: Int): Future[WorkflowProcessData] = {
    Future(run(queryWorkflowProcessData.filter(_.workflowProcessDataId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[WorkflowProcessData] = {
    Future(run(queryWorkflowProcessData.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByWorkflowProcessDataId(id : Int) : Future[List[WorkflowProcessData]] = {
    Future(run(queryWorkflowProcessData))
  }

  def getAll() : Future[List[WorkflowProcessData]] = {
    Future(run(queryWorkflowProcessData))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[WorkflowProcessData]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countWorkflowProcessData()
      elements <- if (offset > count) Future.successful(Nil)
      else selectWorkflowProcessData(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countWorkflowProcessData() = {
    Future(run(queryWorkflowProcessData.size).toInt)
  }


  private def selectWorkflowProcessData(offset: Int, limit: Int): Future[Seq[WorkflowProcessData]] = {
    Future(run(queryWorkflowProcessData).drop(offset).take(limit).toSeq)
  }
} 
Example 52
Source File: WorkflowNodeTrlRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.WorkflowNodeTrl
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}




class WorkflowNodeTrlRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.WorkflowNodeTrlRepository[WorkflowNodeTrl , Int]
    with WorkflowNodeTrlMapping {

  def getById(id: Int): Future[WorkflowNodeTrl] = {
    getByLanguage(id , "en_US")
  }

  def getByLanguage(id: Int , lang : String): Future[WorkflowNodeTrl] = {
    Future(run(queryWorkflowNodeTrl.filter(workflowNode => workflowNode.workflowNodeId == lift(id)
      && workflowNode.language == lift(lang))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[WorkflowNodeTrl] = {
    Future(run(queryWorkflowNodeTrl.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByWorkflowNodeTrlId(id : Int) : Future[List[WorkflowNodeTrl]] = {
    Future(run(queryWorkflowNodeTrl))
  }

  def getAll() : Future[List[WorkflowNodeTrl]] = {
    Future(run(queryWorkflowNodeTrl))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[WorkflowNodeTrl]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countWorkflowNodeTrl()
      elements <- if (offset > count) Future.successful(Nil)
      else selectWorkflowNodeTrl(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countWorkflowNodeTrl() = {
    Future(run(queryWorkflowNodeTrl.size).toInt)
  }


  private def selectWorkflowNodeTrl(offset: Int, limit: Int): Future[Seq[WorkflowNodeTrl]] = {
    Future(run(queryWorkflowNodeTrl).drop(offset).take(limit).toSeq)
  }
} 
Example 53
Source File: UserOrganizationAccessRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.UserOrganizationAccess
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class UserOrganizationAccessRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.UserOrganizationAccessRepository[UserOrganizationAccess , Int]
    with UserOrganizationAccessMapping {

  def getById(id: Int): Future[UserOrganizationAccess] = {
    getByOrganization(id , 0)
  }

  def getByOrganization(id: Int , orgId : Int): Future[UserOrganizationAccess] = {
    Future(run(queryUserOrganizationAccess.filter(userOrganizationAccess => userOrganizationAccess.userId == lift(id)
      && userOrganizationAccess.organizationId == lift(orgId))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[UserOrganizationAccess] = {
    Future(run(queryUserOrganizationAccess.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByUserOrganizationAccessId(id : Int) : Future[List[UserOrganizationAccess]] = {
    Future(run(queryUserOrganizationAccess))
  }

  def getAll() : Future[List[UserOrganizationAccess]] = {
    Future(run(queryUserOrganizationAccess))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[UserOrganizationAccess]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countUserOrganizationAccess()
      elements <- if (offset > count) Future.successful(Nil)
      else selectUserOrganizationAccess(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countUserOrganizationAccess() = {
    Future(run(queryUserOrganizationAccess.size).toInt)
  }


  private def selectUserOrganizationAccess(offset: Int, limit: Int): Future[Seq[UserOrganizationAccess]] = {
    Future(run(queryUserOrganizationAccess).drop(offset).take(limit).toSeq)
  }
} 
Example 54
Source File: AlertRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.Alert
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class AlertRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.AlertRepository[Alert , Int]
    with AlertMapping {

  def getById(id: Int): Future[Alert] = {
    Future(run(queryAlert.filter(_.alertId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[Alert] = {
    Future(run(queryAlert.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByAlertId(id : Int) : Future[List[Alert]] = {
    Future(run(queryAlert))
  }

  def getAll() : Future[List[Alert]] = {
    Future(run(queryAlert))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[Alert]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countAlert()
      elements <- if (offset > count) Future.successful(Nil)
      else selectAlert(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countAlert() = {
    Future(run(queryAlert.size).toInt)
  }


  private def selectAlert(offset: Int, limit: Int): Future[Seq[Alert]] = {
    Future(run(queryAlert).drop(offset).take(limit).toSeq)
  }
} 
Example 55
Source File: FindRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.Find
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class FindRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.FindRepository[Find , Int]
    with FindMapping {

  def getById(id: Int): Future[Find] = {
    Future(run(queryFind.filter(_.findId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[Find] = {
    Future(run(queryFind.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByFindId(id : Int) : Future[List[Find]] = {
    Future(run(queryFind))
  }

  def getAll() : Future[List[Find]] = {
    Future(run(queryFind))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[Find]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countFind()
      elements <- if (offset > count) Future.successful(Nil)
      else selectFind(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countFind() = {
    Future(run(queryFind.size).toInt)
  }

  private def selectFind(offset: Int, limit: Int): Future[Seq[Find]] = {
    Future(run(queryFind).drop(offset).take(limit).toSeq)
  }
} 
Example 56
Source File: WorkflowNodeNextRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.WorkflowNodeNext
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class WorkflowNodeNextRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.WorkflowNodeNextRepository[WorkflowNodeNext , Int]
    with WorkflowNodeNextMapping {

  def getById(id: Int): Future[WorkflowNodeNext] = {
    Future(run(queryWorkflowNodeNext.filter(_.workflowNodeNextId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[WorkflowNodeNext] = {
    Future(run(queryWorkflowNodeNext.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByWorkflowNodeNextId(id : Int) : Future[List[WorkflowNodeNext]] = {
    Future(run(queryWorkflowNodeNext))
  }

  def getAll() : Future[List[WorkflowNodeNext]] = {
    Future(run(queryWorkflowNodeNext))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[WorkflowNodeNext]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countWorkflowNodeNext()
      elements <- if (offset > count) Future.successful(Nil)
      else selectWorkflowNodeNext(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countWorkflowNodeNext() = {
    Future(run(queryWorkflowNodeNext.size).toInt)
  }


  private def selectWorkflowNodeNext(offset: Int, limit: Int): Future[Seq[WorkflowNodeNext]] = {
    Future(run(queryWorkflowNodeNext).drop(offset).take(limit).toSeq)
  }
} 
Example 57
Source File: WorkbenchRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.Workbench
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class WorkbenchRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.WorkbenchRepository[Workbench , Int]
    with WorkbenchMapping {

  def getById(id: Int): Future[Workbench] = {
    Future(run(queryWorkbench.filter(_.workbenchId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[Workbench] = {
    Future(run(queryWorkbench.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByWorkbenchId(id : Int) : Future[List[Workbench]] = {
    Future(run(queryWorkbench))
  }

  def getAll() : Future[List[Workbench]] = {
    Future(run(queryWorkbench))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[Workbench]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countWorkbench()
      elements <- if (offset > count) Future.successful(Nil)
      else selectWorkbench(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countWorkbench() = {
    Future(run(queryWorkbench.size).toInt)
  }


  private def selectWorkbench(offset: Int, limit: Int): Future[Seq[Workbench]] = {
    Future(run(queryWorkbench).drop(offset).take(limit).toSeq)
  }
} 
Example 58
Source File: PackageExportRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.PackageExport
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class PackageExportRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.PackageExportRepository[PackageExport , Int]
    with PackageExportMapping {

  def getById(id: Int): Future[PackageExport] = {
    Future(run(queryPackageExport.filter(_.packageExportId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[PackageExport] = {
    Future(run(queryPackageExport.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByPackageExportId(id : Int) : Future[List[PackageExport]] = {
    Future(run(queryPackageExport))
  }

  def getAll() : Future[List[PackageExport]] = {
    Future(run(queryPackageExport))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[PackageExport]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countPackageExport()
      elements <- if (offset > count) Future.successful(Nil)
      else selectPackageExport(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countPackageExport() = {
    Future(run(queryPackageExport.size).toInt)
  }

  private def selectPackageExport(offset: Int, limit: Int): Future[Seq[PackageExport]] = {
    Future(run(queryPackageExport).drop(offset).take(limit).toSeq)
  }
} 
Example 59
Source File: ReferenceRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.Reference
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class ReferenceRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.ReferenceRepository[Reference , Int]
    with ReferenceMapping {

  def getById(id: Int): Future[Reference] = {
    Future(run(queryReference.filter(_.referenceId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[Reference] = {
    Future(run(queryReference.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByReferenceId(id : Int) : Future[List[Reference]] = {
    Future(run(queryReference))
  }

  def getAll() : Future[List[Reference]] = {
    Future(run(queryReference))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[Reference]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countReference()
      elements <- if (offset > count) Future.successful(Nil)
      else selectReference(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countReference() = {
    Future(run(queryReference.size).toInt)
  }


  private def selectReference(offset: Int, limit: Int): Future[Seq[Reference]] = {
    Future(run(queryReference).drop(offset).take(limit).toSeq)
  }
} 
Example 60
Source File: PinStanceParaRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.PinStancePara
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class PinStanceParaRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.PinStanceParaRepository[PinStancePara , Int]
    with PinStanceParaMapping {

  def getById(id: Int): Future[PinStancePara] = {
    getBySeqNo(id , 10)
  }

  def getBySeqNo(id: Int , seqNo : Int): Future[PinStancePara] = {
    Future(run(queryPinStancePara.filter(pinStancePara => pinStancePara.pinStanceId == lift(id)
      && pinStancePara.seqNo == lift(seqNo))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[PinStancePara] = {
    Future(run(queryPinStancePara.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByPinStanceParaId(id : Int) : Future[List[PinStancePara]] = {
    Future(run(queryPinStancePara))
  }

  def getAll() : Future[List[PinStancePara]] = {
    Future(run(queryPinStancePara))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[PinStancePara]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countPinStancePara()
      elements <- if (offset > count) Future.successful(Nil)
      else selectPinStancePara(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countPinStancePara() = {
    Future(run(queryPinStancePara.size).toInt)
  }

  private def selectPinStancePara(offset: Int, limit: Int): Future[Seq[PinStancePara]] = {
    Future(run(queryPinStancePara).drop(offset).take(limit).toSeq)
  }
} 
Example 61
Source File: ChangeLogRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.ChangeLog
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class ChangeLogRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.ChangeLogRepository[ChangeLog , Int]
    with ChangeLogMapping {

  def getById(id: Int): Future[ChangeLog] = {
    Future(run(queryChangeLog.filter(_.changeLogId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[ChangeLog] = {
    Future(run(queryChangeLog.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByChangeLogId(id : Int) : Future[List[ChangeLog]] = {
    Future(run(queryChangeLog))
  }

  def getAll() : Future[List[ChangeLog]] = {
    Future(run(queryChangeLog))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[ChangeLog]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countChangeLog()
      elements <- if (offset > count) Future.successful(Nil)
      else selectChangeLog(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countChangeLog() = {
    Future(run(queryChangeLog.size).toInt)
  }

  private def selectChangeLog(offset: Int, limit: Int): Future[Seq[ChangeLog]] = {
    Future(run(queryChangeLog).drop(offset).take(limit).toSeq)
  }
} 
Example 62
Source File: TabTrlRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.TabTrl
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class TabTrlRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.TabTrlRepository[TabTrl , Int]
    with TabTrlMapping {

  def getById(id: Int): Future[TabTrl] = {
    getByLanguage(id , "en_US")
  }

  def getByLanguage(id: Int , lang : String): Future[TabTrl] = {
    Future(run(queryTabTrl.filter(tab => tab.tabId == lift(id)
      && tab.language == lift(lang))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[TabTrl] = {
    Future(run(queryTabTrl.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByTabTrlId(id : Int) : Future[List[TabTrl]] = {
    Future(run(queryTabTrl))
  }

  def getAll() : Future[List[TabTrl]] = {
    Future(run(queryTabTrl))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[TabTrl]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countTabTrl()
      elements <- if (offset > count) Future.successful(Nil)
      else selectTabTrl(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countTabTrl() = {
    Future(run(queryTabTrl.size).toInt)
  }


  private def selectTabTrl(offset: Int, limit: Int): Future[Seq[TabTrl]] = {
    Future(run(queryTabTrl).drop(offset).take(limit).toSeq)
  }
} 
Example 63
Source File: AlertRecipientRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.AlertRecipient
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class AlertRecipientRepository(session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.AlertRecipientRepository[AlertRecipient , Int]
    with AlertRecipientMapping {

  def getById(id: Int): Future[AlertRecipient] = {
    Future(run(queryAlertRecipient.filter(_.alertRecipientId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[AlertRecipient] = {
    Future(run(queryAlertRecipient.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByAlertRecipientId(id : Int) : Future[List[AlertRecipient]] = {
    Future(run(queryAlertRecipient))
  }

  def getAll() : Future[List[AlertRecipient]] = {
    Future(run(queryAlertRecipient))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[AlertRecipient]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countAlertRecipient()
      elements <- if (offset > count) Future.successful(Nil)
      else selectAlertRecipient(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countAlertRecipient() = {
    Future(run(queryAlertRecipient.size).toInt)
  }

  private def selectAlertRecipient(offset: Int, limit: Int): Future[Seq[AlertRecipient]] = {
    Future(run(queryAlertRecipient).drop(offset).take(limit).toSeq)
  }
} 
Example 64
Source File: PreferenceRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.Preference
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class PreferenceRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.PreferenceRepository[Preference , Int]
    with PreferenceMapping {

  def getById(id: Int): Future[Preference] = {
    Future(run(queryPreference.filter(_.preferenceId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[Preference] = {
    Future(run(queryPreference.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByPreferenceId(id : Int) : Future[List[Preference]] = {
    Future(run(queryPreference))
  }

  def getAll() : Future[List[Preference]] = {
    Future(run(queryPreference))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[Preference]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countPreference()
      elements <- if (offset > count) Future.successful(Nil)
      else selectPreference(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countPreference() = {
    Future(run(queryPreference.size).toInt)
  }

  private def selectPreference(offset: Int, limit: Int): Future[Seq[Preference]] = {
    Future(run(queryPreference).drop(offset).take(limit).toSeq)
  }
} 
Example 65
Source File: UserQueryRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.UserQuery
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class UserQueryRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.UserQueryRepository[UserQuery , Int]
    with UserQueryMapping {

  def getById(id: Int): Future[UserQuery] = {
    Future(run(queryUserQuery.filter(_.userQueryId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[UserQuery] = {
    Future(run(queryUserQuery.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByUserQueryId(id : Int) : Future[List[UserQuery]] = {
    Future(run(queryUserQuery))
  }

  def getAll() : Future[List[UserQuery]] = {
    Future(run(queryUserQuery))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[UserQuery]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countUserQuery()
      elements <- if (offset > count) Future.successful(Nil)
      else selectUserQuery(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countUserQuery() = {
    Future(run(queryUserQuery.size).toInt)
  }


  private def selectUserQuery(offset: Int, limit: Int): Future[Seq[UserQuery]] = {
    Future(run(queryUserQuery).drop(offset).take(limit).toSeq)
  }
} 
Example 66
Source File: ProcessRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.Process
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class ProcessRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.ProcessRepository[Process , Int]
    with ProcessMapping {

  def getById(id: Int): Future[Process] = {
    Future(run(queryProcess.filter(_.processId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[Process] = {
    Future(run(queryProcess.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByProcessId(id : Int) : Future[List[Process]] = {
    Future(run(queryProcess))
  }

  def getAll() : Future[List[Process]] = {
    Future(run(queryProcess))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[Process]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countProcess()
      elements <- if (offset > count) Future.successful(Nil)
      else selectProcess(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countProcess() = {
    Future(run(queryProcess.size).toInt)
  }

  private def selectProcess(offset: Int, limit: Int): Future[Seq[Process]] = {
    Future(run(queryProcess).drop(offset).take(limit).toSeq)
  }
} 
Example 67
Source File: AlertProcessorRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.AlertProcessor
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class AlertProcessorRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.AlertProcessorRepository[AlertProcessor , Int]
    with AlertProcessorMapping {

  def getById(id: Int): Future[AlertProcessor] = {
    Future(run(queryAlertProcessor.filter(_.alertProcessorId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[AlertProcessor] = {
    Future(run(queryAlertProcessor.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByAlertProcessorId(id : Int) : Future[List[AlertProcessor]] = {
    Future(run(queryAlertProcessor))
  }

  def getAll() : Future[List[AlertProcessor]] = {
    Future(run(queryAlertProcessor))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[AlertProcessor]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countAlertProcessor()
      elements <- if (offset > count) Future.successful(Nil)
      else selectAlertProcessor(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countAlertProcessor() = {
    Future(run(queryAlertProcessor.size).toInt)
  }

  private def selectAlertProcessor(offset: Int, limit: Int): Future[Seq[AlertProcessor]] = {
    Future(run(queryAlertProcessor).drop(offset).take(limit).toSeq)
  }
} 
Example 68
Source File: RecordAccessRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.RecordAccess
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class RecordAccessRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.RecordAccessRepository[RecordAccess , Int]
    with RecordAccessMapping {

  def getById(id: Int): Future[RecordAccess] = {
    getByRole(id , 0)
  }

  def getByRole(id: Int , role : Int): Future[RecordAccess] = {
    Future(run(queryRecordAccess.filter(recordAccess => recordAccess.recordId == lift(id)
      && recordAccess.roleId == lift(role))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[RecordAccess] = {
    Future(run(queryRecordAccess.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByRecordAccessId(id : Int) : Future[List[RecordAccess]] = {
    Future(run(queryRecordAccess))
  }

  def getAll() : Future[List[RecordAccess]] = {
    Future(run(queryRecordAccess))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[RecordAccess]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countRecordAccess()
      elements <- if (offset > count) Future.successful(Nil)
      else selectRecordAccess(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countRecordAccess() = {
    Future(run(queryRecordAccess.size).toInt)
  }


  private def selectRecordAccess(offset: Int, limit: Int): Future[Seq[RecordAccess]] = {
    Future(run(queryRecordAccess).drop(offset).take(limit).toSeq)
  }
} 
Example 69
Source File: OrganizationInfoRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.OrganizationInfo
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class OrganizationInfoRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.OrganizationInfoRepository[OrganizationInfo , Int]
    with OrganizationInfoMapping {

  def getById(id: Int): Future[OrganizationInfo] = {
    Future(run(queryOrganizationInfo.filter(_.organizationId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[OrganizationInfo] = {
    Future(run(queryOrganizationInfo.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByOrganizationInfoId(id : Int) : Future[List[OrganizationInfo]] = {
    Future(run(queryOrganizationInfo))
  }

  def getAll() : Future[List[OrganizationInfo]] = {
    Future(run(queryOrganizationInfo))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[OrganizationInfo]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countOrganizationInfo()
      elements <- if (offset > count) Future.successful(Nil)
      else selectOrganizationInfo(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countOrganizationInfo() = {
    Future(run(queryOrganizationInfo.size).toInt)
  }

  private def selectOrganizationInfo(offset: Int, limit: Int): Future[Seq[OrganizationInfo]] = {
    Future(run(queryOrganizationInfo).drop(offset).take(limit).toSeq)
  }
} 
Example 70
Source File: TreeNodeU4Repository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.TreeNodeU4
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class TreeNodeU4Repository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.TreeNodeU4Repository[TreeNodeU4 , Int]
    with TreeNodeU4Mapping {

  def getById(id: Int): Future[TreeNodeU4] = {
    getByNode(id , 0)
  }

  def getByNode(id: Int , node : Int): Future[TreeNodeU4] = {
    Future(run(queryTreeNodeU4.filter(treeNodeU4 => treeNodeU4.treeId == lift(id)
      && treeNodeU4.nodeId == lift(node))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[TreeNodeU4] = {
    Future(run(queryTreeNodeU4.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByTreeNodeU4Id(id : Int) : Future[List[TreeNodeU4]] = {
    Future(run(queryTreeNodeU4))
  }

  def getAll() : Future[List[TreeNodeU4]] = {
    Future(run(queryTreeNodeU4))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[TreeNodeU4]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countTreeNodeU4()
      elements <- if (offset > count) Future.successful(Nil)
      else selectTreeNodeU4(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countTreeNodeU4() = {
    Future(run(queryTreeNodeU4.size).toInt)
  }


  private def selectTreeNodeU4(offset: Int, limit: Int): Future[Seq[TreeNodeU4]] = {
    Future(run(queryTreeNodeU4).drop(offset).take(limit).toSeq)
  }
} 
Example 71
Source File: InformationWindowRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.InformationWindow
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class InformationWindowRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.InformationWindowRepository[InformationWindow , Int]
    with InformationWindowMapping {

  def getById(id: Int): Future[InformationWindow] = {
    Future(run(queryInformationWindow.filter(_.infoWindowId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[InformationWindow] = {
    Future(run(queryInformationWindow.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByInformationWindowId(id : Int) : Future[List[InformationWindow]] = {
    Future(run(queryInformationWindow))
  }

  def getAll() : Future[List[InformationWindow]] = {
    Future(run(queryInformationWindow))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[InformationWindow]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countInformationWindow()
      elements <- if (offset > count) Future.successful(Nil)
      else selectInformationWindow(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countInformationWindow() = {
    Future(run(queryInformationWindow.size).toInt)
  }

  private def selectInformationWindow(offset: Int, limit: Int): Future[Seq[InformationWindow]] = {
    Future(run(queryInformationWindow).drop(offset).take(limit).toSeq)
  }
} 
Example 72
Source File: ImportFormatRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.ImportFormat
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class ImportFormatRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.ImportFormatRepository[ImportFormat , Int]
    with ImportFormatMapping {

  def getById(id: Int): Future[ImportFormat] = {
    Future(run(queryImportFormat.filter(_.importFormatId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[ImportFormat] = {
    Future(run(queryImportFormat.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByImportFormatId(id : Int) : Future[List[ImportFormat]] = {
    Future(run(queryImportFormat))
  }

  def getAll() : Future[List[ImportFormat]] = {
    Future(run(queryImportFormat))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[ImportFormat]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countImportFormat()
      elements <- if (offset > count) Future.successful(Nil)
      else selectImportFormat(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countImportFormat() = {
    Future(run(queryImportFormat.size).toInt)
  }

  private def selectImportFormat(offset: Int, limit: Int): Future[Seq[ImportFormat]] = {
    Future(run(queryImportFormat).drop(offset).take(limit).toSeq)
  }
} 
Example 73
Source File: UserBusinessPartnerAccessRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.UserBusinessPartnerAccess
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class UserBusinessPartnerAccessRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.UserBusinessPartnerAccessRepository[UserBusinessPartnerAccess , Int]
    with UserBusinessPartnerAccessMapping {

  def getById(id: Int): Future[UserBusinessPartnerAccess] = {
    Future(run(queryUserBusinessPartnerAccess.filter(_.userBusinessPartnerAccessId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[UserBusinessPartnerAccess] = {
    Future(run(queryUserBusinessPartnerAccess.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByUserBusinessPartnerAccessId(id : Int) : Future[List[UserBusinessPartnerAccess]] = {
    Future(run(queryUserBusinessPartnerAccess))
  }

  def getAll() : Future[List[UserBusinessPartnerAccess]] = {
    Future(run(queryUserBusinessPartnerAccess))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[UserBusinessPartnerAccess]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countUserBusinessPartnerAccess()
      elements <- if (offset > count) Future.successful(Nil)
      else selectUserBusinessPartnerAccess(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countUserBusinessPartnerAccess() = {
    Future(run(queryUserBusinessPartnerAccess.size).toInt)
  }


  private def selectUserBusinessPartnerAccess(offset: Int, limit: Int): Future[Seq[UserBusinessPartnerAccess]] = {
    Future(run(queryUserBusinessPartnerAccess).drop(offset).take(limit).toSeq)
  }
} 
Example 74
Source File: TaskTrlRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.TaskTrl
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class TaskTrlRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.TaskTrlRepository[TaskTrl , Int]
    with TaskTrlMapping {

  def getById(id: Int): Future[TaskTrl] = {
    getByLanguage(id , "en_US")
  }

  def getByLanguage(id: Int , lang : String): Future[TaskTrl] = {
    Future(run(queryTaskTrl.filter(task => task.taskId == lift(id)
      && task.language == lift(lang))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[TaskTrl] = {
    Future(run(queryTaskTrl.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByTaskTrlId(id : Int) : Future[List[TaskTrl]] = {
    Future(run(queryTaskTrl))
  }

  def getAll() : Future[List[TaskTrl]] = {
    Future(run(queryTaskTrl))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[TaskTrl]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countTaskTrl()
      elements <- if (offset > count) Future.successful(Nil)
      else selectTaskTrl(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countTaskTrl() = {
    Future(run(queryTaskTrl.size).toInt)
  }


  private def selectTaskTrl(offset: Int, limit: Int): Future[Seq[TaskTrl]] = {
    Future(run(queryTaskTrl).drop(offset).take(limit).toSeq)
  }
} 
Example 75
Source File: EntityRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.{Attribute, Entity}
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}


class EntityRepository(session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.EntityRepository[Entity , Int]
  with EntityMapping
  with AttributeMapping {

  def getById(id: Int): Future[Entity] = {
    Future(run(queryEntity.filter(_.entityId == lift(id))).headOption.get)
  }

  def getAttributes(id: Int): Future[List[Attribute]] = {
    Future(run(queryAttribute.filter(_.entityId == lift(id))))
  }

  def getByUUID(uuid: UUID): Future[Entity] = {
    Future(run(queryEntity.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getAll() : Future[List[Entity]] = {
    Future(run(queryEntity))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[Entity]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countEntity()
      elements <- if (offset > count) Future.successful(Nil)
      else selectEntity(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countEntity() = {
    Future(run(queryEntity.size).toInt)
  }

  private def selectEntity(offset: Int, limit: Int): Future[Seq[Entity]] = {
    Future(run(queryEntity).drop(offset).take(limit).toSeq)
  }
} 
Example 76
Source File: WorkflowBlockRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.WorkflowBlock
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class WorkflowBlockRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.WorkflowBlockRepository[WorkflowBlock , Int]
    with WorkflowBlockMapping {

  def getById(id: Int): Future[WorkflowBlock] = {
    Future(run(queryWorkflowBlock.filter(_.workflowBlockId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[WorkflowBlock] = {
    Future(run(queryWorkflowBlock.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByWorkflowBlockId(id : Int) : Future[List[WorkflowBlock]] = {
    Future(run(queryWorkflowBlock))
  }

  def getAll() : Future[List[WorkflowBlock]] = {
    Future(run(queryWorkflowBlock))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[WorkflowBlock]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countWorkflowBlock()
      elements <- if (offset > count) Future.successful(Nil)
      else selectWorkflowBlock(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countWorkflowBlock() = {
    Future(run(queryWorkflowBlock.size).toInt)
  }


  private def selectWorkflowBlock(offset: Int, limit: Int): Future[Seq[WorkflowBlock]] = {
    Future(run(queryWorkflowBlock).drop(offset).take(limit).toSeq)
  }
} 
Example 77
Source File: RoleOrganizationAccessRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.RoleOrganizationAccess
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class RoleOrganizationAccessRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.RoleOrganizationAccessRepository[RoleOrganizationAccess , Int]
    with RoleOrganizationAccessMapping {

  def getById(id: Int): Future[RoleOrganizationAccess] = {
    getByRole(id , 0)
  }

  def getByRole(id: Int , role : Int): Future[RoleOrganizationAccess] = {
    Future(run(queryRoleOrganizationAccess.filter(roleOrganizationAccess => roleOrganizationAccess.organizationId == lift(id)
      && roleOrganizationAccess.roleId == lift(role))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[RoleOrganizationAccess] = {
    Future(run(queryRoleOrganizationAccess.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByRoleOrganizationAccessId(id : Int) : Future[List[RoleOrganizationAccess]] = {
    Future(run(queryRoleOrganizationAccess))
  }

  def getAll() : Future[List[RoleOrganizationAccess]] = {
    Future(run(queryRoleOrganizationAccess))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[RoleOrganizationAccess]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countRoleOrganizationAccess()
      elements <- if (offset > count) Future.successful(Nil)
      else selectRoleOrganizationAccess(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countRoleOrganizationAccess() = {
    Future(run(queryRoleOrganizationAccess.size).toInt)
  }


  private def selectRoleOrganizationAccess(offset: Int, limit: Int): Future[Seq[RoleOrganizationAccess]] = {
    Future(run(queryRoleOrganizationAccess).drop(offset).take(limit).toSeq)
  }
} 
Example 78
Source File: ZoomConditionRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.ZoomCondition
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class ZoomConditionRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.ZoomConditionRepository[ZoomCondition , Int]
    with ZoomConditionMapping {

  def getById(id: Int): Future[ZoomCondition] = {
    Future(run(queryZoomCondition.filter(_.zoomConditionId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[ZoomCondition] = {
    Future(run(queryZoomCondition.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByZoomConditionId(id : Int) : Future[List[ZoomCondition]] = {
    Future(run(queryZoomCondition))
  }

  def getAll() : Future[List[ZoomCondition]] = {
    Future(run(queryZoomCondition))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[ZoomCondition]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countZoomCondition()
      elements <- if (offset > count) Future.successful(Nil)
      else selectZoomCondition(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countZoomCondition() = {
    Future(run(queryZoomCondition.size).toInt)
  }


  private def selectZoomCondition(offset: Int, limit: Int): Future[Seq[ZoomCondition]] = {
    Future(run(queryZoomCondition).drop(offset).take(limit).toSeq)
  }
} 
Example 79
Source File: MigrationRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.Migration
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class MigrationRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.MigrationRepository[Migration , Int]
    with MigrationMapping {

  def getById(id: Int): Future[Migration] = {
    Future(run(queryMigration.filter(_.migrationId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[Migration] = {
    Future(run(queryMigration.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByMigrationId(id : Int) : Future[List[Migration]] = {
    Future(run(queryMigration))
  }

  def getAll() : Future[List[Migration]] = {
    Future(run(queryMigration))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[Migration]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countMigration()
      elements <- if (offset > count) Future.successful(Nil)
      else selectMigration(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countMigration() = {
    Future(run(queryMigration.size).toInt)
  }

  private def selectMigration(offset: Int, limit: Int): Future[Seq[Migration]] = {
    Future(run(queryMigration).drop(offset).take(limit).toSeq)
  }
} 
Example 80
Source File: SearchDefinitionRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.SearchDefinition
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class SearchDefinitionRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.SearchDefinitionRepository[SearchDefinition , Int]
    with SearchDefinitionMapping {

  def getById(id: Int): Future[SearchDefinition] = {
    Future(run(querySearchDefinition.filter(_.searchDefinitionId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[SearchDefinition] = {
    Future(run(querySearchDefinition.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getBySearchDefinitionId(id : Int) : Future[List[SearchDefinition]] = {
    Future(run(querySearchDefinition))
  }

  def getAll() : Future[List[SearchDefinition]] = {
    Future(run(querySearchDefinition))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[SearchDefinition]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countSearchDefinition()
      elements <- if (offset > count) Future.successful(Nil)
      else selectSearchDefinition(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countSearchDefinition() = {
    Future(run(querySearchDefinition.size).toInt)
  }


  private def selectSearchDefinition(offset: Int, limit: Int): Future[Seq[SearchDefinition]] = {
    Future(run(querySearchDefinition).drop(offset).take(limit).toSeq)
  }
} 
Example 81
Source File: IssueRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.Issue
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class IssueRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.IssueRepository[Issue , Int]
    with IssueMapping {

  def getById(id: Int): Future[Issue] = {
    Future(run(queryIssue.filter(_.issueId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[Issue] = {
    Future(run(queryIssue.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByIssueId(id : Int) : Future[List[Issue]] = {
    Future(run(queryIssue))
  }

  def getAll() : Future[List[Issue]] = {
    Future(run(queryIssue))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[Issue]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countIssue()
      elements <- if (offset > count) Future.successful(Nil)
      else selectIssue(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countIssue() = {
    Future(run(queryIssue.size).toInt)
  }

  private def selectIssue(offset: Int, limit: Int): Future[Seq[Issue]] = {
    Future(run(queryIssue).drop(offset).take(limit).toSeq)
  }
} 
Example 82
Source File: ElementRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.Element
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}


class ElementRepository(session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.ElementRepository[Element , Int]
    with ElementMapping {

  def getById(id: Int): Future[Element] = {
    Future(run(queryElement.filter(_.elementId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[Element] = {
    Future(run(queryElement.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getAll() : Future[List[Element]] = {
    Future(run(queryElement))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[Element]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countElement()
      elements <- if (offset > count) Future.successful(Nil)
      else selectElement(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countElement() = {
    Future(run(queryElement.size).toInt)
  }


  private def selectElement(offset: Int, limit: Int): Future[Seq[Element]] = {
    Future(run(queryElement).drop(offset).take(limit).toSeq)
  }
} 
Example 83
Source File: ArchiveRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.Archive
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class ArchiveRepository(session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.ArchiveRepository[Archive , Int]
    with ArchiveMapping {

  def getById(id: Int): Future[Archive] = {
    Future(run(queryArchive.filter(_.archiveId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[Archive] = {
    Future(run(queryArchive.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByArchiveId(id : Int) : Future[List[Archive]] = {
    Future(run(queryArchive))
  }

  def getAll() : Future[List[Archive]] = {
    Future(run(queryArchive))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[Archive]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countArchive()
      elements <- if (offset > count) Future.successful(Nil)
      else selectArchive(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countArchive() = {
    Future(run(queryArchive.size).toInt)
  }

  private def selectArchive(offset: Int, limit: Int): Future[Seq[Archive]] = {
    Future(run(queryArchive).drop(offset).take(limit).toSeq)
  }
} 
Example 84
Source File: AttributeProcessRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.AttributeProcess
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}

class AttributeProcessRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.AttributeProcessRepository[AttributeProcess , Int]
    with AttributeProcessMapping {

  def getById(id: Int): Future[AttributeProcess] = {
    Future(run(queryAttributeProcess.filter(_.attributeProcessId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[AttributeProcess] = {
    Future(run(queryAttributeProcess.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByAttributeProcessId(id : Int) : Future[List[AttributeProcess]] = {
    Future(run(queryAttributeProcess))
  }

  def getAll() : Future[List[AttributeProcess]] = {
    Future(run(queryAttributeProcess))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[AttributeProcess]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countAttributeProcess()
      elements <- if (offset > count) Future.successful(Nil)
      else selectAttributeProcess(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countAttributeProcess() = {
    Future(run(queryAttributeProcess.size).toInt)
  }

  private def selectAttributeProcess(offset: Int, limit: Int): Future[Seq[AttributeProcess]] = {
    Future(run(queryAttributeProcess).drop(offset).take(limit).toSeq)
  }
} 
Example 85
Source File: MemoRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.Memo
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class MemoRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.MemoRepository[Memo , Int]
    with MemoMapping {

  def getById(id: Int): Future[Memo] = {
    Future(run(queryMemo.filter(_.memoId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[Memo] = {
    Future(run(queryMemo.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByMemoId(id : Int) : Future[List[Memo]] = {
    Future(run(queryMemo))
  }

  def getAll() : Future[List[Memo]] = {
    Future(run(queryMemo))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[Memo]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countMemo()
      elements <- if (offset > count) Future.successful(Nil)
      else selectMemo(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countMemo() = {
    Future(run(queryMemo.size).toInt)
  }

  private def selectMemo(offset: Int, limit: Int): Future[Seq[Memo]] = {
    Future(run(queryMemo).drop(offset).take(limit).toSeq)
  }
} 
Example 86
Source File: ColorRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.Color
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class ColorRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.ColorRepository[Color , Int]
    with ColorMapping {

  def getById(id: Int): Future[Color] = {
    Future(run(queryColor.filter(_.colorId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[Color] = {
    Future(run(queryColor.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByColorId(id : Int) : Future[List[Color]] = {
    Future(run(queryColor))
  }

  def getAll() : Future[List[Color]] = {
    Future(run(queryColor))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[Color]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countColor()
      elements <- if (offset > count) Future.successful(Nil)
      else selectColor(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countColor() = {
    Future(run(queryColor.size).toInt)
  }

  private def selectColor(offset: Int, limit: Int): Future[Seq[Color]] = {
    Future(run(queryColor).drop(offset).take(limit).toSeq)
  }
} 
Example 87
Source File: AlertRuleRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.AlertRule
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class AlertRuleRepository(session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.AlertRuleRepository[AlertRule , Int]
    with AlertRuleMapping {

  def getById(id: Int): Future[AlertRule] = {
    Future(run(queryAlertRule.filter(_.alertRuleId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[AlertRule] = {
    Future(run(queryAlertRule.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByAlertRuleId(id : Int) : Future[List[AlertRule]] = {
    Future(run(queryAlertRule))
  }

  def getAll() : Future[List[AlertRule]] = {
    Future(run(queryAlertRule))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[AlertRule]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countAlertRule()
      elements <- if (offset > count) Future.successful(Nil)
      else selectAlertRule(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countAlertRule() = {
    Future(run(queryAlertRule.size).toInt)
  }

  private def selectAlertRule(offset: Int, limit: Int): Future[Seq[AlertRule]] = {
    Future(run(queryAlertRule).drop(offset).take(limit).toSeq)
  }
} 
Example 88
Source File: UserDefinedTabRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.UserDefinedTab
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class UserDefinedTabRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.UserDefinedTabRepository[UserDefinedTab , Int]
    with UserDefinedTabMapping {

  def getById(id: Int): Future[UserDefinedTab] = {
    Future(run(queryUserDefinedTab.filter(_.userDefinedTabId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[UserDefinedTab] = {
    Future(run(queryUserDefinedTab.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByUserDefinedTabId(id : Int) : Future[List[UserDefinedTab]] = {
    Future(run(queryUserDefinedTab))
  }

  def getAll() : Future[List[UserDefinedTab]] = {
    Future(run(queryUserDefinedTab))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[UserDefinedTab]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countUserDefinedTab()
      elements <- if (offset > count) Future.successful(Nil)
      else selectUserDefinedTab(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countUserDefinedTab() = {
    Future(run(queryUserDefinedTab.size).toInt)
  }


  private def selectUserDefinedTab(offset: Int, limit: Int): Future[Seq[UserDefinedTab]] = {
    Future(run(queryUserDefinedTab).drop(offset).take(limit).toSeq)
  }
} 
Example 89
Source File: TreeNodeCMCRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.TreeNodeCMC
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class TreeNodeCMCRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.TreeNodeCMCRepository[TreeNodeCMC , Int]
    with TreeNodeCMCMapping {

  def getById(id: Int): Future[TreeNodeCMC] = {
    getByNode(id , 0)
  }

  def getByNode(id: Int , node : Int): Future[TreeNodeCMC] = {
    Future(run(queryTreeNodeCMC.filter(treeNodeCMC => treeNodeCMC.treeId == lift(id)
      && treeNodeCMC.nodeId == lift(node))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[TreeNodeCMC] = {
    Future(run(queryTreeNodeCMC.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByTreeNodeCMCId(id : Int) : Future[List[TreeNodeCMC]] = {
    Future(run(queryTreeNodeCMC))
  }

  def getAll() : Future[List[TreeNodeCMC]] = {
    Future(run(queryTreeNodeCMC))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[TreeNodeCMC]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countTreeNodeCMC()
      elements <- if (offset > count) Future.successful(Nil)
      else selectTreeNodeCMC(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countTreeNodeCMC() = {
    Future(run(queryTreeNodeCMC.size).toInt)
  }


  private def selectTreeNodeCMC(offset: Int, limit: Int): Future[Seq[TreeNodeCMC]] = {
    Future(run(queryTreeNodeCMC).drop(offset).take(limit).toSeq)
  }
} 
Example 90
Source File: PackageImportProcessRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.PackageImportProcess
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class PackageImportProcessRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.PackageImportProcessRepository[PackageImportProcess , Int]
    with PackageImportProcessMapping {

  def getById(id: Int): Future[PackageImportProcess] = {
    Future(run(queryPackageImportProcess.filter(_.packageImportProcessId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[PackageImportProcess] = {
    Future(run(queryPackageImportProcess.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByPackageImportProcessId(id : Int) : Future[List[PackageImportProcess]] = {
    Future(run(queryPackageImportProcess))
  }

  def getAll() : Future[List[PackageImportProcess]] = {
    Future(run(queryPackageImportProcess))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[PackageImportProcess]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countPackageImportProcess()
      elements <- if (offset > count) Future.successful(Nil)
      else selectPackageImportProcess(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countPackageImportProcess() = {
    Future(run(queryPackageImportProcess.size).toInt)
  }

  private def selectPackageImportProcess(offset: Int, limit: Int): Future[Seq[PackageImportProcess]] = {
    Future(run(queryPackageImportProcess).drop(offset).take(limit).toSeq)
  }
} 
Example 91
Source File: ChartDataSourceRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.ChartDataSource
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class ChartDataSourceRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.ChartDataSourceRepository[ChartDataSource , Int]
    with ChartDataSourceMapping {

  def getById(id: Int): Future[ChartDataSource] = {
    Future(run(queryChartDataSource.filter(_.chartDataSourceId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[ChartDataSource] = {
    Future(run(queryChartDataSource.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByChartDataSourceId(id : Int) : Future[List[ChartDataSource]] = {
    Future(run(queryChartDataSource))
  }

  def getAll() : Future[List[ChartDataSource]] = {
    Future(run(queryChartDataSource))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[ChartDataSource]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countChartDataSource()
      elements <- if (offset > count) Future.successful(Nil)
      else selectChartDataSource(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countChartDataSource() = {
    Future(run(queryChartDataSource.size).toInt)
  }

  private def selectChartDataSource(offset: Int, limit: Int): Future[Seq[ChartDataSource]] = {
    Future(run(queryChartDataSource).drop(offset).take(limit).toSeq)
  }
} 
Example 92
Source File: ReferenceEntityRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.ReferenceEntity
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class ReferenceEntityRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.ReferenceEntityRepository[ReferenceEntity , Int]
    with ReferenceEntityMapping {

  def getById(id: Int): Future[ReferenceEntity] = {
    Future(run(queryReferenceEntity.filter(_.referenceId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[ReferenceEntity] = {
    Future(run(queryReferenceEntity.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByReferenceEntityId(id : Int) : Future[List[ReferenceEntity]] = {
    Future(run(queryReferenceEntity))
  }

  def getAll() : Future[List[ReferenceEntity]] = {
    Future(run(queryReferenceEntity))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[ReferenceEntity]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countReferenceEntity()
      elements <- if (offset > count) Future.successful(Nil)
      else selectReferenceEntity(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countReferenceEntity() = {
    Future(run(queryReferenceEntity.size).toInt)
  }


  private def selectReferenceEntity(offset: Int, limit: Int): Future[Seq[ReferenceEntity]] = {
    Future(run(queryReferenceEntity).drop(offset).take(limit).toSeq)
  }
} 
Example 93
Source File: AttributeAccessRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.AttributeAccess
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class AttributeAccessRepository(session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.AttributeAccessRepository[AttributeAccess , Int]
    with AttributeAccessMapping {

  def getById(id: Int): Future[AttributeAccess] = {
    getByRole(id , 0)
  }

  def getByRole(id: Int , role : Int): Future[AttributeAccess] = {
    Future(run(queryAttributeAccess.filter(attributeAccess => attributeAccess.attributeId == lift(id)
      && attributeAccess.roleId == lift(role))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[AttributeAccess] = {
    Future(run(queryAttributeAccess.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByAttributeAccessId(id : Int) : Future[List[AttributeAccess]] = {
    Future(run(queryAttributeAccess))
  }

  def getAll() : Future[List[AttributeAccess]] = {
    Future(run(queryAttributeAccess))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[AttributeAccess]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countAttributeAccess()
      elements <- if (offset > count) Future.successful(Nil)
      else selectAttributeAccess(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countAttributeAccess() = {
    Future(run(queryAttributeAccess.size).toInt)
  }

  private def selectAttributeAccess(offset: Int, limit: Int): Future[Seq[AttributeAccess]] = {
    Future(run(queryAttributeAccess).drop(offset).take(limit).toSeq)
  }
} 
Example 94
Source File: WorkflowAccessRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.WorkflowAccess
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class WorkflowAccessRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.WorkflowAccessRepository[WorkflowAccess , Int]
    with WorkflowAccessMapping {

  def getById(id: Int): Future[WorkflowAccess] = {
    getByRole(id , 0)
  }

  def getByRole(id: Int , role : Int): Future[WorkflowAccess] = {
    Future(run(queryWorkflowAccess.filter(workflowAccess => workflowAccess.workflowId == lift(id)
      && workflowAccess.roleId == lift(role))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[WorkflowAccess] = {
    Future(run(queryWorkflowAccess.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByWorkflowAccessId(id : Int) : Future[List[WorkflowAccess]] = {
    Future(run(queryWorkflowAccess))
  }

  def getAll() : Future[List[WorkflowAccess]] = {
    Future(run(queryWorkflowAccess))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[WorkflowAccess]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countWorkflowAccess()
      elements <- if (offset > count) Future.successful(Nil)
      else selectWorkflowAccess(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countWorkflowAccess() = {
    Future(run(queryWorkflowAccess.size).toInt)
  }


  private def selectWorkflowAccess(offset: Int, limit: Int): Future[Seq[WorkflowAccess]] = {
    Future(run(queryWorkflowAccess).drop(offset).take(limit).toSeq)
  }
} 
Example 95
Source File: PackageExportCommonRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.PackageExportCommon
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class PackageExportCommonRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.PackageExportCommonRepository[PackageExportCommon , Int]
    with PackageExportCommonMapping {

  def getById(id: Int): Future[PackageExportCommon] = {
    Future(run(queryPackageExportCommon.filter(_.packageExportCommonId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[PackageExportCommon] = {
    Future(run(queryPackageExportCommon.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByPackageExportCommonId(id : Int) : Future[List[PackageExportCommon]] = {
    Future(run(queryPackageExportCommon))
  }

  def getAll() : Future[List[PackageExportCommon]] = {
    Future(run(queryPackageExportCommon))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[PackageExportCommon]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countPackageExportCommon()
      elements <- if (offset > count) Future.successful(Nil)
      else selectPackageExportCommon(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countPackageExportCommon() = {
    Future(run(queryPackageExportCommon.size).toInt)
  }

  private def selectPackageExportCommon(offset: Int, limit: Int): Future[Seq[PackageExportCommon]] = {
    Future(run(queryPackageExportCommon).drop(offset).take(limit).toSeq)
  }
} 
Example 96
Source File: RecentItemRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.RecentItem
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class RecentItemRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.RecentItemRepository[RecentItem , Int]
    with RecentItemMapping {

  def getById(id: Int): Future[RecentItem] = {
    Future(run(queryRecentItem.filter(_.recentItemId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[RecentItem] = {
    Future(run(queryRecentItem.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByRecentItemId(id : Int) : Future[List[RecentItem]] = {
    Future(run(queryRecentItem))
  }

  def getAll() : Future[List[RecentItem]] = {
    Future(run(queryRecentItem))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[RecentItem]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countRecentItem()
      elements <- if (offset > count) Future.successful(Nil)
      else selectRecentItem(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countRecentItem() = {
    Future(run(queryRecentItem.size).toInt)
  }


  private def selectRecentItem(offset: Int, limit: Int): Future[Seq[RecentItem]] = {
    Future(run(queryRecentItem).drop(offset).take(limit).toSeq)
  }
} 
Example 97
Source File: ImageRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.Image
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class ImageRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.ImageRepository[Image , Int]
    with ImageMapping {

  def getById(id: Int): Future[Image] = {
    Future(run(queryImage.filter(_.imageId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[Image] = {
    Future(run(queryImage.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByImageId(id : Int) : Future[List[Image]] = {
    Future(run(queryImage))
  }

  def getAll() : Future[List[Image]] = {
    Future(run(queryImage))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[Image]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countImage()
      elements <- if (offset > count) Future.successful(Nil)
      else selectImage(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countImage() = {
    Future(run(queryImage.size).toInt)
  }

  private def selectImage(offset: Int, limit: Int): Future[Seq[Image]] = {
    Future(run(queryImage).drop(offset).take(limit).toSeq)
  }
} 
Example 98
Source File: WindowTrlRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.WindowTrl
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class WindowTrlRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.WindowTrlRepository[WindowTrl , Int]
    with WindowTrlMapping {

  def getById(id: Int): Future[WindowTrl] = {
    getByLanguage(id , "en_US")
  }

  def getByLanguage(id: Int , lang : String): Future[WindowTrl] = {
    Future(run(queryWindowTrl.filter(window => window.windowId == lift(id)
      && window.language == lift(lang))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[WindowTrl] = {
    Future(run(queryWindowTrl.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByWindowTrlId(id : Int) : Future[List[WindowTrl]] = {
    Future(run(queryWindowTrl))
  }

  def getAll() : Future[List[WindowTrl]] = {
    Future(run(queryWindowTrl))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[WindowTrl]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countWindowTrl()
      elements <- if (offset > count) Future.successful(Nil)
      else selectWindowTrl(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countWindowTrl() = {
    Future(run(queryWindowTrl.size).toInt)
  }


  private def selectWindowTrl(offset: Int, limit: Int): Future[Seq[WindowTrl]] = {
    Future(run(queryWindowTrl).drop(offset).take(limit).toSeq)
  }
} 
Example 99
Source File: ReplicationDocumentRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.ReplicationDocument
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}




class ReplicationDocumentRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.ReplicationDocumentRepository[ReplicationDocument , Int]
    with ReplicationDocumentMapping {

  def getById(id: Int): Future[ReplicationDocument] = {
    Future(run(queryReplicationDocument.filter(_.replicationDocumentId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[ReplicationDocument] = {
    Future(run(queryReplicationDocument.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByReplicationDocumentId(id : Int) : Future[List[ReplicationDocument]] = {
    Future(run(queryReplicationDocument))
  }

  def getAll() : Future[List[ReplicationDocument]] = {
    Future(run(queryReplicationDocument))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[ReplicationDocument]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countReplicationDocument()
      elements <- if (offset > count) Future.successful(Nil)
      else selectReplicationDocument(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countReplicationDocument() = {
    Future(run(queryReplicationDocument.size).toInt)
  }


  private def selectReplicationDocument(offset: Int, limit: Int): Future[Seq[ReplicationDocument]] = {
    Future(run(queryReplicationDocument).drop(offset).take(limit).toSeq)
  }
} 
Example 100
Source File: ProcessParameterTrlRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.ProcessParameterTrl
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class ProcessParameterTrlRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.ProcessParameterTrlRepository[ProcessParameterTrl , Int]
    with ProcessParameterTrlMapping {

  def getById(id: Int): Future[ProcessParameterTrl] = {
    getByLanguage(id , "en_US")
  }

  def getByLanguage(id: Int , lang : String): Future[ProcessParameterTrl] = {
    Future(run(queryProcessParameterTrl.filter(processParameter => processParameter.processParameterId == lift(id)
      && processParameter.language == lift(lang))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[ProcessParameterTrl] = {
    Future(run(queryProcessParameterTrl.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByProcessParameterTrlId(id : Int) : Future[List[ProcessParameterTrl]] = {
    Future(run(queryProcessParameterTrl))
  }

  def getAll() : Future[List[ProcessParameterTrl]] = {
    Future(run(queryProcessParameterTrl))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[ProcessParameterTrl]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countProcessParameterTrl()
      elements <- if (offset > count) Future.successful(Nil)
      else selectProcessParameterTrl(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countProcessParameterTrl() = {
    Future(run(queryProcessParameterTrl.size).toInt)
  }


  private def selectProcessParameterTrl(offset: Int, limit: Int): Future[Seq[ProcessParameterTrl]] = {
    Future(run(queryProcessParameterTrl).drop(offset).take(limit).toSeq)
  }
} 
Example 101
Source File: TenantRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.Tenant
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class TenantRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.TenantRepository[Tenant , Int]
    with TenantMapping {

  def getById(id: Int): Future[Tenant] = {
    Future(run(queryTenant.filter(_.tenantId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[Tenant] = {
    Future(run(queryTenant.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByTenantId(id : Int) : Future[List[Tenant]] = {
    Future(run(queryTenant))
  }

  def getAll() : Future[List[Tenant]] = {
    Future(run(queryTenant))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[Tenant]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countTenant()
      elements <- if (offset > count) Future.successful(Nil)
      else selectTenant(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countTenant() = {
    Future(run(queryTenant.size).toInt)
  }


  private def selectTenant(offset: Int, limit: Int): Future[Seq[Tenant]] = {
    Future(run(queryTenant).drop(offset).take(limit).toSeq)
  }
} 
Example 102
Source File: TreeNodeCMTRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.TreeNodeCMT
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class TreeNodeCMTRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.TreeNodeCMTRepository[TreeNodeCMT , Int]
    with TreeNodeCMTMapping {

  def getById(id: Int): Future[TreeNodeCMT] = {
    getByNode(id , 0)
  }

  def getByNode(id: Int , node : Int): Future[TreeNodeCMT] = {
    Future(run(queryTreeNodeCMT.filter(treeNodeCMT => treeNodeCMT.treeId == lift(id)
      && treeNodeCMT.nodeId == lift(node))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[TreeNodeCMT] = {
    Future(run(queryTreeNodeCMT.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByTreeNodeCMTId(id : Int) : Future[List[TreeNodeCMT]] = {
    Future(run(queryTreeNodeCMT))
  }

  def getAll() : Future[List[TreeNodeCMT]] = {
    Future(run(queryTreeNodeCMT))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[TreeNodeCMT]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countTreeNodeCMT()
      elements <- if (offset > count) Future.successful(Nil)
      else selectTreeNodeCMT(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countTreeNodeCMT() = {
    Future(run(queryTreeNodeCMT.size).toInt)
  }


  private def selectTreeNodeCMT(offset: Int, limit: Int): Future[Seq[TreeNodeCMT]] = {
    Future(run(queryTreeNodeCMT).drop(offset).take(limit).toSeq)
  }
} 
Example 103
Source File: OrganizationTypeRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.OrganizationType
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class OrganizationTypeRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.OrganizationTypeRepository[OrganizationType , Int]
    with OrganizationTypeMapping {

  def getById(id: Int): Future[OrganizationType] = {
    Future(run(queryOrganizationType.filter(_.organizationTypeId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[OrganizationType] = {
    Future(run(queryOrganizationType.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByOrganizationTypeId(id : Int) : Future[List[OrganizationType]] = {
    Future(run(queryOrganizationType))
  }

  def getAll() : Future[List[OrganizationType]] = {
    Future(run(queryOrganizationType))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[OrganizationType]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countOrganizationType()
      elements <- if (offset > count) Future.successful(Nil)
      else selectOrganizationType(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countOrganizationType() = {
    Future(run(queryOrganizationType.size).toInt)
  }

  private def selectOrganizationType(offset: Int, limit: Int): Future[Seq[OrganizationType]] = {
    Future(run(queryOrganizationType).drop(offset).take(limit).toSeq)
  }
} 
Example 104
Source File: NoteRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.Note
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class NoteRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.NoteRepository[Note , Int]
    with NoteMapping {

  def getById(id: Int): Future[Note] = {
    Future(run(queryNote.filter(_.noteId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[Note] = {
    Future(run(queryNote.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByNoteId(id : Int) : Future[List[Note]] = {
    Future(run(queryNote))
  }

  def getAll() : Future[List[Note]] = {
    Future(run(queryNote))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[Note]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countNote()
      elements <- if (offset > count) Future.successful(Nil)
      else selectNote(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countNote() = {
    Future(run(queryNote.size).toInt)
  }

  private def selectNote(offset: Int, limit: Int): Future[Seq[Note]] = {
    Future(run(queryNote).drop(offset).take(limit).toSeq)
  }
} 
Example 105
Source File: FieldRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.Field
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class FieldRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.FieldRepository[Field , Int]
    with FieldMapping {

  def getById(id: Int): Future[Field] = {
    Future(run(queryField.filter(_.fieldId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[Field] = {
    Future(run(queryField.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByFieldId(id : Int) : Future[List[Field]] = {
    Future(run(queryField))
  }

  def getAll() : Future[List[Field]] = {
    Future(run(queryField))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[Field]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countField()
      elements <- if (offset > count) Future.successful(Nil)
      else selectField(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countField() = {
    Future(run(queryField.size).toInt)
  }

  private def selectField(offset: Int, limit: Int): Future[Seq[Field]] = {
    Future(run(queryField).drop(offset).take(limit).toSeq)
  }
} 
Example 106
Source File: TenantInfoRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.TenantInfo
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class TenantInfoRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.TenantInfoRepository[TenantInfo , Int]
    with TenantInfoMapping {

  def getById(id: Int): Future[TenantInfo] = {
    Future(run(queryTenantInfo.filter(_.tenantId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[TenantInfo] = {
    Future(run(queryTenantInfo.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByTenantInfoId(id : Int) : Future[List[TenantInfo]] = {
    Future(run(queryTenantInfo))
  }

  def getAll() : Future[List[TenantInfo]] = {
    Future(run(queryTenantInfo))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[TenantInfo]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countTenantInfo()
      elements <- if (offset > count) Future.successful(Nil)
      else selectTenantInfo(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countTenantInfo() = {
    Future(run(queryTenantInfo.size).toInt)
  }

  private def selectTenantInfo(offset: Int, limit: Int): Future[Seq[TenantInfo]] = {
    Future(run(queryTenantInfo).drop(offset).take(limit).toSeq)
  }
} 
Example 107
Source File: AccessLogRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.AccessLog
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class AccessLogRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.AccessLogRepository[AccessLog , Int]
    with AccessLogMapping {

  def getById(id: Int): Future[AccessLog] = {
    Future(run(queryAccessLog.filter(_.accessLogId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[AccessLog] = {
    Future(run(queryAccessLog.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }


  def getAll() : Future[List[AccessLog]] = {
    Future(run(queryAccessLog))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[AccessLog]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countAccessLog()
      elements <- if (offset > count) Future.successful(Nil)
      else selectAccessLog(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countAccessLog() = {
    Future(run(queryAccessLog.size).toInt)
  }

  private def selectAccessLog(offset: Int, limit: Int): Future[Seq[AccessLog]] = {
    Future(run(queryAccessLog).drop(offset).take(limit).toSeq)
  }
} 
Example 108
Source File: RelationTypeRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.RelationType
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class RelationTypeRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.RelationTypeRepository[RelationType , Int]
    with RelationTypeMapping {

  def getById(id: Int): Future[RelationType] = {
    Future(run(queryRelationType.filter(_.relationTypeId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[RelationType] = {
    Future(run(queryRelationType.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByRelationTypeId(id : Int) : Future[List[RelationType]] = {
    Future(run(queryRelationType))
  }

  def getAll() : Future[List[RelationType]] = {
    Future(run(queryRelationType))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[RelationType]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countRelationType()
      elements <- if (offset > count) Future.successful(Nil)
      else selectRelationType(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countRelationType() = {
    Future(run(queryRelationType.size).toInt)
  }


  private def selectRelationType(offset: Int, limit: Int): Future[Seq[RelationType]] = {
    Future(run(queryRelationType).drop(offset).take(limit).toSeq)
  }
} 
Example 109
Source File: TreeNodeRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.TreeNode
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class TreeNodeRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.TreeNodeRepository[TreeNode , Int]
    with TreeNodeMapping {

  def getById(id: Int): Future[TreeNode] = {
    getByNode(id , 0)
  }

  def getByNode(id: Int , node : Int): Future[TreeNode] = {
    Future(run(queryTreeNode.filter(treeNode => treeNode.treeId == lift(id)
      && treeNode.nodeId == lift(node))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[TreeNode] = {
    Future(run(queryTreeNode.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByTreeNodeId(id : Int) : Future[List[TreeNode]] = {
    Future(run(queryTreeNode))
  }

  def getAll() : Future[List[TreeNode]] = {
    Future(run(queryTreeNode))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[TreeNode]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countTreeNode()
      elements <- if (offset > count) Future.successful(Nil)
      else selectTreeNode(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countTreeNode() = {
    Future(run(queryTreeNode.size).toInt)
  }


  private def selectTreeNode(offset: Int, limit: Int): Future[Seq[TreeNode]] = {
    Future(run(queryTreeNode).drop(offset).take(limit).toSeq)
  }
} 
Example 110
Source File: ProcessTrlRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.ProcessTrl
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}




class ProcessTrlRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.ProcessTrlRepository[ProcessTrl , Int]
    with ProcessTrlMapping {

  def getById(id: Int): Future[ProcessTrl] = {
    getByLanguage(id , "en_US")
  }

  def getByLanguage(id: Int , lang : String): Future[ProcessTrl] = {
    Future(run(queryProcessTrl.filter(process => process.processId == lift(id)
      && process.language == lift(lang))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[ProcessTrl] = {
    Future(run(queryProcessTrl.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByProcessTrlId(id : Int) : Future[List[ProcessTrl]] = {
    Future(run(queryProcessTrl))
  }

  def getAll() : Future[List[ProcessTrl]] = {
    Future(run(queryProcessTrl))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[ProcessTrl]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countProcessTrl()
      elements <- if (offset > count) Future.successful(Nil)
      else selectProcessTrl(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countProcessTrl() = {
    Future(run(queryProcessTrl.size).toInt)
  }


  private def selectProcessTrl(offset: Int, limit: Int): Future[Seq[ProcessTrl]] = {
    Future(run(queryProcessTrl).drop(offset).take(limit).toSeq)
  }
} 
Example 111
Source File: ReportViewAttributeRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.ReportViewAttribute
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class ReportViewAttributeRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.ReportViewAttributeRepository[ReportViewAttribute , Int]
    with ReportViewAttributeMapping {

  def getById(id: Int): Future[ReportViewAttribute] = {
    Future(run(queryReportViewAttribute.filter(_.reportViewAttributeId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[ReportViewAttribute] = {
    Future(run(queryReportViewAttribute.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByReportViewAttributeId(id : Int) : Future[List[ReportViewAttribute]] = {
    Future(run(queryReportViewAttribute))
  }

  def getAll() : Future[List[ReportViewAttribute]] = {
    Future(run(queryReportViewAttribute))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[ReportViewAttribute]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countReportViewAttribute()
      elements <- if (offset > count) Future.successful(Nil)
      else selectReportViewAttribute(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countReportViewAttribute() = {
    Future(run(queryReportViewAttribute.size).toInt)
  }


  private def selectReportViewAttribute(offset: Int, limit: Int): Future[Seq[ReportViewAttribute]] = {
    Future(run(queryReportViewAttribute).drop(offset).take(limit).toSeq)
  }
} 
Example 112
Source File: SchedulerRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.Scheduler
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class SchedulerRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.SchedulerRepository[Scheduler , Int]
    with SchedulerMapping {

  def getById(id: Int): Future[Scheduler] = {
    Future(run(queryScheduler.filter(_.schedulerId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[Scheduler] = {
    Future(run(queryScheduler.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getBySchedulerId(id : Int) : Future[List[Scheduler]] = {
    Future(run(queryScheduler))
  }

  def getAll() : Future[List[Scheduler]] = {
    Future(run(queryScheduler))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[Scheduler]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countScheduler()
      elements <- if (offset > count) Future.successful(Nil)
      else selectScheduler(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countScheduler() = {
    Future(run(queryScheduler.size).toInt)
  }


  private def selectScheduler(offset: Int, limit: Int): Future[Seq[Scheduler]] = {
    Future(run(queryScheduler).drop(offset).take(limit).toSeq)
  }
} 
Example 113
Source File: ViewAttributeRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.ViewAttribute
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class ViewAttributeRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.ViewAttributeRepository[ViewAttribute , Int]
    with ViewAttributeMapping {

  def getById(id: Int): Future[ViewAttribute] = {
    Future(run(queryViewAttribute.filter(_.viewAttributeId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[ViewAttribute] = {
    Future(run(queryViewAttribute.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByViewAttributeId(id : Int) : Future[List[ViewAttribute]] = {
    Future(run(queryViewAttribute))
  }

  def getAll() : Future[List[ViewAttribute]] = {
    Future(run(queryViewAttribute))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[ViewAttribute]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countViewAttribute()
      elements <- if (offset > count) Future.successful(Nil)
      else selectViewAttribute(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countViewAttribute() = {
    Future(run(queryViewAttribute.size).toInt)
  }


  private def selectViewAttribute(offset: Int, limit: Int): Future[Seq[ViewAttribute]] = {
    Future(run(queryViewAttribute).drop(offset).take(limit).toSeq)
  }
} 
Example 114
Source File: PackageImportRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.PackageImport
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class PackageImportRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.PackageImportRepository[PackageImport , Int]
    with PackageImportMapping {

  def getById(id: Int): Future[PackageImport] = {
    Future(run(queryPackageImport.filter(_.packageImportId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[PackageImport] = {
    Future(run(queryPackageImport.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByPackageImportId(id : Int) : Future[List[PackageImport]] = {
    Future(run(queryPackageImport))
  }

  def getAll() : Future[List[PackageImport]] = {
    Future(run(queryPackageImport))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[PackageImport]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countPackageImport()
      elements <- if (offset > count) Future.successful(Nil)
      else selectPackageImport(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countPackageImport() = {
    Future(run(queryPackageImport.size).toInt)
  }

  private def selectPackageImport(offset: Int, limit: Int): Future[Seq[PackageImport]] = {
    Future(run(queryPackageImport).drop(offset).take(limit).toSeq)
  }
} 
Example 115
Source File: SchedulerParameterRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository
import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.SchedulerParameter
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class SchedulerParameterRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.SchedulerParameterRepository[SchedulerParameter , Int]
    with SchedulerParameterMapping {

  def getById(id: Int): Future[SchedulerParameter] = {
    getByParameter(id , 400)
  }

  def getByParameter(id: Int , parameter : Int): Future[SchedulerParameter] = {
    Future(run(querySchedulerParameter.filter(schedulerParameter => schedulerParameter.schedulerId == lift(id)
      && schedulerParameter.processParameterId == lift(parameter))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[SchedulerParameter] = {
    Future(run(querySchedulerParameter.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getBySchedulerParameterId(id : Int) : Future[List[SchedulerParameter]] = {
    Future(run(querySchedulerParameter))
  }

  def getAll() : Future[List[SchedulerParameter]] = {
    Future(run(querySchedulerParameter))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[SchedulerParameter]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countSchedulerParameter()
      elements <- if (offset > count) Future.successful(Nil)
      else selectSchedulerParameter(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countSchedulerParameter() = {
    Future(run(querySchedulerParameter.size).toInt)
  }


  private def selectSchedulerParameter(offset: Int, limit: Int): Future[Seq[SchedulerParameter]] = {
    Future(run(querySchedulerParameter).drop(offset).take(limit).toSeq)
  }
} 
Example 116
Source File: WorkflowRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.Workflow
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class WorkflowRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.WorkflowRepository[Workflow , Int]
    with WorkflowMapping {

  def getById(id: Int): Future[Workflow] = {
    Future(run(queryWorkflow.filter(_.workflowId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[Workflow] = {
    Future(run(queryWorkflow.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByWorkflowId(id : Int) : Future[List[Workflow]] = {
    Future(run(queryWorkflow))
  }

  def getAll() : Future[List[Workflow]] = {
    Future(run(queryWorkflow))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[Workflow]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countWorkflow()
      elements <- if (offset > count) Future.successful(Nil)
      else selectWorkflow(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countWorkflow() = {
    Future(run(queryWorkflow.size).toInt)
  }


  private def selectWorkflow(offset: Int, limit: Int): Future[Seq[Workflow]] = {
    Future(run(queryWorkflow).drop(offset).take(limit).toSeq)
  }
} 
Example 117
Source File: UserRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.User
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class UserRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.UserRepository[User , Int]
    with UserMapping {

  def getById(id: Int): Future[User] = {
    Future(run(queryUser.filter(_.userId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[User] = {
    Future(run(queryUser.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByUserId(id : Int) : Future[List[User]] = {
    Future(run(queryUser))
  }

  def getAll() : Future[List[User]] = {
    Future(run(queryUser))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[User]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countUser()
      elements <- if (offset > count) Future.successful(Nil)
      else selectUser(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countUser() = {
    Future(run(queryUser.size).toInt)
  }


  private def selectUser(offset: Int, limit: Int): Future[Seq[User]] = {
    Future(run(queryUser).drop(offset).take(limit).toSeq)
  }
} 
Example 118
Source File: MenuRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.Menu
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class MenuRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.MenuRepository[Menu , Int]
    with MenuMapping {

  def getById(id: Int): Future[Menu] = {
    Future(run(queryMenu.filter(_.menuId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[Menu] = {
    Future(run(queryMenu.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByMenuId(id : Int) : Future[List[Menu]] = {
    Future(run(queryMenu))
  }

  def getAll() : Future[List[Menu]] = {
    Future(run(queryMenu))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[Menu]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countMenu()
      elements <- if (offset > count) Future.successful(Nil)
      else selectMenu(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countMenu() = {
    Future(run(queryMenu.size).toInt)
  }

  private def selectMenu(offset: Int, limit: Int): Future[Seq[Menu]] = {
    Future(run(queryMenu).drop(offset).take(limit).toSeq)
  }
} 
Example 119
Source File: AttributeRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository
import java.util.UUID

import com.eevolution.context.dictionary.domain.api
import com.eevolution.context.dictionary.domain.model.Attribute
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}


class AttributeRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.AttributeRepository[Attribute , Int]
    with AttributeMapping {

  def getById(id: Int): Future[Attribute] = {
    Future(run(queryAttribute.filter(_.attributeId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[Attribute] = {
    Future(run(queryAttribute.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByEntityId(id : Int) : Future[List[Attribute]] = {
    Future(run(queryAttribute))
  }

  def getAll() : Future[List[Attribute]] = {
    Future(run(queryAttribute))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[Attribute]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countAttribute()
      elements <- if (offset > count) Future.successful(Nil)
      else selectAttribute(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countAttribute() = {
    Future(run(queryAttribute.size).toInt)
  }


  private def selectAttribute(offset: Int, limit: Int): Future[Seq[Attribute]] = {
    Future(run(queryAttribute).drop(offset).take(limit).toSeq)
  }

} 
Example 120
Source File: SequenceAuditRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.SequenceAudit
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class SequenceAuditRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.SequenceAuditRepository[SequenceAudit , Int]
    with SequenceAuditMapping {

  def getById(id: Int): Future[SequenceAudit] = {
    getByDocumentNo(id , "")
  }

  def getByDocumentNo(id: Int , document : String): Future[SequenceAudit] = {
    Future(run(querySequenceAudit.filter(sequenceAudit => sequenceAudit.sequenceId == lift(id)
      && sequenceAudit.documentNo == lift(document))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[SequenceAudit] = {
    Future(run(querySequenceAudit.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getBySequenceAuditId(id : Int) : Future[List[SequenceAudit]] = {
    Future(run(querySequenceAudit))
  }

  def getAll() : Future[List[SequenceAudit]] = {
    Future(run(querySequenceAudit))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[SequenceAudit]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countSequenceAudit()
      elements <- if (offset > count) Future.successful(Nil)
      else selectSequenceAudit(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countSequenceAudit() = {
    Future(run(querySequenceAudit.size).toInt)
  }


  private def selectSequenceAudit(offset: Int, limit: Int): Future[Seq[SequenceAudit]] = {
    Future(run(querySequenceAudit).drop(offset).take(limit).toSeq)
  }
} 
Example 121
Source File: DesktopRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.Desktop
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class DesktopRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.DesktopRepository[Desktop , Int]
    with DesktopMapping {

  def getById(id: Int): Future[Desktop] = {
    Future(run(queryDesktop.filter(_.desktopId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[Desktop] = {
    Future(run(queryDesktop.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByDesktopId(id : Int) : Future[List[Desktop]] = {
    Future(run(queryDesktop))
  }

  def getAll() : Future[List[Desktop]] = {
    Future(run(queryDesktop))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[Desktop]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countDesktop()
      elements <- if (offset > count) Future.successful(Nil)
      else selectDesktop(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countDesktop() = {
    Future(run(queryDesktop.size).toInt)
  }

  private def selectDesktop(offset: Int, limit: Int): Future[Seq[Desktop]] = {
    Future(run(queryDesktop).drop(offset).take(limit).toSeq)
  }
} 
Example 122
Source File: ProcessParameterRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.ProcessParameter
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class ProcessParameterRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.ProcessParameterRepository[ProcessParameter , Int]
    with ProcessParameterMapping {

  def getById(id: Int): Future[ProcessParameter] = {
    Future(run(queryProcessParameter.filter(_.processParameterId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[ProcessParameter] = {
    Future(run(queryProcessParameter.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByProcessParameterId(id : Int) : Future[List[ProcessParameter]] = {
    Future(run(queryProcessParameter))
  }

  def getAll() : Future[List[ProcessParameter]] = {
    Future(run(queryProcessParameter))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[ProcessParameter]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countProcessParameter()
      elements <- if (offset > count) Future.successful(Nil)
      else selectProcessParameter(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countProcessParameter() = {
    Future(run(queryProcessParameter.size).toInt)
  }

  private def selectProcessParameter(offset: Int, limit: Int): Future[Seq[ProcessParameter]] = {
    Future(run(queryProcessParameter).drop(offset).take(limit).toSeq)
  }
} 
Example 123
Source File: PrintLabelLineRepository.scala    From ADReactiveSystem   with GNU General Public License v3.0 5 votes vote down vote up
package com.eevolution.context.dictionary.infrastructure.repository

import java.util.UUID

import com.eevolution.context.dictionary.domain._
import com.eevolution.context.dictionary.domain.model.PrintLabelLine
import com.eevolution.context.dictionary.infrastructure.db.DbContext._
import com.eevolution.utils.PaginatedSequence
import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession

import scala.concurrent.{ExecutionContext, Future}



class PrintLabelLineRepository (session: JdbcSession)(implicit executionContext: ExecutionContext)
  extends api.repository.PrintLabelLineRepository[PrintLabelLine , Int]
    with PrintLabelLineMapping {

  def getById(id: Int): Future[PrintLabelLine] = {
    Future(run(queryPrintLabelLine.filter(_.printLabelLineId == lift(id))).headOption.get)
  }

  def getByUUID(uuid: UUID): Future[PrintLabelLine] = {
    Future(run(queryPrintLabelLine.filter(_.uuid == lift(uuid.toString))).headOption.get)
  }

  def getByPrintLabelLineId(id : Int) : Future[List[PrintLabelLine]] = {
    Future(run(queryPrintLabelLine))
  }

  def getAll() : Future[List[PrintLabelLine]] = {
    Future(run(queryPrintLabelLine))
  }

  def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[PrintLabelLine]] = {
    val offset = page * pageSize
    val limit = (page + 1) * pageSize
    for {
      count <- countPrintLabelLine()
      elements <- if (offset > count) Future.successful(Nil)
      else selectPrintLabelLine(offset, limit)
    } yield {
      PaginatedSequence(elements, page, pageSize, count)
    }
  }

  private def countPrintLabelLine() = {
    Future(run(queryPrintLabelLine.size).toInt)
  }

  private def selectPrintLabelLine(offset: Int, limit: Int): Future[Seq[PrintLabelLine]] = {
    Future(run(queryPrintLabelLine).drop(offset).take(limit).toSeq)
  }
} 
Example 124
Source File: StorageNodeReadResponseSerializer.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db.kryo

import java.util.UUID

import com.esotericsoftware.kryo.io.{Input, Output}
import com.esotericsoftware.kryo.{Kryo, Serializer}
import justin.db.Data
import justin.db.actors.protocol._

object StorageNodeReadResponseSerializer extends Serializer[StorageNodeReadResponse] {

  private object Discriminator {
    val Found      = 1
    val Conflicted = 2
    val NotFound   = 3
    val Failed     = 4
  }

  override def write(kryo: Kryo, output: Output, readResponse: StorageNodeReadResponse): Unit = readResponse match {
    case StorageNodeFoundRead(data)           =>
      output.writeInt(Discriminator.Found)
      DataSerializer.write(kryo, output, data)
    case StorageNodeConflictedRead(conflicts) =>
      output.writeInt(Discriminator.Conflicted)
      ListOfDataSerializer.write(kryo, output, conflicts)
    case StorageNodeNotFoundRead(id)          =>
      output.writeInt(Discriminator.NotFound)
      output.writeString(id.toString)
    case StorageNodeFailedRead(id)            =>
      output.writeInt(Discriminator.Failed)
      output.writeString(id.toString)
  }

  override def read(kryo: Kryo, input: Input, `type`: Class[StorageNodeReadResponse]): StorageNodeReadResponse = {
    input.readInt() match {
      case Discriminator.Found      => StorageNodeFoundRead(DataSerializer.read(kryo, input, classOf[Data]))
      case Discriminator.Conflicted => StorageNodeConflictedRead(ListOfDataSerializer.read(kryo, input, classOf[List[Data]]))
      case Discriminator.NotFound   => StorageNodeNotFoundRead(UUID.fromString(input.readString()))
      case Discriminator.Failed     => StorageNodeFailedRead(UUID.fromString(input.readString()))
    }
  }
} 
Example 125
Source File: Data.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db

import java.util.UUID

import justin.db.consistenthashing.NodeId
import justin.db.replica.PreferenceList
import justin.db.storage.JustinData
import justin.db.vectorclocks.VectorClock
import justin.db.versioning.NodeIdVectorClockBase64

import scala.language.implicitConversions

case class Data(id: UUID, value: String, vclock: VectorClock[NodeId] = VectorClock(), timestamp: Long = System.currentTimeMillis())

object Data {

  def updateVclock(data: Data, preferenceList: PreferenceList): Data = {
    val nodeIds = preferenceList.all
    data.copy(vclock = nodeIds.foldLeft(data.vclock)(_ increase _))
  }

  implicit def toInternal(data: Data): JustinData = {
    val encodedVClock = new NodeIdVectorClockBase64().encode(data.vclock).get // TODO: check if encoding of VClock is possible (make it typesafe)
    JustinData(data.id, data.value, encodedVClock, data.timestamp)
  }

  implicit def fromInternal(justinData: JustinData): Data = {
    val decodedVClock = new NodeIdVectorClockBase64().decode(justinData.vclock).get // TODO: check if decoding of VClock is possible (make it typesafe)
    Data(justinData.id, justinData.value, decodedVClock, justinData.timestamp)
  }
} 
Example 126
Source File: IsPrimaryOrReplica.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db.replica

import java.util.UUID

import justin.db.consistenthashing.{NodeId, Ring, UUID2RingPartitionId}
import justin.db.storage.PluggableStorageProtocol.DataOriginality

class IsPrimaryOrReplica(nodeId: NodeId, ring: Ring) extends (UUID => DataOriginality) {

  override def apply(id: UUID): DataOriginality = {
    val partitionId = UUID2RingPartitionId(id, ring)

    if(ring.getNodeId(partitionId).contains(nodeId)) {
      DataOriginality.Primary(partitionId)
    } else {
      DataOriginality.Replica(partitionId)
    }
  }
} 
Example 127
Source File: ReplicaWriteCoordinator.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db.replica.write

import java.util.UUID

import justin.db._
import justin.db.actors.protocol._
import justin.db.cluster.ClusterMembers
import justin.db.consistenthashing.{NodeId, Ring, UUID2RingPartitionId}
import justin.db.replica._

import scala.concurrent.{ExecutionContext, Future}

class ReplicaWriteCoordinator(
  nodeId: NodeId, ring: Ring, n: N,
  localDataWriter: ReplicaLocalWriter,
  remoteDataWriter: ReplicaRemoteWriter
)(implicit ec: ExecutionContext) extends ((StorageNodeWriteRequest, ClusterMembers) => Future[StorageNodeWriteResponse]) {

  override def apply(cmd: StorageNodeWriteRequest, clusterMembers: ClusterMembers): Future[StorageNodeWriteResponse] = cmd match {
    case StorageNodeWriteDataLocal(data) => writeLocal(data)
    case Internal.WriteReplica(w, data)  => coordinateReplicated(w, data, clusterMembers)
  }

  private def writeLocal(data: Data) = localDataWriter.apply(data, new IsPrimaryOrReplica(nodeId, ring))

  private def coordinateReplicated(w: W, data: Data, clusterMembers: ClusterMembers) = {
    val ringPartitionId = UUID2RingPartitionId.apply(data.id, ring)
    PreferenceList(ringPartitionId, n, ring).fold(onLeft(data.id), onRight(w, data, clusterMembers))
  }

  // TODO: rename to "onFailure"
  private def onLeft(id: UUID)(err: PreferenceList.Error) = Future.successful(StorageNodeFailedWrite(id))

  // TODO: rename to "onSuccess"
  private def onRight(w: W, data: Data, clusterMembers: ClusterMembers)(preferenceList: PreferenceList) = {
    val updatedData = Data.updateVclock(data, preferenceList)
    makeWrites(w, updatedData, clusterMembers, preferenceList)
      .map(new ReplicaWriteAgreement().reach(w))
      .map(consensus2WritingResult(updatedData.id))
  }

  private def makeWrites(w: W, updatedData: Data, clusterMembers: ClusterMembers, preferenceList: PreferenceList) = {
    ResolveNodeAddresses(nodeId, preferenceList, clusterMembers) match {
      case ResolvedNodeAddresses(true, remotes)  if remotes.size + 1 >= w.w => (writeLocal(updatedData) zip remoteDataWriter(remotes, updatedData)).map(converge)
      case ResolvedNodeAddresses(false, remotes) if remotes.size     >= w.w => remoteDataWriter(remotes, updatedData)
      case _                                                                => Future.successful(List(StorageNodeFailedWrite(updatedData.id)))
    }
  }

  private def consensus2WritingResult(id: UUID): WriteAgreement => StorageNodeWriteResponse = {
    case WriteAgreement.NotEnoughWrites => StorageNodeFailedWrite(id)
    case WriteAgreement.Ok              => StorageNodeSuccessfulWrite(id)
  }
} 
Example 128
Source File: ReplicaReadCoordinator.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db.replica.read

import java.util.UUID

import justin.db._
import justin.db.actors.protocol._
import justin.db.cluster.ClusterMembers
import justin.db.consistenthashing.{NodeId, Ring, UUID2RingPartitionId}
import justin.db.replica._

import scala.concurrent.{ExecutionContext, Future}

class ReplicaReadCoordinator(
  nodeId: NodeId, ring: Ring, n: N,
  localDataReader: ReplicaLocalReader,
  remoteDataReader: ReplicaRemoteReader
)(implicit ec: ExecutionContext) extends ((StorageNodeReadRequest, ClusterMembers) => Future[StorageNodeReadResponse]) {

  override def apply(cmd: StorageNodeReadRequest, clusterMembers: ClusterMembers): Future[StorageNodeReadResponse] = cmd match {
    case StorageNodeLocalRead(id)    => readLocalData(id)
    case Internal.ReadReplica(r, id) => coordinateReplicated(r, id, clusterMembers)
  }

  private def readLocalData(id: UUID) = localDataReader.apply(id, new IsPrimaryOrReplica(nodeId, ring))

  private def coordinateReplicated(r: R, id: UUID, clusterMembers: ClusterMembers) = {
    val partitionId = UUID2RingPartitionId.apply(id, ring)
    PreferenceList(partitionId, n, ring).fold(onLeft(id), onRight(r, id, clusterMembers))
  }

  private def onLeft(id: UUID)(err: PreferenceList.Error) = Future.successful(StorageNodeFailedRead(id))

  private def onRight(r: R, id: UUID, clusterMembers: ClusterMembers)(preferenceList: PreferenceList) = {
    gatherReads(r, id, clusterMembers, preferenceList).map { reads =>
      val consensus = new ReplicaReadAgreement().reach(r)(reads)
      consensus2ReadingResult(id)(consensus)
    }
  }

  private def gatherReads(r: R, id: UUID, clusterMembers: ClusterMembers, preferenceList: PreferenceList) = {
    ResolveNodeAddresses(nodeId, preferenceList, clusterMembers) match {
      case ResolvedNodeAddresses(true, remotes)  if remotes.size + 1 >= r.r => (readLocalData(id) zip remoteDataReader.apply(remotes, id)).map(converge)
      case ResolvedNodeAddresses(false, remotes) if remotes.size >= r.r     => remoteDataReader.apply(remotes, id)
      case _                                                                => Future.successful(List(StorageNodeFailedRead(id)))
    }
  }

  private def consensus2ReadingResult(id: => UUID): ReadAgreement => StorageNodeReadResponse = {
    case ReadAgreement.Consequent(data) => StorageNodeFoundRead(data)
    case ReadAgreement.Found(data)      => StorageNodeFoundRead(data)
    case ReadAgreement.Conflicts(data)  => StorageNodeConflictedRead(data)
    case ReadAgreement.NotEnoughFound   => StorageNodeNotFoundRead(id)
    case ReadAgreement.AllFailed        => StorageNodeFailedRead(id)
    case ReadAgreement.AllNotFound      => StorageNodeNotFoundRead(id)
  }
} 
Example 129
Source File: ReplicaRemoteReader.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db.replica.read

import java.util.UUID

import akka.pattern.ask
import akka.util.Timeout
import justin.db.actors.StorageNodeActorRef
import justin.db.actors.protocol.{StorageNodeFailedRead, StorageNodeLocalRead, StorageNodeReadResponse}

import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}

class ReplicaRemoteReader(implicit ec: ExecutionContext) {

  private implicit val timeout = Timeout(3.seconds) // TODO: tune this value

  def apply(storageNodeRefs: List[StorageNodeActorRef], id: UUID): Future[List[StorageNodeReadResponse]] = {
    Future.sequence(storageNodeRefs.map(getValue(_, id)))
  }

  private def getValue(node: StorageNodeActorRef, id: UUID): Future[StorageNodeReadResponse] = {
    (node.ref ? StorageNodeLocalRead(id))
      .mapTo[StorageNodeReadResponse]
      .recover { case _ => StorageNodeFailedRead(id) }
  }
} 
Example 130
Source File: StorageNodeClient.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db.client

import java.util.UUID

import justin.db.Data
import justin.db.replica.{R, W}
import justin.db.replica.W

import scala.concurrent.Future

trait StorageNodeClient {
  def get(id: UUID, r: R): Future[GetValueResponse]
  def write(data: Data, w: W): Future[WriteValueResponse]
}

sealed trait GetValueResponse
object GetValueResponse {
  case class Found(data: Data)           extends GetValueResponse
  case class Conflicts(data: List[Data]) extends GetValueResponse
  case class NotFound(id: UUID)          extends GetValueResponse
  case class Failure(error: String)      extends GetValueResponse
}

sealed trait WriteValueResponse
object WriteValueResponse {
  case class Success(id: UUID)      extends WriteValueResponse
  case object Conflict              extends WriteValueResponse
  case class Failure(error: String) extends WriteValueResponse
} 
Example 131
Source File: ActorRefStorageNodeClient.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db.client

import java.util.UUID

import akka.pattern.ask
import akka.util.Timeout
import justin.db.Data
import justin.db.actors.StorageNodeActorRef
import justin.db.actors.protocol._
import justin.db.replica.{R, W}

import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}

class ActorRefStorageNodeClient(storageNodeActor: StorageNodeActorRef)(implicit ex: ExecutionContext) extends StorageNodeClient {

  implicit val timeout = Timeout(5.seconds) // TODO: tune this value

  override def get(id: UUID, r: R): Future[GetValueResponse] = {
    (storageNodeActor.ref ? Internal.ReadReplica(r, id)).mapTo[StorageNodeReadResponse].map {
      case StorageNodeFoundRead(data)      => GetValueResponse.Found(data)
      case StorageNodeConflictedRead(data) => GetValueResponse.Conflicts(data)
      case StorageNodeNotFoundRead(id)     => GetValueResponse.NotFound(id)
      case StorageNodeFailedRead(_)        => GetValueResponse.Failure(s"Couldn't read value with id ${id.toString}")
    } recover { case ex: Throwable         => GetValueResponse.Failure(s"Unsuccessful read of value with id ${id.toString}") }
  }

  override def write(data: Data, w: W): Future[WriteValueResponse] = {
    (storageNodeActor.ref ? Internal.WriteReplica(w, data)).mapTo[StorageNodeWriteResponse].map {
      case StorageNodeSuccessfulWrite(id)   => WriteValueResponse.Success(id)
      case StorageNodeConflictedWrite(_, _) => WriteValueResponse.Conflict
      case StorageNodeFailedWrite(id)       => WriteValueResponse.Failure(s"Couldn't write value with id ${id.toString}")
    } recover { case ex: Throwable          => WriteValueResponse.Failure(s"Unsuccessful write of value with id ${data.id.toString}") }
  }
} 
Example 132
Source File: DataTest.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db

import java.util.UUID

import justin.db.consistenthashing.NodeId
import justin.db.replica.PreferenceList
import justin.db.vectorclocks.{Counter, VectorClock}
import org.scalatest.{FlatSpec, Matchers}

class DataTest extends FlatSpec with Matchers {

  behavior of "Data"

  it should "update its empty inner Vector Clock based on preference list" in {
    // given
    val data           = Data(id = UUID.randomUUID(), value = "some value")
    val preferenceList = PreferenceList(NodeId(1), List(NodeId(5), NodeId(8)))

    // when
    val updatedData = Data.updateVclock(data, preferenceList)

    // then
    val expectedVclock = VectorClock[NodeId](Map(
      NodeId(1) -> Counter(1),
      NodeId(5) -> Counter(1),
      NodeId(8) -> Counter(1))
    )
    updatedData shouldBe Data(data.id, data.value, expectedVclock, updatedData.timestamp)
  }

  it should "increase vector clock's counter of repeated nodeId when updating data" in {
    // given
    val data           = Data(id = UUID.randomUUID(), value = "some value")
    val preferenceList = PreferenceList(NodeId(1), List(NodeId(1), NodeId(1)))

    // when
    val updatedData = Data.updateVclock(data, preferenceList)

    // then
    val expectedVclock = VectorClock[NodeId](Map(
      NodeId(1) -> Counter(3)
    ))
    updatedData shouldBe Data(data.id, data.value, expectedVclock, data.timestamp)
  }

  it should "increase already existed vector clock's counter when updating data" in {
    // given
    val initVClock     = VectorClock[NodeId](Map(NodeId(1) -> Counter(3)))
    val data = Data(id = UUID.randomUUID(), value = "some value", initVClock)
    val preferenceList = PreferenceList(NodeId(1), List(NodeId(5), NodeId(8)))

    // when
    val updatedData = Data.updateVclock(data, preferenceList)

    // then
    val expectedVclock = VectorClock[NodeId](Map(
      NodeId(1) -> Counter(4),
      NodeId(5) -> Counter(1),
      NodeId(8) -> Counter(1))
    )
    updatedData shouldBe Data(data.id, data.value, expectedVclock, data.timestamp)
  }
} 
Example 133
Source File: DataSerializerTest.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db.kryo

import java.io.{ByteArrayInputStream, ByteArrayOutputStream}
import java.util.UUID

import com.esotericsoftware.kryo.Kryo
import com.esotericsoftware.kryo.io.{Input, Output}
import justin.db.Data
import justin.db.consistenthashing.NodeId
import justin.db.vectorclocks.{Counter, VectorClock}
import org.scalatest.{FlatSpec, Matchers}

class DataSerializerTest extends FlatSpec with Matchers {

  behavior of "Data Serializer"

  it should "serialize/deserialize correctly" in {
    // kryo init
    val kryo = new Kryo()
    kryo.register(classOf[justin.db.Data], DataSerializer)

    // object
    val vClock         = VectorClock[NodeId](Map(NodeId(1) -> Counter(3)))
    val timestamp      = System.currentTimeMillis()
    val serializedData = Data(id = UUID.randomUUID(), value = "some value", vClock, timestamp)

    // serialization
    val bos    = new ByteArrayOutputStream()
    val output = new Output(bos)
    val _      = kryo.writeObject(output, serializedData)
    output.flush()

    // deserialization
    val bis              = new ByteArrayInputStream(bos.toByteArray)
    val input            = new Input(bis)
    val deserializedData = kryo.readObject(input, classOf[Data])

    serializedData shouldBe deserializedData
  }
} 
Example 134
Source File: StorageNodeWriteDataLocalSerializerTest.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db.kryo

import java.io.{ByteArrayInputStream, ByteArrayOutputStream}
import java.util.UUID

import com.esotericsoftware.kryo.Kryo
import com.esotericsoftware.kryo.io.{Input, Output}
import justin.db.Data
import justin.db.actors.protocol.StorageNodeWriteDataLocal
import justin.db.consistenthashing.NodeId
import justin.db.vectorclocks.{Counter, VectorClock}
import org.scalatest.{FlatSpec, Matchers}

class StorageNodeWriteDataLocalSerializerTest extends FlatSpec with Matchers {

  behavior of "StorageNodeWriteDataLocal Serializer"

  it should "serialize/deserialize StorageNodeWriteDataLocal" in {
    // kryo init
    val kryo = new Kryo()
    kryo.register(classOf[StorageNodeWriteDataLocal], StorageNodeWriteDataLocalSerializer)

    // object
    val data = Data(
      id        = UUID.randomUUID(),
      value     = "some value",
      vclock    = VectorClock[NodeId](Map(NodeId(1) -> Counter(3))),
      timestamp = System.currentTimeMillis()
    )
    val serializedData = StorageNodeWriteDataLocal(data)

    // serialization
    val bos    = new ByteArrayOutputStream()
    val output = new Output(bos)
    val _      = kryo.writeObject(output, serializedData)
    output.flush()

    // deserialization
    val bis              = new ByteArrayInputStream(bos.toByteArray)
    val input            = new Input(bis)
    val deserializedData = kryo.readObject(input, classOf[StorageNodeWriteDataLocal])

    serializedData shouldBe deserializedData
  }
} 
Example 135
Source File: StorageNodeLocalReadSerializerTest.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db.kryo

import java.io.{ByteArrayInputStream, ByteArrayOutputStream}
import java.util.UUID

import com.esotericsoftware.kryo.Kryo
import com.esotericsoftware.kryo.io.{Input, Output}
import justin.db.actors.protocol.StorageNodeLocalRead
import org.scalatest.{FlatSpec, Matchers}

class StorageNodeLocalReadSerializerTest extends FlatSpec with Matchers {

  behavior of "StorageNodeLocalReader Serializer"

  it should "serialize/deserialize correctly" in {
    // kryo init
    val kryo = new Kryo()
    kryo.register(classOf[StorageNodeLocalRead], StorageNodeLocalReadSerializer)

    // object
    val serializedData = StorageNodeLocalRead(UUID.randomUUID())

    // serialization
    val bos    = new ByteArrayOutputStream()
    val output = new Output(bos)
    val _      = kryo.writeObject(output, serializedData)
    output.flush()

    // deserialization
    val bis              = new ByteArrayInputStream(bos.toByteArray)
    val input            = new Input(bis)
    val deserializedData = kryo.readObject(input, classOf[StorageNodeLocalRead])

    serializedData shouldBe deserializedData
  }
} 
Example 136
Source File: IsPrimaryOrReplicaTest.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db.replica

import java.util.UUID

import justin.db.consistenthashing.{NodeId, Ring}
import justin.db.storage.PluggableStorageProtocol.DataOriginality
import org.scalatest.{FlatSpec, Matchers}

class IsPrimaryOrReplicaTest extends FlatSpec with Matchers {

  behavior of "Data Originality Resolver"

  it should "reason exemplary data's id as a replica" in {
    // given
    val nodeId   = NodeId(0)
    val ring     = Ring.apply(nodesSize = 3, partitionsSize = 21)
    val resolver = new IsPrimaryOrReplica(nodeId, ring)
    val id       = UUID.fromString("179d6eb0-681d-4277-9caf-3d6d60e9faf9")

    // when
    val originality = resolver.apply(id)

    // then
    originality shouldBe a[DataOriginality.Replica]
  }

  it should "reason exemplary data's id as a primary" in {
    // given
    val nodeId   = NodeId(0)
    val ring     = Ring.apply(nodesSize = 3, partitionsSize = 21)
    val resolver = new IsPrimaryOrReplica(nodeId, ring)
    val id       = UUID.fromString("16ec44cd-5b4e-4b38-a647-206c1dc11b50")

    // when
    val originality = resolver.apply(id)

    // then
    originality shouldBe a[DataOriginality.Primary]
  }
} 
Example 137
Source File: ReplicaLocalWriterTest.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db.replica.write

import java.util.UUID

import justin.db.Data
import justin.db.actors.protocol.{StorageNodeConflictedWrite, StorageNodeFailedWrite, StorageNodeSuccessfulWrite}
import justin.db.consistenthashing.NodeId
import justin.db.storage.PluggableStorageProtocol.{Ack, DataOriginality, StorageGetData}
import justin.db.storage.{GetStorageProtocol, JustinData, PutStorageProtocol}
import justin.db.vectorclocks.{Counter, VectorClock}
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{FlatSpec, Matchers}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.concurrent.duration._

class ReplicaLocalWriterTest extends FlatSpec with Matchers with ScalaFutures {

  behavior of "Replica Local Writer"

  override implicit def patienceConfig: PatienceConfig = PatienceConfig(10.seconds, 50.millis)

  
  it should "fail to write predecessor to already stored data" in {
    // given
    val id      = UUID.randomUUID()
    val data    = Data(id, "some-value", VectorClock(Map(NodeId(1) -> Counter(2))))
    val newData = Data(id, "some-value-2", VectorClock(Map(NodeId(1) -> Counter(1))))
    val writer = new ReplicaLocalWriter(new GetStorageProtocol with PutStorageProtocol {
      override def get(id: UUID)(resolveOriginality: (UUID) => DataOriginality): Future[StorageGetData] = Future.successful(StorageGetData.Single(data))
      override def put(data: JustinData)(resolveOriginality: (UUID) => DataOriginality): Future[Ack] = ???
    })

    // when
    val result = writer.apply(newData, null)

    // then
    whenReady(result) { _ shouldBe StorageNodeFailedWrite(id) }
  }

  it should "get conflicted write when trying to save new data with conflicted vector clock comparing to already existed one" in {
    // given
    val id      = UUID.randomUUID()
    val data    = Data(id, "some-value", VectorClock(Map(NodeId(1) -> Counter(1))))
    val newData = Data(id, "some-value-2", VectorClock(Map(NodeId(2) -> Counter(1))))
    val writer = new ReplicaLocalWriter(new GetStorageProtocol with PutStorageProtocol {
      override def get(id: UUID)(resolveOriginality: (UUID) => DataOriginality): Future[StorageGetData] = Future.successful(StorageGetData.Single(data))
      override def put(data: JustinData)(resolveOriginality: (UUID) => DataOriginality): Future[Ack] = Ack.future
    })

    // when
    val result = writer.apply(newData, null)

    // then
    whenReady(result) { _ shouldBe StorageNodeConflictedWrite(data, newData) }
  }

  it should "get successful write when trying to save new data with consequent vector clock comparing to already existed one" in {
    // given
    val id      = UUID.randomUUID()
    val data    = Data(id, "some-value", VectorClock(Map(NodeId(1) -> Counter(1))))
    val newData = Data(id, "some-value-2", VectorClock(Map(NodeId(1) -> Counter(2))))
    val writer = new ReplicaLocalWriter(new GetStorageProtocol with PutStorageProtocol {
      override def get(id: UUID)(resolveOriginality: (UUID) => DataOriginality): Future[StorageGetData] = Future.successful(StorageGetData.Single(data))
      override def put(data: JustinData)(resolveOriginality: (UUID) => DataOriginality): Future[Ack] = Ack.future
    })

    // when
    val result = writer.apply(newData, null)

    // then
    whenReady(result) { _ shouldBe StorageNodeSuccessfulWrite(id) }
  }
} 
Example 138
Source File: ReplicaRemoteWriterTest.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db.replica.write

import java.util.UUID

import akka.actor.{Actor, ActorSystem}
import akka.testkit.{TestActorRef, TestKit}
import justin.db.Data
import justin.db.actors.StorageNodeActorRef
import justin.db.actors.protocol.{StorageNodeFailedWrite, StorageNodeSuccessfulWrite, StorageNodeWriteDataLocal}
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{FlatSpecLike, Matchers}

import scala.concurrent.duration._

class ReplicaRemoteWriterTest extends TestKit(ActorSystem("test-system"))
  with FlatSpecLike
  with Matchers
  with ScalaFutures {

  behavior of "Replica Remote Writer"

  override implicit def patienceConfig: PatienceConfig = PatienceConfig(10.seconds, 50.millis)

  it should "get info back that one of the saving is successful and second one has failed" in {
    // given
    val service = new ReplicaRemoteWriter()(system.dispatcher)
    val data = Data(id = UUID.randomUUID(), value = "exemplary-value")
    val storageSuccessfulActorRef = testActorRef(msgBack = StorageNodeSuccessfulWrite(data.id))
    val storageFailedActorRef     = testActorRef(msgBack = StorageNodeFailedWrite(data.id))
    val storageNodeRefs           = List(storageSuccessfulActorRef, storageFailedActorRef).map(StorageNodeActorRef)

    // when
    val writingResult = service.apply(storageNodeRefs, data)

    // then
    whenReady(writingResult) { _ shouldBe List(StorageNodeSuccessfulWrite(data.id), StorageNodeFailedWrite(data.id)) }
  }

  it should "recover failed behavior of actor" in {
    // given
    val service = new ReplicaRemoteWriter()(system.dispatcher)
    val data = Data(id = UUID.randomUUID(), value = "exemplary-value")
    val storageActorRef = testActorRef(new Exception)
    val storageNodeRefs = List(StorageNodeActorRef(storageActorRef))

    // when
    val writingResult = service.apply(storageNodeRefs, data)

    // then
    whenReady(writingResult) { _ shouldBe List(StorageNodeFailedWrite(data.id)) }
  }

  private def testActorRef(msgBack: => Any) = {
    TestActorRef(new Actor {
      override def receive: Receive = {
        case StorageNodeWriteDataLocal(id) => sender() ! msgBack
      }
    })
  }
} 
Example 139
Source File: ReplicaWriteAgreementTest.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db.replica.write

import java.util.UUID

import justin.db.actors.protocol.{StorageNodeFailedWrite, StorageNodeSuccessfulWrite}
import justin.db.replica.W
import org.scalatest.{FlatSpec, Matchers}

class ReplicaWriteAgreementTest extends FlatSpec with Matchers {

  behavior of "Reach Consensus of Replicated Writes"

  it should "agreed on \"SuccessfulWrite\" if number of successful write is not less than client expectations" in {
    // given
    val w = W(2)
    val writes = List(StorageNodeSuccessfulWrite(UUID.randomUUID()), StorageNodeSuccessfulWrite(UUID.randomUUID()), StorageNodeFailedWrite(UUID.randomUUID()))

    // when
    val result = new ReplicaWriteAgreement().reach(w)(writes)

    // then
    result shouldBe WriteAgreement.Ok
  }

  it should "agreed on \"NotEnoughWrites\" if number of successful write is less than client expectations" in {
    // given
    val w = W(3)
    val writes = List(StorageNodeSuccessfulWrite(UUID.randomUUID()), StorageNodeSuccessfulWrite(UUID.randomUUID()), StorageNodeFailedWrite(UUID.randomUUID()))

    // when
    val result = new ReplicaWriteAgreement().reach(w)(writes)

    // then
    result shouldBe WriteAgreement.NotEnoughWrites
  }
} 
Example 140
Source File: ReplicaRemoteReaderTest.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db.replica.read

import java.util.UUID

import akka.actor.{Actor, ActorSystem}
import akka.testkit.{TestActorRef, TestKit}
import justin.db.Data
import justin.db.actors.StorageNodeActorRef
import justin.db.actors.protocol._
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{FlatSpecLike, Matchers}

import scala.concurrent.duration._

class ReplicaRemoteReaderTest extends TestKit(ActorSystem("test-system"))
  with FlatSpecLike
  with Matchers
  with ScalaFutures {

  behavior of "Replica Remote Reader"

  override implicit def patienceConfig: PatienceConfig = PatienceConfig(10.seconds, 50.millis)

  it should "get info back that one of the value could be found and second one is obsolete" in {
    // given
    val service = new ReplicaRemoteReader()(system.dispatcher)
    val id = UUID.randomUUID()
    val foundData = Data(id, "value")
    val notFoundId = UUID.randomUUID()
    val storageNotFoundActorRef = testActorRef(msgBack = StorageNodeNotFoundRead(notFoundId))
    val storageFoundActorRef    = testActorRef(msgBack = StorageNodeFoundRead(foundData))
    val storageNodeRefs         = List(storageNotFoundActorRef, storageFoundActorRef).map(StorageNodeActorRef)

    // when
    val readingResult = service.apply(storageNodeRefs, id)

    // then
    whenReady(readingResult) { _ shouldBe List(StorageNodeNotFoundRead(notFoundId), StorageNodeFoundRead(foundData)) }
  }

  it should "recover failed behavior of actor" in {
    // given
    val service = new ReplicaRemoteReader()(system.dispatcher)
    val id = UUID.randomUUID()
    val storageActorRef = testActorRef(new Exception)
    val storageNodeRefs = List(StorageNodeActorRef(storageActorRef))

    // when
    val readingResult = service.apply(storageNodeRefs, id)

    // then
    whenReady(readingResult) { _ shouldBe List(StorageNodeFailedRead(id)) }
  }

  private def testActorRef(msgBack: => Any) = {
    TestActorRef(new Actor {
      override def receive: Receive = {
        case StorageNodeLocalRead(id) => sender() ! msgBack
      }
    })
  }
} 
Example 141
Source File: ReplicaLocalReaderTest.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db.replica.read

import java.util.UUID

import justin.db.Data
import justin.db.actors.protocol.{StorageNodeFailedRead, StorageNodeFoundRead, StorageNodeNotFoundRead}
import justin.db.consistenthashing.NodeId
import justin.db.storage.GetStorageProtocol
import justin.db.storage.PluggableStorageProtocol.{DataOriginality, StorageGetData}
import justin.db.vectorclocks.VectorClock
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{FlatSpec, Matchers}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.concurrent.Future

class ReplicaLocalReaderTest extends FlatSpec with Matchers with ScalaFutures {

  behavior of "Replica Local Reader"

  override implicit def patienceConfig: PatienceConfig = PatienceConfig(10.seconds, 50.millis)

  it should "found data for existing key" in {
    // given
    val id   = UUID.randomUUID()
    val data = Data(id, "value", VectorClock[NodeId]().increase(NodeId(1)))
    val service = new ReplicaLocalReader(new GetStorageProtocol {
      override def get(id: UUID)(resolveOriginality: (UUID) => DataOriginality): Future[StorageGetData] = {
        Future.successful(StorageGetData.Single(data))
      }
    })

    // when
    val result = service.apply(id, null)

    // then
    whenReady(result) { _ shouldBe StorageNodeFoundRead(data) }
  }

  it should "not found data for non-existing key" in {
    // given
    val id = UUID.randomUUID()
    val service = new ReplicaLocalReader(new GetStorageProtocol {
      override def get(id: UUID)(resolveOriginality: (UUID) => DataOriginality): Future[StorageGetData] = {
        Future.successful(StorageGetData.None)
      }
    })

    // when
    val result = service.apply(id, null)

    // then
    whenReady(result) { _ shouldBe StorageNodeNotFoundRead(id) }
  }

  it should "recover failure reading" in {
    // given
    val id = UUID.randomUUID()
    val service = new ReplicaLocalReader(new GetStorageProtocol {
      override def get(id: UUID)(resolveOriginality: (UUID) => DataOriginality): Future[StorageGetData] = Future.failed(new Exception)
    })

    // when
    val result = service.apply(id, null)

    // then
    whenReady(result) { _ shouldBe StorageNodeFailedRead(id) }
  }
} 
Example 142
Source File: Unmarshallers.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.httpapi

import java.util.UUID

import akka.http.scaladsl.unmarshalling._
import akka.stream.Materializer
import spray.json.{JsString, JsValue, JsonFormat, _}

import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Failure, Success, Try}

object Unmarshallers {

  implicit val UuidFormat = new JsonFormat[UUID] {
    override def read(json: JsValue): UUID = {
      json match {
        case JsString(uuid) => Try(UUID.fromString(uuid)) match {
          case Success(parsedUuid) => parsedUuid
          case Failure(_)          => deserializationError("UUID could not be created from given string")
        }
        case _ => deserializationError("UUID could not be converted to UUID object.")
      }
    }
    override def write(obj: UUID): JsValue = JsString(obj.toString)
  }

  object UUIDUnmarshaller extends FromStringUnmarshaller[UUID] {
    override def apply(value: String)(implicit ec: ExecutionContext, materializer: Materializer): Future[UUID] = {
      Future.apply(UUID.fromString(value))
    }
  }
} 
Example 143
Source File: HttpRouter.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.httpapi

import java.util.UUID

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import justin.db.Data
import justin.db.client.{ActorRefStorageNodeClient, GetValueResponse, WriteValueResponse}
import justin.db.replica.{R, W}
import justin.db.storage.Base64
import justin.db.versioning.NodeIdVectorClockBase64
import justin.httpapi.JustinDirectives._
import justin.httpapi.Unmarshallers.UUIDUnmarshaller
import spray.json.DefaultJsonProtocol._
import spray.json.RootJsonFormat

import scala.concurrent.ExecutionContext
import scala.util.{Failure, Success}

object HttpRouter {
  import Unmarshallers.UuidFormat

  case class Result(value: String)
  implicit val valueFormat: RootJsonFormat[Result] = jsonFormat1(Result)

  case class ConflictedData(id: String, value: String, vclock: Base64)
  implicit val conflictedDataFormat: RootJsonFormat[ConflictedData] = jsonFormat3(ConflictedData)

  case class PutValue(id: UUID, value: String, w: Int)
  implicit val putValueFormat: RootJsonFormat[PutValue] = jsonFormat3(PutValue)
}

class HttpRouter(client: ActorRefStorageNodeClient)(implicit ec: ExecutionContext) {
  import HttpRouter._

  private[this] def transformConflictedData(data: Data) = {
    val vcBase64 = new NodeIdVectorClockBase64().encode(data.vclock).get
    ConflictedData(data.id.toString, data.value, vcBase64)
  }

  def routes: Route = withVectorClockHeader { vClockHeader =>
    {
      (get & path("get") & pathEndOrSingleSlash & parameters(('id.as(UUIDUnmarshaller), 'r.as[Int]))) { (uuid, r) =>
        onComplete(client.get(uuid, R(r))) {
          case Success(GetValueResponse.Found(data))     => respondWithHeader(VectorClockHeader(data.vclock)) { complete(OK -> Result(data.value)) }
          case Success(GetValueResponse.Conflicts(data)) => complete(MultipleChoices -> data.map(transformConflictedData))
          case Success(GetValueResponse.NotFound(id))    => complete(NotFound -> Result(s"Couldn't found value with id ${id.toString}"))
          case Success(GetValueResponse.Failure(err))    => complete(BadRequest -> Result(err))
          case Failure(ex)                               => complete(InternalServerError -> Result(ex.getMessage))
        }
      }
    } ~
    (post & path("put") & pathEndOrSingleSlash & entity(as[PutValue])) { putValue =>
      complete {
        client.write(Data(putValue.id, putValue.value, vClockHeader.vectorClock), W(putValue.w)).map[ToResponseMarshallable] {
          case WriteValueResponse.Success(id)  => NoContent
          case WriteValueResponse.Conflict     => MultipleChoices -> Result("Multiple Choices")
          case WriteValueResponse.Failure(err) => BadRequest      -> Result(err)
        }
      }
    }
  }
} 
Example 144
Source File: UnmarshallersTest.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.httpapi

import java.util.UUID

import org.scalatest.{FlatSpec, Matchers}
import spray.json.{DeserializationException, JsNumber, JsString}

class UnmarshallersTest extends FlatSpec with Matchers {

  behavior of "Unmarshaller"

  it should "encode JSON into UUID" in {
    val uuid = UUID.randomUUID()
    val jsString = JsString(uuid.toString)

    Unmarshallers.UuidFormat.read(jsString) shouldBe uuid
  }

  it should "decode UUID into JSON" in {
    val uuid = UUID.randomUUID()
    val expectedJSON = Unmarshallers.UuidFormat.write(uuid)

    expectedJSON shouldBe JsString(uuid.toString)
  }

  it should "handle not expected format of JSON" in {
    val jsNumber = JsNumber(1)

    intercept[DeserializationException] {
      Unmarshallers.UuidFormat.read(jsNumber)
    }
  }

  it should "handle wrong format of UUID" in {
    val fakeUUID = "1-2-3-4"
    val jsString = JsString(fakeUUID)

    intercept[DeserializationException] {
      Unmarshallers.UuidFormat.read(jsString)
    }
  }
} 
Example 145
Source File: RocksDBStorage.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db.storage

import java.io.{ByteArrayInputStream, ByteArrayOutputStream, File}
import java.util.UUID

import com.esotericsoftware.kryo.io.{Input, Output}
import com.esotericsoftware.kryo.{Kryo, Serializer}
import justin.db.storage.PluggableStorageProtocol.{Ack, StorageGetData}
import org.rocksdb.{FlushOptions, Options, RocksDB}

import scala.concurrent.Future

// TODO:
// Current version store every single data under one file (totally doesn't care about data originality).
// Data should be eventually splitted by ring partitionId.
// This might be an issue during possible data movements between nodes.
final class RocksDBStorage(dir: File) extends PluggableStorageProtocol {
  import RocksDBStorage._

  {
    RocksDB.loadLibrary()
  }

  private[this] val kryo = new Kryo()

  private[this] val db: RocksDB = {
    val options: Options = new Options().setCreateIfMissing(true)
    RocksDB.open(options, dir.getPath)
  }

  override def get(id: UUID)(resolveOriginality: (UUID) => PluggableStorageProtocol.DataOriginality): Future[PluggableStorageProtocol.StorageGetData] = {
    val key: Array[Byte] = uuid2bytes(kryo, id)
    val dataBytes: Array[Byte] = db.get(key)

    val justinDataOpt = Option(dataBytes).map { dataBytes =>
      val input = new Input(new ByteArrayInputStream(dataBytes))
      JustinDataSerializer.read(kryo, input, classOf[JustinData])
    }

    Future.successful(justinDataOpt.map(StorageGetData.Single).getOrElse(StorageGetData.None))
  }

  override def put(data: JustinData)(resolveOriginality: (UUID) => PluggableStorageProtocol.DataOriginality): Future[PluggableStorageProtocol.Ack] = {
    val key: Array[Byte] = uuid2bytes(kryo, data.id)
    val dataBytes: Array[Byte] = {
      val output = new Output(new ByteArrayOutputStream())
      JustinDataSerializer.write(kryo, output, data)
      output.getBuffer
    }

    db.put(key, dataBytes)
    db.flush(new FlushOptions().setWaitForFlush(true))

    Ack.future
  }
}

object RocksDBStorage {

  def uuid2bytes(kryo: Kryo, id: UUID): Array[Byte] = {
    val output = new Output(new ByteArrayOutputStream(), 16)
    UUIDSerializer.write(kryo, output, id)
    output.getBuffer
  }

  object UUIDSerializer extends Serializer[UUID] {
    override def read(kryo: Kryo, input: Input, `type`: Class[UUID]): UUID = {
      new UUID(input.readLong, input.readLong)
    }

    override def write(kryo: Kryo, output: Output, uuid: UUID): Unit = {
      output.writeLong(uuid.getMostSignificantBits)
      output.writeLong(uuid.getLeastSignificantBits)
    }
  }

  object JustinDataSerializer extends Serializer[JustinData] {
    override def read(kryo: Kryo, input: Input, `type`: Class[JustinData]): JustinData = {
      JustinData(
        id        = UUIDSerializer.read(kryo, input, classOf[UUID]),
        value     = input.readString(),
        vclock    = input.readString(),
        timestamp = input.readLong()
      )
    }

    override def write(kryo: Kryo, output: Output, data: JustinData): Unit = {
      UUIDSerializer.write(kryo, output, data.id)
      output.writeString(data.value)
      output.writeString(data.vclock)
      output.writeLong(data.timestamp)
    }
  }
} 
Example 146
Source File: JustinDataSerializerTest.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db.storage

import java.io.{ByteArrayInputStream, ByteArrayOutputStream}
import java.util.UUID

import com.esotericsoftware.kryo.Kryo
import com.esotericsoftware.kryo.io.{Input, Output}
import justin.db.storage.RocksDBStorage.JustinDataSerializer
import org.scalatest.{FlatSpec, Matchers}

class JustinDataSerializerTest extends FlatSpec with Matchers {

  behavior of "JustinDataSerializer"

  it should "serialize/deserialize JustinData with Kryo" in {
    val kryo = new Kryo()
    val data = JustinData(
      id        = UUID.randomUUID,
      value     = "to jest przykladowa wartość",
      vclock    = "vclock-value",
      timestamp = 1234124L
    )

    // serialize
    val output = new Output(new ByteArrayOutputStream())
    JustinDataSerializer.write(kryo, output, data)
    val dataBytes = output.getBuffer

    // deserialize
    val input = new Input(new ByteArrayInputStream(dataBytes))
    JustinDataSerializer.read(kryo, input, classOf[JustinData]) shouldBe data
  }
} 
Example 147
Source File: RocksDBStorageTest.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db.storage

import java.nio.file.Files
import java.util.UUID

import justin.db.storage.PluggableStorageProtocol.{Ack, DataOriginality, StorageGetData}
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{FlatSpec, Matchers}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._

class RocksDBStorageTest extends FlatSpec with Matchers  with ScalaFutures {

  behavior of "RocksDBStorage"

  it should "save 3 payloads and read them" in {
    val journal = Files.createTempDirectory("rocksdb")
    val rocksdb = new RocksDBStorage(journal.toFile)
    val data1 = JustinData(
      id        = UUID.randomUUID,
      value     = "1",
      vclock    = "vclock-value",
      timestamp = 1234124L
    )
    val data2 = JustinData(
      id        = UUID.randomUUID,
      value     = "1",
      vclock    = "vclock-value",
      timestamp = 1234124L
    )
    val data3 = JustinData(
      id        = UUID.randomUUID,
      value     = "3",
      vclock    = "vclock-value",
      timestamp = 1234124L
    )
    val dataOriginality = DataOriginality.Primary(ringPartitionId = 1)

    // PUT
    rocksdb.put(data1)(_ => dataOriginality).futureValue shouldBe Ack
    rocksdb.put(data2)(_ => dataOriginality).futureValue shouldBe Ack
    rocksdb.put(data3)(_ => dataOriginality).futureValue shouldBe Ack

    // GET
    rocksdb.get(data3.id)(_ => dataOriginality).futureValue shouldBe StorageGetData.Single(data3)
    rocksdb.get(data2.id)(_ => dataOriginality).futureValue shouldBe StorageGetData.Single(data2)
    rocksdb.get(data1.id)(_ => dataOriginality).futureValue shouldBe StorageGetData.Single(data1)
  }

  override implicit def patienceConfig: PatienceConfig = PatienceConfig(10.seconds, 50.millis)
} 
Example 148
Source File: UUIDSerializerTest.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db.storage

import java.io.ByteArrayInputStream
import java.util.UUID

import com.esotericsoftware.kryo.Kryo
import com.esotericsoftware.kryo.io.Input
import justin.db.storage.RocksDBStorage.UUIDSerializer
import org.scalatest.{FlatSpec, Matchers}

class UUIDSerializerTest extends FlatSpec with Matchers {

  behavior of "UUIDSerializer"

  it should "serialize/deserialize UUID with Kryo" in {
    val uuid = UUID.randomUUID()
    val kryo = new Kryo()

    // serialize
    val bytes = RocksDBStorage.uuid2bytes(kryo, uuid)

    // deserialize
    val input = new Input(new ByteArrayInputStream(bytes))
    val id = UUIDSerializer.read(kryo, input, classOf[UUID])

    uuid shouldBe id
  }
} 
Example 149
Source File: PluggableStorageProtocol.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db.storage

import java.util.UUID

import justin.db.storage.PluggableStorageProtocol.{Ack, DataOriginality, StorageGetData}

import scala.concurrent.Future

trait GetStorageProtocol {
  def get(id: UUID)(resolveOriginality: UUID => DataOriginality): Future[StorageGetData]
}

trait PutStorageProtocol {
  def put(data: JustinData)(resolveOriginality: UUID => DataOriginality): Future[Ack]
}

trait PluggableStorageProtocol extends GetStorageProtocol with PutStorageProtocol

object PluggableStorageProtocol {
  
  sealed trait StorageGetData
  object StorageGetData {
    case class Single(data: JustinData) extends StorageGetData
    case object None                    extends StorageGetData
  }

  sealed trait Ack
  case object Ack extends Ack {
    val future: Future[Ack] = Future.successful(Ack)
  }

  sealed trait DataOriginality { def ringPartitionId: RingPartitionId }
  object DataOriginality {
    case class Primary(ringPartitionId: RingPartitionId) extends DataOriginality
    case class Replica(ringPartitionId: RingPartitionId) extends DataOriginality
  }
} 
Example 150
Source File: Generators.scala    From finagle-postgres   with Apache License 2.0 5 votes vote down vote up
package com.twitter.finagle.postgres

import java.nio.charset.StandardCharsets
import java.time.{ZonedDateTime, _}
import java.time.temporal.JulianFields
import java.util.UUID

import org.scalacheck.{Arbitrary, Gen}
import Arbitrary.arbitrary
import com.twitter.finagle.postgres.values.Interval

object Generators {
  //need a more sensible BigDecimal generator, because ScalaCheck goes crazy with it and we can't even stringify them
  //this will be sufficient to test the decoder
  implicit val arbBD: Arbitrary[BigDecimal] = Arbitrary(for {
    precision <- Gen.choose(1, 32)
    scale <- Gen.choose(-precision, precision)
    digits <- Gen.listOfN[Char](precision, Gen.numChar)
  } yield BigDecimal(BigDecimal(digits.mkString).bigDecimal.movePointLeft(scale)))

  implicit val arbDate = Arbitrary[LocalDate](for {
    julian <- Gen.choose(1721060, 5373484)  //Postgres date parser doesn't like dates outside year range 0000-9999
  } yield LocalDate.now().`with`(JulianFields.JULIAN_DAY, julian))

  implicit val arbTime: Arbitrary[LocalTime] = Arbitrary[LocalTime](for {
    usec <- Gen.choose(0L, 24L * 60 * 60 * 1000000 - 1)
  } yield LocalTime.ofNanoOfDay(usec * 1000))

  implicit val arbInstant = Arbitrary[Instant](for {
    milli <- Gen.posNum[Long]
  } yield Instant.ofEpochMilli(milli))

  implicit val arbTimestamp = Arbitrary[LocalDateTime](for {
    milli <- Gen.posNum[Long]
  } yield LocalDateTime.ofInstant(Instant.ofEpochMilli(milli), ZoneId.systemDefault()))

  implicit val arbTimestampTz = Arbitrary[ZonedDateTime](for {
    milli <- Gen.posNum[Long]
  } yield ZonedDateTime.ofInstant(Instant.ofEpochMilli(milli), ZoneId.systemDefault()))

  implicit val arbZoneOffset = Arbitrary(Gen.choose(-12, 12).map(ZoneOffset.ofHours))

  implicit val arbInterval = Arbitrary(for {
    months <- Gen.choose(-120, 120)
    years <- Gen.choose(-10, 10)
    days <- Gen.choose(-50, 50)
    hours <- Gen.choose(-50, 50)
    minutes <- Gen.choose(0, 59)
    seconds <- Gen.choose(0, 59)
  } yield Interval(
    Duration.ofSeconds(seconds).plusMinutes(minutes).plusHours(hours),
    Period.ofMonths(months).plusYears(years).plusDays(days)
  ))

  implicit val arbTimeTz = Arbitrary[OffsetTime](for {
    time <- arbitrary[LocalTime]
    offs <- arbitrary[ZoneOffset]
  } yield time.atOffset(offs))

  implicit val arbUUID = Arbitrary[UUID](Gen.uuid)

  // arbitrary string that only contains valid UTF-8 characters
  val utf8 = StandardCharsets.UTF_8.newEncoder()
  implicit val arbUTF8String = Arbitrary(arbitrary[String].filter {
    str => utf8.canEncode(str) && !str.contains('\u0000')
  })

  // TODO: can empty maps be supported?
  implicit val arbHStore: Arbitrary[Map[String, Option[String]]] = Arbitrary(
    Gen.mapOf(for {
      k <- Gen.identifier
      v <- Gen.oneOf(Gen.alphaStr.map(Some(_)), Gen.const(None))
    } yield (k, v)).suchThat(_.nonEmpty)
  )

  // postgres has slightly different precision rules, but that doesn't mean the decoder isn't working
  implicit val arbFloat = Arbitrary[Float](for {
    precision <- Gen.choose(1, 6)
    scale <- Gen.choose(-10, 10)
    digits <- Gen.listOfN[Char](precision, Gen.numChar)
  } yield BigDecimal(BigDecimal(digits.mkString).bigDecimal.movePointLeft(scale)).toFloat)

  implicit val arbDouble = Arbitrary[Double](for {
    precision <- Gen.choose(1, 15)
    scale <- Gen.choose(-20, 20)
    digits <- Gen.listOfN[Char](precision, Gen.numChar)
  } yield BigDecimal(BigDecimal(digits.mkString).bigDecimal.movePointLeft(scale)).toDouble)
} 
Example 151
Source File: VirtualScreeningTest.scala    From MaRe   with Apache License 2.0 5 votes vote down vote up
package se.uu.it.mare

import java.io.File
import java.util.UUID

import scala.io.Source
import scala.util.Properties

import org.apache.spark.SharedSparkContext
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner

private object SDFUtils {
  def parseIDsAndScores(sdf: String): Array[(String, String)] = {
    sdf.split("\\n\\$\\$\\$\\$\\n").map { mol =>
      val lines = mol.split("\\n")
      (lines(0), lines.last)
    }
  }
}

@RunWith(classOf[JUnitRunner])
class VirtualScreeningTest extends FunSuite with SharedSparkContext {

  private val tmpDir = new File(Properties.envOrElse("TMPDIR", "/tmp"))

  test("Virtual Screening") {

    sc.hadoopConfiguration.set("textinputformat.record.delimiter", "\n$$$$\n")
    val mols = sc.textFile(getClass.getResource("sdf/molecules.sdf").getPath)

    // Parallel execution with MaRe
    val hitsParallel = new MaRe(mols)
      .map(
        inputMountPoint = TextFile("/input.sdf", "\n$$$$\n"),
        outputMountPoint = TextFile("/output.sdf", "\n$$$$\n"),
        imageName = "mcapuccini/oe:latest",
        command = "fred -receptor /var/openeye/hiv1_protease.oeb " +
          "-hitlist_size 0 " +
          "-conftest none " +
          "-dock_resolution Low " +
          "-dbase /input.sdf " +
          "-docked_molecule_file /output.sdf")
      .reduce(
        inputMountPoint = TextFile("/input.sdf", "\n$$$$\n"),
        outputMountPoint = TextFile("/output.sdf", "\n$$$$\n"),
        imageName = "mcapuccini/sdsorter:latest",
        command = "sdsorter -reversesort='FRED Chemgauss4 score' " +
          "-keep-tag='FRED Chemgauss4 score' " +
          "-nbest=30 " +
          "/input.sdf " +
          "/output.sdf")
      .rdd.collect.mkString("\n$$$$\n")

    // Serial execution
    val inputFile = new File(getClass.getResource("sdf/molecules.sdf").getPath)
    val dockedFile = new File(tmpDir, "mare_test_" + UUID.randomUUID.toString)
    dockedFile.createNewFile
    dockedFile.deleteOnExit
    val outputFile = new File(tmpDir, "mare_test_" + UUID.randomUUID.toString)
    outputFile.createNewFile
    outputFile.deleteOnExit
    DockerHelper.run(
      imageName = "mcapuccini/oe:latest",
      command = "fred -receptor /var/openeye/hiv1_protease.oeb " +
        "-hitlist_size 0 " +
        "-conftest none " +
        "-dock_resolution Low " +
        "-dbase /input.sdf " +
        "-docked_molecule_file /docked.sdf",
      bindFiles = Seq(inputFile, dockedFile),
      volumeFiles = Seq(new File("/input.sdf"), new File("/docked.sdf")),
      forcePull = false)
    DockerHelper.run(
      imageName = "mcapuccini/sdsorter:latest",
      command = "sdsorter -reversesort='FRED Chemgauss4 score' " +
        "-keep-tag='FRED Chemgauss4 score' " +
        "-nbest=30 " +
        "/docked.sdf " +
        "/output.sdf",
      bindFiles = Seq(dockedFile, outputFile),
      volumeFiles = Seq(new File("/docked.sdf"), new File("/output.sdf")),
      forcePull = false)
    val hitsSerial = Source.fromFile(outputFile).mkString

    // Test
    val parallel = SDFUtils.parseIDsAndScores(hitsParallel)
    val serial = SDFUtils.parseIDsAndScores(hitsSerial)
    assert(parallel.deep == serial.deep)

  }

} 
Example 152
Source File: ReadsKey.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.ops.v4

import java.util.UUID

import play.api.libs.json.{JsError, JsResult, JsSuccess}

trait ReadsKey[A] { self =>

  
  private[ops] abstract class AlwaysReadsKey[A] extends ReadsKey[A] {
    def readSafe(key: String): A
    final override def read(key: String): JsResult[A] = JsSuccess(readSafe(key))
  }

  implicit val readKeyString: ReadsKey[String] = new AlwaysReadsKey[String] {
    final override def readSafe(key: String): String = key
  }

  implicit val readKeySymbol: ReadsKey[Symbol] = new AlwaysReadsKey[Symbol] {
    final override def readSafe(key: String): Symbol = Symbol(key)
  }

  implicit val readKeyUUID: ReadsKey[UUID] = new ReadsKey[UUID] {
    final override def read(key: String): JsResult[UUID] = {
      if (key.length == 36) {
        try JsSuccess(UUID.fromString(key)) catch {
          case _: IllegalArgumentException => JsError("Invalid UUID format")
        }
      } else JsError("Invalid UUID length")
    }
  }

  implicit val readKeyByte: ReadsKey[Byte] = readsKeyNumber(java.lang.Byte.parseByte)
  implicit val readKeyShort: ReadsKey[Short] = readsKeyNumber(java.lang.Short.parseShort)
  implicit val readKeyInt: ReadsKey[Int] = readsKeyNumber(java.lang.Integer.parseInt)
  implicit val readKeyLong: ReadsKey[Long] = readsKeyNumber(java.lang.Long.parseLong)
} 
Example 153
Source File: ReadsKey.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.ops.v4

import java.util.UUID

import play.api.libs.json.{JsError, JsResult, JsSuccess}

trait ReadsKey[A] { self =>

  
  private[ops] abstract class AlwaysReadsKey[A] extends ReadsKey[A] {
    def readSafe(key: String): A
    final override def read(key: String): JsResult[A] = JsSuccess(readSafe(key))
  }

  implicit val readKeyString: ReadsKey[String] = new AlwaysReadsKey[String] {
    final override def readSafe(key: String): String = key
  }

  implicit val readKeySymbol: ReadsKey[Symbol] = new AlwaysReadsKey[Symbol] {
    final override def readSafe(key: String): Symbol = Symbol(key)
  }

  implicit val readKeyUUID: ReadsKey[UUID] = new ReadsKey[UUID] {
    final override def read(key: String): JsResult[UUID] = {
      if (key.length == 36) {
        try JsSuccess(UUID.fromString(key)) catch {
          case _: IllegalArgumentException => JsError("Invalid UUID format")
        }
      } else JsError("Invalid UUID length")
    }
  }

  implicit val readKeyByte: ReadsKey[Byte] = readsKeyNumber(java.lang.Byte.parseByte)
  implicit val readKeyShort: ReadsKey[Short] = readsKeyNumber(java.lang.Short.parseShort)
  implicit val readKeyInt: ReadsKey[Int] = readsKeyNumber(java.lang.Integer.parseInt)
  implicit val readKeyLong: ReadsKey[Long] = readsKeyNumber(java.lang.Long.parseLong)
} 
Example 154
Source File: SessionActor.scala    From reactive-consul   with MIT License 5 votes vote down vote up
package stormlantern.consul.client.session

import java.util.UUID

import akka.actor.{ ActorRef, Props, Actor }
import stormlantern.consul.client.dao.ConsulHttpClient
import stormlantern.consul.client.session.SessionActor.{ MonitorSession, SessionAcquired, StartSession }

import scala.concurrent.Future

class SessionActor(httpClient: ConsulHttpClient, listener: ActorRef) extends Actor {

  import scala.concurrent.ExecutionContext.Implicits.global

  // Actor state
  var sessionId: Option[UUID] = None

  def receive = {
    case StartSession ⇒ startSession().map { id ⇒
      self ! SessionAcquired(id)
    }
    case SessionAcquired(id) ⇒
      sessionId = Some(id)
      listener ! SessionAcquired(id)
      self ! MonitorSession(0)
    case MonitorSession(lastIndex) ⇒

  }

  // Internal methods
  def startSession(): Future[UUID] = {
    httpClient.putSession().map { id ⇒
      sessionId = Some(id)
      id
    }
  }
}

object SessionActor {
  // Constructors
  def props(httpClient: ConsulHttpClient, listener: ActorRef) = Props(new SessionActor(httpClient, listener))
  // Public messages
  case object StartSession
  case class SessionAcquired(sessionId: UUID)
  // Private messages
  private case class MonitorSession(lastIndex: Long)
} 
Example 155
Source File: SessionInfo.scala    From reactive-consul   with MIT License 5 votes vote down vote up
package stormlantern.consul.client.dao

import java.util.UUID

case class SessionInfo(
  lockDelay: Long,
  checks: Set[String],
  node: String,
  id: UUID,
  createIndex: Long,
  name: Option[String],
  behavior: String,
  TTL: String
) 
Example 156
Source File: ConsulHttpClient.scala    From reactive-consul   with MIT License 5 votes vote down vote up
package stormlantern.consul.client.dao

import java.util.UUID

import scala.concurrent.Future

trait ConsulHttpClient {
  def getService(
    service: String,
    tag: Option[String] = None,
    index: Option[Long] = None,
    wait: Option[String] = None,
    dataCenter: Option[String] = None
  ): Future[IndexedServiceInstances]
  def putService(registration: ServiceRegistration): Future[String]
  def deleteService(serviceId: String): Future[Unit]
  def putSession(
    sessionCreation: Option[SessionCreation] = None,
    dataCenter: Option[String] = None
  ): Future[UUID]
  def getSessionInfo(sessionId: UUID, index: Option[Long] = None, dataCenter: Option[String] = None): Future[Option[SessionInfo]]
  def putKeyValuePair(key: String, value: Array[Byte], sessionOp: Option[SessionOp] = None): Future[Boolean]
  def getKeyValuePair(
    key: String,
    index: Option[Long] = None,
    wait: Option[String] = None,
    recurse: Boolean = false,
    keysOnly: Boolean = false
  ): Future[Seq[KeyData]]
} 
Example 157
Source File: ConsulHttpProtocol.scala    From reactive-consul   with MIT License 5 votes vote down vote up
package stormlantern.consul.client.dao

import java.util.UUID

import spray.json._

import scala.util.control.NonFatal
import java.util.Base64

trait ConsulHttpProtocol extends DefaultJsonProtocol {

  implicit val uuidFormat = new JsonFormat[UUID] {
    override def read(json: JsValue): UUID = json match {
      case JsString(uuid) ⇒ try {
        UUID.fromString(uuid)
      } catch {
        case NonFatal(e) ⇒ deserializationError("Expected UUID, but got " + uuid)
      }
      case x ⇒ deserializationError("Expected UUID as JsString, but got " + x)
    }

    override def write(obj: UUID): JsValue = JsString(obj.toString)
  }

  implicit val binaryDataFormat = new JsonFormat[BinaryData] {
    override def read(json: JsValue): BinaryData = json match {
      case JsString(data) ⇒ try {
        BinaryData(Base64.getMimeDecoder.decode(data))
      } catch {
        case NonFatal(e) ⇒ deserializationError("Expected base64 encoded binary data, but got " + data)
      }
      case x ⇒ deserializationError("Expected base64 encoded binary data as JsString, but got " + x)
    }

    override def write(obj: BinaryData): JsValue = JsString(Base64.getMimeEncoder.encodeToString(obj.data))
  }

  implicit val serviceFormat = jsonFormat(
    (node: String, address: String, serviceId: String, serviceName: String, serviceTags: Option[Set[String]], serviceAddress: String, servicePort: Int) ⇒
      ServiceInstance(node, address, serviceId, serviceName, serviceTags.getOrElse(Set.empty), serviceAddress, servicePort),
    "Node", "Address", "ServiceID", "ServiceName", "ServiceTags", "ServiceAddress", "ServicePort"
  )
  implicit val httpCheckFormat = jsonFormat(HttpHealthCheck, "HTTP", "Interval")
  implicit val scriptCheckFormat = jsonFormat(ScriptHealthCheck, "Script", "Interval")
  implicit val ttlCheckFormat = jsonFormat(TTLHealthCheck, "TTL")
  implicit val checkWriter = lift {
    new JsonWriter[HealthCheck] {
      override def write(obj: HealthCheck): JsValue = obj match {
        case obj: ScriptHealthCheck ⇒ obj.toJson
        case obj: HttpHealthCheck   ⇒ obj.toJson
        case obj: TTLHealthCheck    ⇒ obj.toJson
      }
    }
  }
  implicit val serviceRegistrationFormat = jsonFormat(ServiceRegistration, "Name", "ID", "Tags", "Address", "Port", "Check")
  implicit val sessionCreationFormat = jsonFormat(SessionCreation, "LockDelay", "Name", "Node", "Checks", "Behavior", "TTL")
  implicit val keyDataFormat = jsonFormat(KeyData, "Key", "CreateIndex", "ModifyIndex", "LockIndex", "Flags", "Value", "Session")
  implicit val sessionInfoFormat = jsonFormat(SessionInfo, "LockDelay", "Checks", "Node", "ID", "CreateIndex", "Name", "Behavior", "TTL")
} 
Example 158
Source File: LeaderFollowerActor.scala    From reactive-consul   with MIT License 5 votes vote down vote up
package stormlantern.consul.client.election

import java.util.UUID

import akka.actor.{ Actor, Props }
import spray.json._
import stormlantern.consul.client.dao.{ AcquireSession, BinaryData, ConsulHttpClient, KeyData }
import stormlantern.consul.client.election.LeaderFollowerActor._

class LeaderFollowerActor(httpClient: ConsulHttpClient, sessionId: UUID, key: String, host: String, port: Int) extends Actor with DefaultJsonProtocol {

  implicit val ec = context.dispatcher

  implicit val leaderInfoFormat = jsonFormat2(LeaderInfo)
  val leaderInfoBytes = LeaderInfo(host, port).toJson.compactPrint.getBytes("UTF-8")

  // Actor state
  var electionState: Option[ElectionState] = None

  // Behavior
  def receive = {
    case Participate ⇒
      httpClient.putKeyValuePair(key, leaderInfoBytes, Some(AcquireSession(sessionId))).map {
        case true ⇒
          self ! SetElectionState(Some(Leader))
          self ! MonitorLock(0)
        case false ⇒
          self ! MonitorLock(0)
      }
    case SetElectionState(state) ⇒
      electionState = state
    case MonitorLock(index) ⇒
      httpClient.getKeyValuePair(key, index = Some(index), wait = Some("1s")).map {
        case Seq(KeyData(_, _, newIndex, _, _, BinaryData(data), session)) ⇒
          if (newIndex > index) {
            if (session.isEmpty) {
              self ! SetElectionState(None)
              self ! Participate
            } else if (session.get == sessionId) {
              self ! SetElectionState(Some(Leader))
              self ! MonitorLock(newIndex)
            } else {
              val leaderInfo = new String(data, "UTF-8").parseJson.convertTo[LeaderInfo](leaderInfoFormat)
              self ! SetElectionState(Some(Follower(leaderInfo.host, leaderInfo.port)))
              self ! MonitorLock(newIndex)
            }
          } else {
            self ! MonitorLock(index)
          }
      }
  }
}

object LeaderFollowerActor {

  //Props
  def props(httpClient: ConsulHttpClient, sessionId: UUID, key: String, host: String, port: Int): Props =
    Props(new LeaderFollowerActor(httpClient, sessionId, key, host, port))

  // Election state
  sealed trait ElectionState
  case object Leader extends ElectionState
  case class Follower(host: String, port: Int) extends ElectionState

  // Internal messages
  case object Participate
  case class SetElectionState(state: Option[ElectionState])
  case class MonitorLock(lastIndex: Long)
} 
Example 159
Source File: LeaderFollowerActorSpec.scala    From reactive-consul   with MIT License 5 votes vote down vote up
package stormlantern.consul.client.election

import java.util
import java.util.UUID

import akka.actor.ActorSystem
import akka.testkit.{ TestActorRef, ImplicitSender, TestKit }
import org.scalamock.scalatest.MockFactory
import org.scalatest.{ BeforeAndAfterAll, Matchers, FlatSpecLike }
import stormlantern.consul.client.dao.{ BinaryData, KeyData, AcquireSession, ConsulHttpClient }
import stormlantern.consul.client.election.LeaderFollowerActor.Participate

import scala.concurrent.Future

class LeaderFollowerActorSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender with FlatSpecLike
    with Matchers with BeforeAndAfterAll with MockFactory {

  def this() = this(ActorSystem("LeaderFollowerActorSpec"))

  override def afterAll() {
    TestKit.shutdownActorSystem(system)
  }

  trait TestScope {
    val sessionId: UUID = UUID.fromString("9A3BB9C-E2E7-43DF-BFD5-845417146552")
    val key = "path/to/our/key"
    val host = "myhost.mynetwork.net"
    val port = 1337
    val consulHttpClient: ConsulHttpClient = mock[ConsulHttpClient]
    val leaderInfoBytes: Array[Byte] = s"""{"host":"$host","port":$port}""".getBytes("UTF-8")
  }

  "The LeaderFollowerActor" should "participate in an election, win, watch for changes and participate again when session is lost" in new TestScope {
    val sut = TestActorRef(LeaderFollowerActor.props(consulHttpClient, sessionId, key, host, port))
    (consulHttpClient.putKeyValuePair _).expects(where { (k, lib, op) ⇒
      k == key && util.Arrays.equals(lib, leaderInfoBytes) && op.contains(AcquireSession(sessionId))
    }).returns(Future.successful(true))
    (consulHttpClient.getKeyValuePair _).expects(key, Some(0L), Some("1s"), false, false).returns {
      Future.successful(Seq(KeyData(key, 1, 1, 1, 0, BinaryData(leaderInfoBytes), Some(sessionId))))
    }
    (consulHttpClient.getKeyValuePair _).expects(key, Some(1L), Some("1s"), false, false).returns {
      Future.successful(Seq(KeyData(key, 1, 2, 1, 0, BinaryData(leaderInfoBytes), None)))
    }
    (consulHttpClient.putKeyValuePair _).expects(where { (k, lib, op) ⇒
      k == key && util.Arrays.equals(lib, leaderInfoBytes) && op.contains(AcquireSession(sessionId))
    }).onCall { p ⇒
      sut.stop()
      Future.successful(false)
    }
    sut ! Participate
  }

  it should "participate in an election, lose, watch for changes and participate again when session is lost" in new TestScope {
    val otherSessionId: UUID = UUID.fromString("9A3BB9C-E2E7-43DF-BFD5-845417146553")
    val sut = TestActorRef(LeaderFollowerActor.props(consulHttpClient, sessionId, key, host, port))
    (consulHttpClient.putKeyValuePair _).expects(where { (k, lib, op) ⇒
      k == key && util.Arrays.equals(lib, leaderInfoBytes) && op.contains(AcquireSession(sessionId))
    }).returns(Future.successful(false))
    (consulHttpClient.getKeyValuePair _).expects(key, Some(0L), Some("1s"), false, false).returns {
      Future.successful(Seq(KeyData(key, 1, 1, 1, 0, BinaryData(leaderInfoBytes), Some(otherSessionId))))
    }
    (consulHttpClient.getKeyValuePair _).expects(key, Some(1L), Some("1s"), false, false).returns {
      Future.successful(Seq(KeyData(key, 1, 2, 1, 0, BinaryData(leaderInfoBytes), None)))
    }
    (consulHttpClient.putKeyValuePair _).expects(where { (k, lib, op) ⇒
      k == key && util.Arrays.equals(lib, leaderInfoBytes) && op.contains(AcquireSession(sessionId))
    }).onCall { p ⇒
      sut.stop()
      Future.successful(true)
    }
    sut ! Participate
  }
} 
Example 160
Source File: package.scala    From gatling-amqp-plugin   with Apache License 2.0 5 votes vote down vote up
package ru.tinkoff.gatling.amqp

import java.util.UUID

import com.eatthepath.uuid.FastUUID
import ru.tinkoff.gatling.amqp.request.AmqpProtocolMessage

package object protocol {
  trait AmqpMessageMatcher {
    def prepareRequest(msg: AmqpProtocolMessage): Unit
    def requestMatchId(msg: AmqpProtocolMessage): String
    def responseMatchId(msg: AmqpProtocolMessage): String
  }

  object MessageIdMessageMatcher extends AmqpMessageMatcher {
    override def prepareRequest(msg: AmqpProtocolMessage): Unit    = {}
    override def requestMatchId(msg: AmqpProtocolMessage): String  = msg.messageId
    override def responseMatchId(msg: AmqpProtocolMessage): String = msg.messageId
  }

  object CorrelationIdMessageMatcher extends AmqpMessageMatcher {
    override def prepareRequest(msg: AmqpProtocolMessage): Unit    = msg.correlationId(FastUUID.toString(UUID.randomUUID))
    override def requestMatchId(msg: AmqpProtocolMessage): String  = msg.correlationId
    override def responseMatchId(msg: AmqpProtocolMessage): String = msg.correlationId
  }

  case class AmqpProtocolMessageMatcher(extractId: AmqpProtocolMessage => String) extends AmqpMessageMatcher {
    override def prepareRequest(msg: AmqpProtocolMessage): Unit = {}

    override def requestMatchId(msg: AmqpProtocolMessage): String = extractId(msg)

    override def responseMatchId(msg: AmqpProtocolMessage): String = extractId(msg)
  }

  case object RabbitMQConnectionFactoryBuilderBase {
    def host(host: String): RabbitMQConnectionFactoryBuilder = RabbitMQConnectionFactoryBuilder(host = Some(host))

    
    def default: RabbitMQConnectionFactoryBuilder = RabbitMQConnectionFactoryBuilder()
  }
} 
Example 161
Source File: DeviceService.scala    From ledger-manager-chrome   with MIT License 5 votes vote down vote up
package co.ledger.manager.web.services

import java.util.UUID

import biz.enef.angulate.Module.RichModule
import biz.enef.angulate.Service
import biz.enef.angulate.core.Location
import co.ledger.wallet.core.device.Device.{Connect, Disconnect}
import co.ledger.wallet.core.device.DeviceManager.ConnectivityTypes.ConnectivityType
import co.ledger.wallet.core.device.utils.EventReceiver
import co.ledger.wallet.core.device.{Device, DeviceFactory, DeviceManager}
import co.ledger.wallet.core.utils.Preferences
import co.ledger.manager.web.core.device.usb.UsbDeviceFactory
import co.ledger.manager.web.core.utils.{ChromeGlobalPreferences, ChromePreferences}

import scala.concurrent.{ExecutionContext, Future, duration}
import scala.scalajs.js
import scala.scalajs.js.timers._



class DeviceService(val windowService: WindowService, $location: Location,  $route: js.Dynamic, sessionService: SessionService) extends Service with DeviceManager[Any] {
  import co.ledger.wallet.core.device.DeviceManager.ConnectivityTypes._

  override implicit val ec: ExecutionContext = scala.concurrent.ExecutionContext.Implicits.global

  override protected def delayedFunctionHandler: DelayedFunctionHandler = (delay: Long, f: () => Unit) => {
    import duration._
    setTimeout(delay.milliseconds)(f())
  }

  override protected def preferences: Preferences = _preferences

  override def context: Any = this

  override def registerDevice(device: Device): Future[UUID] = {
    device.eventBus.register(_eventReceiver)
    super.registerDevice(device)
  }

  override def unregisterDevice(device: Device): Unit = {
    device.eventBus.unregister(_eventReceiver)
    super.unregisterDevice(device)
  }

  override protected val _deviceManager: Map[ConnectivityType, DeviceFactory] = Map(
    Usb -> new UsbDeviceFactory
  )

  private val _preferences = new ChromeGlobalPreferences("DeviceService")

  private val _eventReceiver = new EventReceiver {
    override def receive: Receive = {
      case Connect(_) =>
      case Disconnect(_) =>
        sessionService.stopCurrentSessions()
        windowService.dismissSnackbar()
        $location.path("/launch/")
        $route.reload()
    }
  }
}

object DeviceService {

  def init(module: RichModule) = {
    module.serviceOf[DeviceService]("deviceService")
  }

} 
Example 162
Source File: LedgerApi.scala    From ledger-manager-chrome   with MIT License 5 votes vote down vote up
package co.ledger.wallet.core.device.ethereum

import java.util.UUID

import co.ledger.wallet.core.device.Device
import co.ledger.wallet.core.device.DeviceManager.ConnectivityTypes
import co.ledger.wallet.core.utils.{DerivationPath, HexUtils}
import co.ledger.wallet.core.utils.DerivationPath.Root

import scala.concurrent.{ExecutionContext, Future}


class LedgerApi(override val device: Device)
  extends LedgerCommonApiInterface
  with LedgerBolosApi {
  override implicit val ec: ExecutionContext = scala.concurrent.ExecutionContext.Implicits.global

  val uuid = UUID.randomUUID()
  device.uuid = uuid
}

object LedgerApi {

  def apply(device: Device): LedgerApi = {
    val lastApi = _lastApi.filter(device.uuid == _.device.uuid)
    lastApi.getOrElse {
      val api = device.connectivityType match {
        case others => new LedgerApi(device)
      }
      _lastApi = Some(api)
      api
    }
  }

  def apply(uuid: UUID): Option[LedgerApi] = _lastApi filter(_.uuid == uuid)

  private var _lastApi: Option[LedgerApi] = None
} 
Example 163
Source File: SpecificPrimitivesSpec.scala    From sbt-avrohugger   with Apache License 2.0 5 votes vote down vote up
import test._
import org.specs2.mutable.Specification
import java.sql.{Date, Timestamp}
import java.util.UUID
class SpecificPrimitivesSpec extends Specification {

  "A case class with an `Int` field" should {
    "deserialize correctly" in {
      val record1 = AvroTypeProviderTest00(1)
      val record2 = AvroTypeProviderTest00(2)
      val records = List(record1, record2)
      SpecificTestUtil.verifyWriteAndRead(records)
    }
  }

  "A case class with an `Float` field" should {
    "deserialize correctly" in {
      val record1 = AvroTypeProviderTest01(1F)
      val record2 = AvroTypeProviderTest01(2F)
      val records = List(record1, record2)
      SpecificTestUtil.verifyWriteAndRead(records)
    }
  }

  "A case class with an `Long` field" should {
    "deserialize correctly" in {
      val record1 = AvroTypeProviderTest02(1L)
      val record2 = AvroTypeProviderTest02(2L)
      val records = List(record1, record2)
      SpecificTestUtil.verifyWriteAndRead(records)
    }
  }

  "A case class with an `Double` field" should {
    "deserialize correctly" in {
      val record1 = AvroTypeProviderTest03(1D)
      val record2 = AvroTypeProviderTest03(2D)
      val records = List(record1, record2)
      SpecificTestUtil.verifyWriteAndRead(records)
    }
  }

  "A case class with an `Boolean` field" should {
    "deserialize correctly" in {
      val record1 = AvroTypeProviderTest04(true)
      val record2 = AvroTypeProviderTest04(false)
      val records = List(record1, record2)
      SpecificTestUtil.verifyWriteAndRead(records)
    }
  }

  "A case class with an `String` field" should {
    "deserialize correctly" in {
      val record1 = AvroTypeProviderTest05("hello world")
      val record2 = AvroTypeProviderTest05("hello galaxy")
      val records = List(record1, record2)
      SpecificTestUtil.verifyWriteAndRead(records)
    }
  }

  "A case class with an `Null` field" should {
    "deserialize correctly" in {
      val record1 = AvroTypeProviderTest06(null)
      val record2 = AvroTypeProviderTest06(null)
      val records = List(record1, record2)
      SpecificTestUtil.verifyWriteAndRead(records)
    }
  }

  "A case class with an `Array[Bytes]` field" should {
    "deserialize correctly" in {
      val record1 = AvroTypeProviderTest69("hello world".getBytes)
      val record2 = AvroTypeProviderTest69("hello galaxy".getBytes)
      val records = List(record1, record2)
      SpecificTestUtil.verifyWriteAndRead(records)
    }
  }

  "A case class with a `logicalType` fields from .avsc" should {
    "deserialize correctly" in {
      val t1 = System.currentTimeMillis()
      val t2 = System.currentTimeMillis()
      val record1 = LogicalSc(BigDecimal(10.0).setScale(8), new Timestamp(Long.MaxValue), new Date(t1), UUID.randomUUID())
      val record2 = LogicalSc(BigDecimal(10.0).setScale(8), new Timestamp(Long.MaxValue), new Date(t2), UUID.randomUUID())
      val records = List(record1, record2)
      SpecificTestUtil.verifyWriteAndRead(records)
    }
  }

} 
Example 164
Source File: SampleFramework.scala    From mesos-actor   with Apache License 2.0 5 votes vote down vote up
package com.adobe.api.platform.runtime.mesos.sample

import akka.actor.ActorSystem
import akka.pattern.ask
import akka.stream.ActorMaterializer
import akka.util.Timeout
import com.adobe.api.platform.runtime.mesos._
import java.time.Instant
import java.util.UUID

import scala.concurrent.Await
import scala.concurrent.Future
import scala.concurrent.duration._


object SampleFramework {

  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem("sample-framework-system")
    implicit val mat = ActorMaterializer()
    implicit val log = system.log
    implicit val ec = system.dispatcher

    val taskLaunchTimeout = Timeout(15 seconds)
    val taskDeleteTimeout = Timeout(10 seconds)
    val subscribeTimeout = Timeout(5 seconds)
    val teardownTimeout = Timeout(5 seconds)

    val mesosClientActor = system.actorOf(
      MesosClient.props(
        () => "sample-" + UUID.randomUUID(),
        "sample-framework",
        "http://192.168.99.100:5050",
        "*",
        30.seconds,
        taskStore = new LocalTaskStore))

    mesosClientActor
      .ask(Subscribe)(subscribeTimeout)
      .mapTo[SubscribeComplete]
      .onComplete(complete => {
        log.info("subscribe completed successfully...")
      })

    var taskCount = 0
    def nextName() = {
      taskCount += 1
      s"sample-task-${Instant.now.getEpochSecond}-${taskCount}"
    }
    def nextId() = "sample-task-" + UUID.randomUUID()

    (1 to 3).foreach(_ => {
      val task = TaskDef(
        nextId(),
        nextName(),
        "trinitronx/python-simplehttpserver",
        0.1,
        24,
        List(8080, 8081),
        Some(HealthCheckConfig(0)),
        commandDef = Some(CommandDef()))
      val launched: Future[TaskState] = mesosClientActor.ask(SubmitTask(task))(taskLaunchTimeout).mapTo[TaskState]
      launched map {
        case taskDetails: Running => {
          val taskHost = taskDetails.hostname
          val taskPorts = taskDetails.hostports
          log.info(
            s"launched task id ${taskDetails.taskId} with state ${taskDetails.taskStatus.getState} on agent ${taskHost} listening on ports ${taskPorts}")

          //schedule delete in 10 seconds
          system.scheduler.scheduleOnce(10.seconds) {
            log.info(s"removing previously created task ${taskDetails.taskId}")
            mesosClientActor
              .ask(DeleteTask(taskDetails.taskId))(taskDeleteTimeout)
              .mapTo[Deleted]
              .map(deleted => {
                log.info(s"task killed ended with state ${deleted.taskStatus.getState}")
              })
          }
        }
        case s => log.error(s"failed to launch task; state is ${s}")
      } recover {
        case t => log.error(s"task launch failed ${t.getMessage}", t)
      }
    })

    system.scheduler.scheduleOnce(30.seconds) {
      val complete: Future[Any] = mesosClientActor.ask(Teardown)(teardownTimeout)
      Await.result(complete, 10.seconds)
      println("teardown completed!")
      system.terminate().map(_ => System.exit(0))
    }

  }

} 
Example 165
Source File: Transformer.scala    From mleap   with Apache License 2.0 5 votes vote down vote up
package ml.combust.mleap.runtime.frame

import java.util.UUID

import ml.combust.mleap.core.Model
import ml.combust.mleap.core.types.{NodeShape, StructField, StructType}
import ml.combust.mleap.runtime.function.{FieldSelector, Selector, UserDefinedFunction}

import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Failure, Success, Try}

 }
}

trait BaseTransformer extends Transformer {
  val exec: UserDefinedFunction

  val inputs: Seq[String] = inputSchema.fields.map(_.name)
  val selectors: Seq[Selector] = inputs.map(FieldSelector)
}

trait SimpleTransformer extends BaseTransformer {
  val output: String = outputSchema.fields.head.name

  lazy val typedExec: UserDefinedFunction = exec.withInputs(inputSchema).withOutput(outputSchema)
  override def transform[FB <: FrameBuilder[FB]](builder: FB): Try[FB] = {
    builder.withColumn(output, selectors: _*)(typedExec)
  }
}

trait MultiTransformer extends BaseTransformer {
  val outputs: Seq[String] = outputSchema.fields.map(_.name)

  lazy val typedExec: UserDefinedFunction = exec.withInputs(inputSchema).withOutput(outputSchema)
  override def transform[FB <: FrameBuilder[FB]](builder: FB): Try[FB] = {
    builder.withColumns(outputs, selectors: _*)(typedExec)
  }
} 
Example 166
Source File: SparkTransformBuilderSpec.scala    From mleap   with Apache License 2.0 5 votes vote down vote up
package ml.combust.mleap.spark

import java.util.UUID

import org.apache.spark.sql.{Row, SparkSession}
import org.apache.spark.sql.types.{DoubleType, StructType}
import SparkSupport._
import ml.combust.mleap.core.{Model, types}
import ml.combust.mleap.core.types.{NodeShape, ScalarType, StructField}
import ml.combust.mleap.runtime.frame.{FrameBuilder, Transformer}
import org.scalatest.FunSpec

import scala.collection.JavaConverters._
import scala.util.Try


case class MyTransformer() extends Transformer {
  override val uid: String = UUID.randomUUID().toString

  override def transform[TB <: FrameBuilder[TB]](builder: TB): Try[TB] = {
    builder.withColumns(Seq("output1", "output2"), "input") {
      (input: Double) => (input + 23, input.toString)
    }
  }

  override val shape: NodeShape = NodeShape().withStandardInput("input").
    withOutput("output1", "output1").withOutput("output2", "output2")

  override val model: Model = new Model {
    override def inputSchema: types.StructType = types.StructType("input" -> ScalarType.Double).get

    override def outputSchema: types.StructType = types.StructType("output1" -> ScalarType.Double,
      "output2" -> ScalarType.String).get
  }
}

class SparkTransformBuilderSpec extends FunSpec {
  describe("transformer with multiple outputs") {
    it("works with Spark as well") {
      val spark = SparkSession.builder().
        appName("Spark/MLeap Parity Tests").
        master("local[2]").
        getOrCreate()
      val schema = new StructType().
        add("input", DoubleType)
      val data = Seq(Row(45.7d)).asJava
      val dataset = spark.createDataFrame(data, schema)
      val transformer = MyTransformer()
      val outputDataset = transformer.sparkTransform(dataset).collect()

      assert(outputDataset.head.getDouble(1) == 68.7)
      assert(outputDataset.head.getString(2) == "45.7")
    }
  }

  describe("input/output schema") {
    it("has the correct inputs and outputs") {
      val transformer = MyTransformer()
      assert(transformer.schema.fields ==
        Seq(StructField("input", types.ScalarType.Double),
          StructField("output1", types.ScalarType.Double),
          StructField("output2", types.ScalarType.String)))
    }
  }
} 
Example 167
Source File: DeriveGenSpec.scala    From zio   with Apache License 2.0 5 votes vote down vote up
package zio.test.magnolia

import java.util.UUID

import zio.random.Random
import zio.test.Assertion._
import zio.test.GenUtils._
import zio.test.Sized
import zio.test._
import zio.test.magnolia.DeriveGen._

object DeriveGenSpec extends DefaultRunnableSpec {

  final case class Person(name: String, age: Int)

  val genPerson: Gen[Random with Sized, Person] = DeriveGen[Person]

  sealed trait Color

  object Color {
    case object Red   extends Color
    case object Green extends Color
    case object Blue  extends Color
  }

  val genColor: Gen[Random with Sized, Color] = DeriveGen[Color]

  sealed trait NonEmptyList[+A] { self =>
    def foldLeft[S](s: S)(f: (S, A) => S): S =
      self match {
        case NonEmptyList.Cons(h, t) => t.foldLeft(f(s, h))(f)
        case NonEmptyList.Single(h)  => f(s, h)
      }
    def length: Int =
      foldLeft(0)((s, _) => s + 1)
  }

  object NonEmptyList {
    final case class Cons[+A](head: A, tail: NonEmptyList[A]) extends NonEmptyList[A]
    final case class Single[+A](value: A)                     extends NonEmptyList[A]
  }

  def genNonEmptyList[A](implicit ev: DeriveGen[A]): Gen[Random with Sized, NonEmptyList[A]] =
    DeriveGen[NonEmptyList[A]]

  def assertDeriveGen[A: DeriveGen]: TestResult = assertCompletes

  def spec = suite("DeriveGenSpec")(
    suite("derivation")(
      testM("case classes can be derived") {
        checkSample(genPerson)(isGreaterThan(1), _.distinct.length)
      },
      testM("sealed traits can be derived") {
        checkSample(genColor)(equalTo(3), _.distinct.length)
      },
      testM("recursive types can be derived") {
        check(genNonEmptyList[Int])(as => assert(as.length)(isGreaterThan(0)))
      }
    ),
    suite("instances")(
      test("boolean")(assertDeriveGen[Boolean]),
      test("byte")(assertDeriveGen[Byte]),
      test("char")(assertDeriveGen[Char]),
      test("double")(assertDeriveGen[Double]),
      test("float")(assertDeriveGen[Float]),
      test("function")(assertDeriveGen[Int => Int]),
      test("int")(assertDeriveGen[Int]),
      test("iterable")(assertDeriveGen[Iterable[Int]]),
      test("list")(assertDeriveGen[List[Int]]),
      test("long")(assertDeriveGen[Long]),
      test("map")(assertDeriveGen[Map[Int, Int]]),
      test("option")(assertDeriveGen[Option[Int]]),
      test("partialFunction")(assertDeriveGen[PartialFunction[Int, Int]]),
      test("seq")(assertDeriveGen[Seq[Int]]),
      test("set")(assertDeriveGen[Set[Int]]),
      test("short")(assertDeriveGen[Short]),
      test("string")(assertDeriveGen[String]),
      test("tuple2")(assertDeriveGen[(Int, Int)]),
      test("tuple3")(assertDeriveGen[(Int, Int, Int)]),
      test("tuple4")(assertDeriveGen[(Int, Int, Int, Int)]),
      test("unit")(assertDeriveGen[Unit]),
      test("uuid")(assertDeriveGen[UUID]),
      test("vector")(assertDeriveGen[Vector[Int]])
    ),
    suite("shrinking")(
      testM("derived generators shrink to smallest value") {
        checkShrink(genPerson)(Person("", 0))
      }
    )
  )
} 
Example 168
Source File: Serdes.scala    From zio-kafka   with Apache License 2.0 5 votes vote down vote up
package zio.kafka.serde

import java.nio.ByteBuffer
import java.util.UUID

import org.apache.kafka.common.serialization.{ Serdes => KafkaSerdes }

private[zio] trait Serdes {
  lazy val long: Serde[Any, Long]             = Serde(KafkaSerdes.Long()).inmap(Long2long)(long2Long)
  lazy val int: Serde[Any, Int]               = Serde(KafkaSerdes.Integer()).inmap(Integer2int)(int2Integer)
  lazy val short: Serde[Any, Short]           = Serde(KafkaSerdes.Short()).inmap(Short2short)(short2Short)
  lazy val float: Serde[Any, Float]           = Serde(KafkaSerdes.Float()).inmap(Float2float)(float2Float)
  lazy val double: Serde[Any, Double]         = Serde(KafkaSerdes.Double()).inmap(Double2double)(double2Double)
  lazy val string: Serde[Any, String]         = Serde(KafkaSerdes.String())
  lazy val byteArray: Serde[Any, Array[Byte]] = Serde(KafkaSerdes.ByteArray())
  lazy val byteBuffer: Serde[Any, ByteBuffer] = Serde(KafkaSerdes.ByteBuffer())
  lazy val uuid: Serde[Any, UUID]             = Serde(KafkaSerdes.UUID())
} 
Example 169
Source File: ThingsController.scala    From swagger-check   with MIT License 5 votes vote down vote up
package controllers

import java.util.UUID
import javax.inject.Inject

import dal.ThingsRepository
import models.{Link, ThingType, ThingsPage, ThingsPageLinks}
import play.api.libs.json.Json
import play.api.mvc.{AbstractController, ControllerComponents}

import scala.concurrent.ExecutionContext

class ThingsController @Inject()(
    thingRepository: ThingsRepository,
    components: ControllerComponents)(implicit ec: ExecutionContext)
    extends AbstractController(components) {
  def getPage(thingType: Option[ThingType.Type], offset: Int, limit: Int) =
    Action.async { implicit request =>
      thingRepository.getPage(thingType, offset, limit).map { things =>
        val page = ThingsPage(
          things,
          ThingsPageLinks(
            Link.fromCall(
              routes.ThingsController.getPage(thingType, offset, limit)),
            None,
            None))
        Ok(Json.toJson(page))
      }
    }

  def createThing = Action {
    Created
  }

  def getThing(id: UUID) = Action.async { implicit request =>
    thingRepository.getById(id).map {
      case Some(thing) =>
        Ok(Json.toJson(thing))
      case None =>
        NotFound
    }
  }
} 
Example 170
Source File: Arbitraries.scala    From swagger-check   with MIT License 5 votes vote down vote up
package support

import java.util.UUID

import de.leanovate.swaggercheck.generators.Generators
import models._
import org.scalacheck.{Arbitrary, Gen}

trait Arbitraries {
  implicit val arbitraryUUID = Arbitrary[UUID](Gen.uuid)

  implicit val arbitraryThingType = Arbitrary[ThingType.Value](Gen.oneOf(ThingType.Primary, ThingType.Secondary, ThingType.Other))

  implicit val arbitraryThing = Arbitrary[Thing](for {
    id <- Arbitrary.arbitrary[UUID]
    name <- Gen.choose(1, 100).flatMap(Gen.listOfN(_, Gen.alphaNumChar).map(_.mkString))
    thingType <- Arbitrary.arbitrary[ThingType.Value]
  } yield Thing(id, name, thingType))

  implicit val arbitraryLink = Arbitrary[Link](for {
    href <- Generators.url
  } yield Link(href))

  implicit val arbitraryThingPageLinks = Arbitrary[ThingsPageLinks](for {
    self <- Arbitrary.arbitrary[Link]
    first <- Arbitrary.arbitrary[Option[Link]]
    last <- Arbitrary.arbitrary[Option[Link]]
  } yield ThingsPageLinks(self, first, last))

  implicit val arbitraryThingPage = Arbitrary[ThingsPage](for {
    size <- Gen.choose(0, 20)
    things <- Gen.listOfN(size, Arbitrary.arbitrary[Thing])
    _links <- Arbitrary.arbitrary[ThingsPageLinks]
  } yield ThingsPage(things, _links))

  implicit val arbitraryError = Arbitrary[Error](for {
    code <- Gen.choose(100, 599)
    message <- Arbitrary.arbitrary[String]
  } yield Error(code, message))
} 
Example 171
Source File: ThingsControllerSpec.scala    From swagger-check   with MIT License 5 votes vote down vote up
package controllers

import java.util.UUID

import dal.ThingsRepository
import de.leanovate.swaggercheck.playhelper._
import de.leanovate.swaggercheck.schema.model.ValidationSuccess
import models.{Thing, ThingType}
import org.scalacheck.{Arbitrary, Gen}
import org.specs2.ScalaCheck
import org.specs2.mock.Mockito
import play.api.Application
import play.api.inject.bind
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.test._
import support.{Arbitraries, ThingApi}

import scala.concurrent.Future

class ThingsControllerSpec extends PlaySpecification with ScalaCheck with ThingApi with Mockito with Arbitraries{

  "ThingController" should {
    "support all /things routes" in {
      implicit val arbitraryRequest = Arbitrary[PlayOperationVerifier](swaggerCheck.operationVerifier())
      val app = testApp()

      prop { requestVerifier: PlayOperationVerifier =>
        val Some(result) = route(app, requestVerifier.request)

        status(result) must between(200, 300)

        requestVerifier.responseVerifier.verify(result) must be equalTo ValidationSuccess
      }
    }
  }

  def testApp(): Application = {
    val mockThingsRepository = mock[ThingsRepository]

    mockThingsRepository.getPage(any[Option[ThingType.Value]], any[Int], any[Int]) answers { _ => Future.successful(Gen.nonEmptyListOf(Arbitrary.arbitrary[Thing]).sample.getOrElse(Seq.empty)) }
    mockThingsRepository.getById(any[UUID]) answers { _ => Future.successful(Arbitrary.arbitrary[Thing].sample)}

    new GuiceApplicationBuilder()
      .overrides(bind[ThingsRepository].toInstance(mockThingsRepository))
      .build()
  }
} 
Example 172
Source File: AnyThing.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.fixtures.model

import java.net.{URI, URL}
import java.time.temporal.ChronoUnit
import java.time.{Instant, LocalDate}
import java.util.UUID

import de.leanovate.swaggercheck.generators.Generators
import org.scalacheck.{Arbitrary, Gen}
import play.api.libs.json.{Json, OFormat}

import scala.util.Try

case class AnyThing(
                     anUUID: String,
                     anURL: String,
                     anURI: String,
                     anEmail: String,
                     aDate: LocalDate,
                     aDateTime: Instant,
                     anInt32: Int,
                     anInt64: Long,
                     aFloat: Float,
                     aDouble: Double,
                     aBoolean: Boolean,
                     anEnum: String,
                     aMap: Map[String, String]
                   ) {
  def isValid: Boolean = {
    Try {
      UUID.fromString(anUUID)
      new URL(anURL)
      new URI(anURI)
    }.isSuccess && Set("V1", "V2", "V3").contains(anEnum)
  }
}

object AnyThing {
  implicit val jsonFormat: OFormat[AnyThing] = Json.format[AnyThing]

  implicit val arbitrary = Arbitrary(for {
    anUUID <- Gen.uuid.map(_.toString)
    anURL <- Generators.url
    anURI <- Generators.uri
    anEmail <- Generators.email
    aDate <- Arbitrary.arbitrary[Int].map(diff => LocalDate.now().plus(diff, ChronoUnit.DAYS))
    aDateTime <- Arbitrary.arbitrary[Long].map(diff => Instant.now().plus(diff, ChronoUnit.NANOS))
    anInt32 <- Arbitrary.arbitrary[Int]
    anInt64 <- Arbitrary.arbitrary[Long]
    aFloat <- Arbitrary.arbitrary[Float]
    aDouble <- Arbitrary.arbitrary[Double]
    aBoolean <- Arbitrary.arbitrary[Boolean]
    anEnum <- Gen.oneOf("V1", "V2", "V3")
    aMap <- Arbitrary.arbitrary[Map[String, String]]
  } yield AnyThing(anUUID, anURL, anURI, anEmail, aDate, aDateTime, anInt32, anInt64, aFloat, aDouble, aBoolean, anEnum, aMap))
} 
Example 173
Source File: OtherBase.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.fixtures.model

import java.util.UUID

import org.scalacheck.{Arbitrary, Gen}
import play.api.libs.json.Json

case class OtherBase(
                      id: UUID,
                      firstName: Option[String],
                      lastName: String
                      )

object OtherBase {
  implicit val jsonFormat = Json.format[OtherBase]

  implicit val arbitrary = Arbitrary(for {
    id <- Gen.uuid
    firstName <- Arbitrary.arbitrary[Option[String]]
    lastName <- Arbitrary.arbitrary[String]
  } yield OtherBase(id, firstName, lastName))
} 
Example 174
Source File: SubBase.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.fixtures.model

import java.util.UUID

import de.leanovate.swaggercheck.generators.Generators
import org.scalacheck.{Arbitrary, Gen}
import play.api.libs.json.Json

case class SubBase(
                    id: UUID,
                    email: Option[String]
                    )

object SubBase {
  implicit val jsonFormat = Json.format[SubBase]

  implicit val arbitrary = Arbitrary(for {
    id <- Gen.uuid
    email <- Gen.option(Generators.email)
  } yield SubBase(id, email))
} 
Example 175
Source File: Author.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.fixtures.bookdb

import java.util.UUID

import org.scalacheck.{Arbitrary, Gen}
import play.api.libs.json.Json

case class Author(
                   id: Option[UUID],
                   name: String
                 )

object Author {
  implicit val jsonFormat = Json.format[Author]

  implicit val arbitrary = Arbitrary(for {
    id <- Gen.option(Gen.uuid)
    name <- Arbitrary.arbitrary[String]
  } yield Author(id, name))
} 
Example 176
Source File: BookDbApiSpecification.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck

import java.util.UUID

import de.leanovate.swaggercheck.fixtures.bookdb.Author
import de.leanovate.swaggercheck.schema.ValidationResultToProp._
import de.leanovate.swaggercheck.simple._
import org.scalacheck.Prop.{BooleanOperators, forAll}
import org.scalacheck.{Arbitrary, Properties, Shrink}
import play.api.libs.json.Json

object BookDbApiSpecification extends Properties("BookDB API") {
  val swaggerChecks = SwaggerChecks(getClass.getClassLoader.getResourceAsStream("bookdb_api.yaml"))

  property("Author is correctly written") = {
    val verifier = swaggerChecks.jsonVerifier("Author")

    forAll(Arbitrary.arbitrary[Author]) {
      author: Author =>
        val json = Json.stringify(Json.toJson(author))

        verifier.verify(json)
    }
  }

  property("Author can be correctly parsed") = {
    val verifier = swaggerChecks.jsonVerifier("Author")

    forAll(swaggerChecks.jsonGenerator("Author")) {
      json =>
        Json.parse(json.minified).validate[Author].isSuccess :| "Json can be deserialized" &&
          verifier.verify(json.minified).isSuccess :| "Json conforms to own schema" &&
          Shrink.shrink(json).forall {
            shrinked =>
              verifier.verify(shrinked.minified).isSuccess
          } :| "All shrinked variants conform to schema"
    }
  }

  property("Request generator POST /author") = {
    val verifier = swaggerChecks.jsonVerifier("Author")

    forAll(swaggerChecks.requestGenerator("POST", "/v1/authors")) {
      request =>
        (request.method == "POST") :| "Method" &&
          (request.path == "/v1/authors") :| "Path" &&
          request.body.isDefined :| "Has body" &&
          verifier.verify(request.body.get.minified).isSuccess :| "Body is author"
    }
  }

  property("Request generator GET /author/{id}") =
    forAll(swaggerChecks.requestGenerator("GET", "/v1/authors/{id}")) {
      request =>
        (request.method == "GET") :| "Method" &&
          request.path.startsWith("/v1/authors") :| "Path" &&
          (UUID.fromString(request.path.substring(12)) ne null) :| "Id is uuid" &&
          request.body.isEmpty :| "Has no body"
    }

  property("Operation verifier") = forAll(swaggerChecks.operationVerifier[SimpleRequest, SimpleResponse](_ == "/v1/authors")) {
    case operationVerifier: SimpleOperationVerifier if operationVerifier.request.method == "GET" =>
      val profileJson = swaggerChecks.jsonGenerator("AuthorsPage")
      val response = SimpleResponse(200, Map.empty, profileJson.sample.get.minified)

      (operationVerifier.request.path == "/v1/authors") :| "Path" &&
        (operationVerifier.request.method == "GET") :| "Method" &&
        operationVerifier.responseVerifier.verify(response).isSuccess :| "Response verifier"
    case operationVerifier: SimpleOperationVerifier =>
      val profileJson = swaggerChecks.jsonGenerator("Author")
      val response = SimpleResponse(201, Map.empty, "")

      (operationVerifier.request.path == "/v1/authors") :| "Path" &&
        (operationVerifier.request.method == "POST") :| "Method" &&
        operationVerifier.responseVerifier.verify(response).isSuccess :| "Response verifier"
      true :| "Just ok"
  }
} 
Example 177
Source File: StringFormats.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema.model.formats

import java.net.{URI, URL}
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
import java.time.{Instant, LocalDate}
import java.util.UUID

import de.leanovate.swaggercheck.schema.model.{JsonPath, ValidationResult}

import scala.util.Try

object StringFormats {

  object URLString extends ValueFormat[String] {
    override def validate(path: JsonPath, value: String): ValidationResult =
      if (Try(new URL(value)).isSuccess)
        ValidationResult.success
      else
        ValidationResult.error(s"'$value' is not an url: $path")
  }

  object URIString extends ValueFormat[String] {
    override def validate(path: JsonPath, value: String): ValidationResult =
      if (Try(new URI(value)).isSuccess)
        ValidationResult.success
      else
        ValidationResult.error(s"'$value' is not an uri: $path")
  }

  object UUIDString extends ValueFormat[String] {
    override def validate(path: JsonPath, value: String): ValidationResult =
      if (Try(UUID.fromString(value)).isSuccess)
        ValidationResult.success
      else
        ValidationResult.error(s"'$value' is not an uuid: $path")
  }

  object EmailString extends ValueFormat[String] {
    val emailPattern = """(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])""".r

    override def validate(path: JsonPath, value: String): ValidationResult =
      if (emailPattern.pattern.matcher(value).matches()) {
        ValidationResult.success
      } else {
        ValidationResult.error(s"'$value' is not an email: $path")
      }  }

  object DateString extends ValueFormat[String] {
    override def validate(path: JsonPath, value: String): ValidationResult =
      if (Try(DateTimeFormatter.ISO_DATE.parse(value)).isSuccess)
        ValidationResult.success
      else
        ValidationResult.error(s"'$value' is not a date: $path")
  }

  object DateTimeString extends ValueFormat[String] {
    override def validate(path: JsonPath, value: String): ValidationResult =
      if (Try(DateTimeFormatter.ISO_DATE_TIME.parse(value)).isSuccess)
        ValidationResult.success
      else
        ValidationResult.error(s"'$value' is not a date-time: $path")
  }

  val defaultFormats = Map(
    "url" -> URLString,
    "uri" -> URIString,
    "uuid" -> UUIDString,
    "email" -> EmailString,
    "date" -> DateString,
    "date-time" -> DateTimeString
  )
} 
Example 178
Source File: MyService.scala    From airframe   with Apache License 2.0 5 votes vote down vote up
package example.api


trait ResourceApi {
  @Endpoint(method = HttpMethod.GET, path = "/v1/resources/:id")
  def getResource(getRequest: GetResourceRequest): ResourceResponse

  @Endpoint(method = HttpMethod.POST, path = "/v1/resources")
  def addResource(createResourceRequest: CreateResourceRequest): ResourceResponse

  @Endpoint(method = HttpMethod.DELETE, path = "/v1/resources/:id")
  def deleteResource(deleteResourceRequest: DeleteResourceRequest, request: Request): Unit

  @Endpoint(method = HttpMethod.PATCH, path = "/v1/resources")
  def patchResource(request: HttpRequest[Request]): Unit

  @Endpoint(method = HttpMethod.GET, path = "/v1/resources")
  def listResources(context: HttpContext[Request, Response, Future]): Seq[ResourceResponse] = {
    // Non abstract method example
    Seq.empty
  }
}

case class Query(id: String, sql: String)
case class CreateQueryRequest(request_id: String = UUID.randomUUID().toString, sql: String)
case class QueryResultResponse(id: String, nextToken: String)
trait QueryApi {
  @Endpoint(method = HttpMethod.GET, path = "/v1/query")
  def listQueries: Seq[Query]

  @Endpoint(method = HttpMethod.GET, path = "/v1/query/:id")
  def getQueryById(id: Int): QueryResultResponse

  @Endpoint(method = HttpMethod.GET, path = "/v1/query/:id/page/:page")
  def getQueryPage(id: Int, page: Int): QueryResultResponse

  @Endpoint(method = HttpMethod.POST, path = "/v1/query")
  def newQuery(createQueryRequest: CreateQueryRequest): QueryResultResponse
}

case class Book(id: String, name: String)

trait BookApi {
  @Endpoint(method = HttpMethod.GET, path = "/v1/books")
  def getBooks(limit: Int = 100, sort: Option[Boolean] = None): Seq[Book]
} 
Example 179
Source File: LazyF0.scala    From airframe   with Apache License 2.0 5 votes vote down vote up
package wvlet.airframe

import java.util.UUID

object LazyF0 {
  def apply[R](f: => R): LazyF0[R] = new LazyF0(f)
}


  def eval: R = f

  override def hashCode(): Int = {
    uuid.hashCode()
  }

  def canEqual(other: Any): Boolean = other.isInstanceOf[LazyF0[_]]

  override def equals(other: Any): Boolean = {
    other match {
      case that: LazyF0[_] =>
        // Scala 2.12 generates Lambda for Function0, and the class might be generated every time, so
        // comparing functionClasses doesn't work
        (that canEqual this) && this.uuid == that.uuid
      case _ => false
    }
  }
} 
Example 180
Source File: MyService.scala    From airframe   with Apache License 2.0 5 votes vote down vote up
package example
import java.util.UUID

import wvlet.airframe.http._

import scala.concurrent.Future

case class GetResourceRequest(id: String)
case class ResourceResponse(id: String, data: String)
case class CreateResourceRequest(id: String, data: String)
case class DeleteResourceRequest(id: String)


trait ResourceApi {
  @Endpoint(method = HttpMethod.GET, path = "/v1/resources/:id")
  def getResource(getRequest: GetResourceRequest): ResourceResponse

  @Endpoint(method = HttpMethod.POST, path = "/v1/resources")
  def addResource(createResourceRequest: CreateResourceRequest): ResourceResponse

  @Endpoint(method = HttpMethod.DELETE, path = "/v1/resources/:id")
  def deleteResource(deleteResourceRequest: DeleteResourceRequest, request: HttpMessage.Request): Unit

  @Endpoint(method = HttpMethod.GET, path = "/v1/resources")
  def listResources(context: HttpContext[HttpMessage.Request, HttpMessage.Response, Future]): Seq[ResourceResponse] = {
    // Non abstract method example
    Seq.empty
  }
}

case class Query(id: String, sql: String)
case class CreateQueryRequest(request_id: String = UUID.randomUUID().toString, sql: String)
case class QueryResultResponse(id: String, nextToken: String)

trait QueryApi {
  @Endpoint(method = HttpMethod.GET, path = "/v1/query")
  def listQueries: Seq[Query]

  @Endpoint(method = HttpMethod.GET, path = "/v1/query/:id")
  def getQueryById(id: Int): QueryResultResponse

  @Endpoint(method = HttpMethod.GET, path = "/v1/query/:id/page/:page")
  def getQueryPage(id: Int, page: Int): QueryResultResponse

  @Endpoint(method = HttpMethod.POST, path = "/v1/query")
  def newQuery(createQueryRequest: CreateQueryRequest): QueryResultResponse
} 
Example 181
Source File: Compat.scala    From airframe   with Apache License 2.0 5 votes vote down vote up
package wvlet.airframe.codec
import java.time.Instant
import java.util.UUID

import wvlet.airframe.surface.Surface

import scala.util.Try


object Compat {
  def messageCodecFinder: MessageCodecFinder                = MessageCodecFinder.defaultMessageCodecFinder
  def platformSpecificCodecs: Map[Surface, MessageCodec[_]] = Map.empty

  def codecOfClass(
      cl: Class[_],
      codecFactory: MessageCodecFactory = MessageCodecFactory.defaultFactoryForJSON
  ): Option[MessageCodec[_]] = None

  private[codec] def parseInstant(s: String): Option[Instant] = {
    Try(Instant.parse(s)).toOption
  }

  def readUUIDFromBytes(data: Array[Byte]): UUID = {
    throw new IllegalArgumentException("Reading binary UUID is not supported in Scala.js")
  }
} 
Example 182
Source File: StandardCodec.scala    From airframe   with Apache License 2.0 5 votes vote down vote up
package wvlet.airframe.codec

import java.util.UUID

import wvlet.airframe.surface.Surface


object StandardCodec {
  val javaClassCodec = Map(
    Surface.of[Throwable]         -> ThrowableCodec,
    Surface.of[Exception]         -> ThrowableCodec,
    Surface.of[java.time.Instant] -> JavaInstantTimeCodec,
    Surface.of[UUID]              -> UUIDCodec
  )

  val standardCodec: Map[Surface, MessageCodec[_]] =
    PrimitiveCodec.primitiveCodec ++ PrimitiveCodec.primitiveArrayCodec ++ javaClassCodec
} 
Example 183
Source File: UUIDCodec.scala    From airframe   with Apache License 2.0 5 votes vote down vote up
package wvlet.airframe.codec
import java.util.UUID

import wvlet.airframe.msgpack.spi.{Packer, Unpacker, ValueType}


object UUIDCodec extends MessageCodec[UUID] {

  override def pack(p: Packer, v: UUID): Unit = {
    p.packString(v.toString)
  }
  override def unpack(
      u: Unpacker,
      v: MessageContext
  ): Unit = {
    u.getNextValueType match {
      case ValueType.NIL =>
        u.unpackNil
        v.setNull
      case ValueType.STRING =>
        val s = u.unpackString
        try {
          v.setObject(UUID.fromString(s))
        } catch {
          case e: IllegalArgumentException =>
            v.setError(e)
        }
      case ValueType.BINARY =>
        val len  = u.unpackBinaryHeader
        val data = u.readPayload(len)
        try {
          v.setObject(Compat.readUUIDFromBytes(data))
        } catch {
          case e: Throwable => v.setError(e)
        }
      case _ =>
        u.skipValue
        v.setNull
    }
  }
} 
Example 184
Source File: MapConversionTest.scala    From airframe   with Apache License 2.0 5 votes vote down vote up
package wvlet.airframe.codec
import java.util.UUID

import wvlet.airspec.AirSpec


object MapConversionTest extends AirSpec {

  case class A(id: Int, name: String, key: UUID)

  test("convert Map[String, Any] to object") {
    val uuid  = UUID.randomUUID()
    val m     = Map("id" -> 10, "name" -> "leo", "key" -> uuid)
    val codec = MessageCodec.of[A]
    val a     = codec.fromMap(m)
    a shouldBe A(10, "leo", uuid)
  }
} 
Example 185
Source File: Compat.scala    From airframe   with Apache License 2.0 5 votes vote down vote up
package wvlet.airframe.codec
import java.time.Instant
import java.util.UUID

import wvlet.airframe.codec.JavaStandardCodec.JavaEnumCodec
import wvlet.airframe.metrics.TimeParser
import wvlet.airframe.surface.reflect.{ReflectSurfaceFactory, ReflectTypeUtil}
import wvlet.airframe.surface.{GenericSurface, JavaEnumSurface, Surface}

import scala.reflect.runtime.{universe => ru}
import scala.util.Try


object Compat {
  def messageCodecFinder: MessageCodecFinder = {
    MessageCodecFinder.defaultMessageCodecFinder orElse
      JVMMessageCodecFinder
  }

  object JVMMessageCodecFinder extends MessageCodecFinder {
    override def findCodec(
        factory: MessageCodecFactory,
        seenSet: Set[Surface]
    ): PartialFunction[Surface, MessageCodec[_]] = {
      case JavaEnumSurface(cl) =>
        JavaEnumCodec(cl)
      case s if ReflectTypeUtil.hasStringUnapplyConstructor(s) =>
        new StringUnapplyCodec(s)
    }
  }

  def platformSpecificCodecs: Map[Surface, MessageCodec[_]] =
    JavaTimeCodec.javaTimeCodecs ++ JavaStandardCodec.javaStandardCodecs

  def codecOf[A: ru.TypeTag]: MessageCodec[A] = MessageCodecFactory.defaultFactory.of[A]
  def codecOfClass(
      cl: Class[_],
      codecFactory: MessageCodecFactory = MessageCodecFactory.defaultFactoryForJSON
  ): Option[MessageCodec[_]] = {
    // Finding the surface using reflection
    val surface = ReflectSurfaceFactory.ofClass(cl)
    codecFactory.of(surface) match {
      case o: ObjectCodecBase if o.paramCodec.isEmpty =>
        // If the codec is an ObjectCodec without any parameters,
        // it will produce empty json object ({}), so we cannot use it
        None
      case codec =>
        Some(codec)
    }
  }

  private[codec] def parseInstant(s: String): Option[Instant] = {
    Try(Instant.parse(s)).toOption
      .orElse(TimeParser.parseAtLocalTimeZone(s).map(_.toInstant))
  }

  def readUUIDFromBytes(data: Array[Byte]): UUID = {
    UUID.nameUUIDFromBytes(data)
  }
} 
Example 186
Source File: IdentificationWithFallback.scala    From dependency   with MIT License 5 votes vote down vote up
package controllers.util

import java.util.UUID

import javax.inject.{Inject, Singleton}
import db.{TokensDao, UsersDao}
import io.flow.common.v0.models.UserReference
import io.flow.log.RollbarLogger
import io.flow.play.controllers._
import io.flow.play.util.{AuthData, Config}
import play.api.mvc._

import scala.concurrent.{ExecutionContext, Future}

// Custom implementation based on FlowController.Identified but with database fallback for auth
@Singleton
class IdentificationWithFallback @Inject()(
  val parser: BodyParsers.Default,
  val config: Config,
  authorization: AuthorizationImpl,
  tokensDao: TokensDao,
  usersDao: UsersDao
)(implicit val executionContext: ExecutionContext, logger: RollbarLogger)
  extends ActionBuilder[IdentifiedRequest, AnyContent] with FlowActionInvokeBlockHelper {

  def invokeBlock[A](request: Request[A], block: (IdentifiedRequest[A]) => Future[Result]): Future[Result] = {
    auth(request.headers)(AuthData.Identified.fromMap) match {
      case None =>
        legacyUser(request.headers) match {
          case None => Future.successful(unauthorized(request))
          case Some(user) =>
            val ad = AuthData.Identified(user = user, session = None, requestId = "lib-play-" + UUID.randomUUID.toString, customer = None)
            block(new IdentifiedRequest(ad, request))
        }
      case Some(ad) => block(new IdentifiedRequest(ad, request))
    }
  }

  private[this] def legacyUser(headers: Headers): Option[UserReference] = {
    basicAuthorizationToken(headers) match {
      case None => None
      case Some(token) => {
        token match {
          case token: Token => getUser(token.token)
          case token: JwtToken => Some(UserReference(token.userId))
        }
      }
    }
  }

  private def getUser(token: String): Option[UserReference] = {
    tokensDao.findByToken(token) match {
      case Some(t) => Some(UserReference(t.user.id))
      case None => usersDao.findById(token).map(user => UserReference(user.id))
    }
  }

  
  private[this] def basicAuthorizationToken(
    headers: play.api.mvc.Headers
  ): Option[Authorization] = {
    headers.get("Authorization").flatMap { h =>
      authorization.get(h)
    }
  }

} 
Example 187
Source File: SubscriptionActionBuilder.scala    From dependency   with MIT License 5 votes vote down vote up
package controllers.util

import java.util.UUID

import db.{TokensDao, UsersDao}
import io.flow.common.v0.models.UserReference
import io.flow.log.RollbarLogger
import io.flow.play.controllers.{AuthorizationImpl, IdentifiedRequest}
import io.flow.play.util.{AuthData, Config}
import play.api.mvc._

import scala.concurrent.{ExecutionContext, Future}

@javax.inject.Singleton
class SubscriptionActionBuilder @javax.inject.Inject() (
  override val parser: BodyParsers.Default,
  override val config: Config,
  authorization: AuthorizationImpl,
  tokensDao: TokensDao,
  usersDao: UsersDao,
)(implicit override val executionContext: ExecutionContext, logger: RollbarLogger) extends IdentificationWithFallback(parser, config, authorization, tokensDao, usersDao) {

  override def invokeBlock[A](request: Request[A], block: IdentifiedRequest[A] => Future[Result]): Future[Result] = {
    request.queryString.getOrElse("identifier", Seq.empty).toList match {
      case Nil => {
        super.invokeBlock(request, block)
      }

      case identifier :: Nil => {
        usersDao.findByIdentifier(identifier) match {
          case None => {
            Future.successful(unauthorized(request))
          }
          case Some(user) => {
            val ad = AuthData.Identified(
              user = UserReference(id = user.id),
              session = None,
              requestId = "dependency-api-" + UUID.randomUUID.toString,
              customer = None
            )
            block(new IdentifiedRequest(ad, request))
          }
        }
      }

      case multiple => {
        logger.withKeyValue("size", multiple.size).warn(s"Multiple identifiers found in request - assuming no User")
        Future.successful(unauthorized(request))
      }
    }
  }

} 
Example 188
Source File: BinariesDaoSpec.scala    From dependency   with MIT License 5 votes vote down vote up
package db

import java.util.UUID

import io.flow.dependency.v0.models.{BinaryType, Organization, SyncEvent}
import util.DependencySpec

class BinariesDaoSpec extends DependencySpec {

  private[this] lazy val org: Organization = createOrganization()

  "findByName" in {
    val lang = createBinary(org)
    binariesDao.findByName(lang.name.toString).map(_.name) must be(
      Some(lang.name)
    )

    binariesDao.findByName(UUID.randomUUID.toString) must be(None)
  }

  "findById" in {
    val lang = createBinary(org)
    binariesDao.findById(lang.id).map(_.id) must be(
      Some(lang.id)
    )

    binariesDao.findById(UUID.randomUUID.toString) must be(None)
  }

  "findAll by ids" in {
    val binary1 = createBinary(org)
    val binary2 = createBinary(org)

    binariesDao.findAll(ids = Some(Seq(binary1.id, binary2.id))).map(_.id).sorted must be(
      Seq(binary1, binary2).map(_.id).sorted
    )

    binariesDao.findAll(ids = Some(Nil)) must be(Nil)
    binariesDao.findAll(ids = Some(Seq(UUID.randomUUID.toString))) must be(Nil)
    binariesDao.findAll(ids = Some(Seq(binary1.id, UUID.randomUUID.toString))).map(_.id) must be(Seq(binary1.id))
  }

  "findAll by isSynced" in {
    val binary = createBinary(org)
    createSync(createSyncForm(objectId = binary.id, event = SyncEvent.Completed))

    binariesDao.findAll(id = Some(binary.id), isSynced = Some(true)).map(_.id) must be(Seq(binary.id))
    binariesDao.findAll(id = Some(binary.id), isSynced = Some(false)) must be(Nil)
  }

  "findAll by projectId" in {
    val (project, binaryVersion) = createProjectWithBinary(org)

    binariesDao.findAll(id = Some(binaryVersion.binary.id), projectId = Some(project.id)).map(_.id) must be(Seq(binaryVersion.binary.id))
    binariesDao.findAll(id = Some(binaryVersion.binary.id), projectId = Some(createProject().id)) must be(Nil)
  }

  "create" must {
    "validates empty name" in {
      val form = createBinaryForm(org).copy(name = BinaryType.UNDEFINED("   "))
      binariesDao.validate(form) must be(
        Seq("Name cannot be empty")
      )
    }

    "validates duplicate names" in {
      val lang = createBinary(org)
      val form = createBinaryForm(org).copy(name = BinaryType.UNDEFINED(lang.name.toString.toUpperCase))
      binariesDao.validate(form) must be(
        Seq("Binary with this name already exists")
      )
    }
  }

} 
Example 189
Source File: TokensDaoSpec.scala    From dependency   with MIT License 5 votes vote down vote up
package db

import java.util.UUID

import util.DependencySpec

class TokensDaoSpec extends DependencySpec {

  "setLatestByTag" in {
    val form = InternalTokenForm.UserCreated(createTokenForm())
    val token1 = rightOrErrors(tokensDao.create(systemUser, form))

    val token2 = tokensDao.setLatestByTag(systemUser, form)
    token1.id must not be (token2.id)
  }

  "findById" in {
    val token = createToken()
    tokensDao.findById(Authorization.All, token.id).map(_.id) must be(
      Some(token.id)
    )

    tokensDao.findById(Authorization.All, UUID.randomUUID.toString) must be(None)
  }

  "getCleartextGithubOauthTokenByUserId" in {
    val user = createUser()
    val actualToken = createTestKey()
    val form = InternalTokenForm.GithubOauth(user.id, actualToken)
    tokensDao.create(systemUser, form)

    tokensDao.getCleartextGithubOauthTokenByUserId(user.id) must be(Some(actualToken))
    tokensDao.getCleartextGithubOauthTokenByUserId(createUser().id) must be(None)
  }

  "addCleartextIfAvailable" in {
    val token = createToken()
    token.cleartext must be(None)
    val clear = tokensDao.addCleartextIfAvailable(systemUser, token).cleartext.getOrElse {
      sys.error("Failed to read token")
    }
    token.masked must be(clear.substring(0, 3) + "-masked-xxx")
    tokensDao.addCleartextIfAvailable(systemUser, token).cleartext must be(None)
    clear.length must be(64)
  }

  "findAll by ids" in {
    val token1 = createToken()
    val token2 = createToken()

    tokensDao.findAll(Authorization.All, ids = Some(Seq(token1.id, token2.id))).map(_.id) must be(
      Seq(token1.id, token2.id)
    )

    tokensDao.findAll(Authorization.All, ids = Some(Nil)) must be(Nil)
    tokensDao.findAll(Authorization.All, ids = Some(Seq(UUID.randomUUID.toString))) must be(Nil)
    tokensDao.findAll(Authorization.All, ids = Some(Seq(token1.id, UUID.randomUUID.toString))).map(_.id) must be(Seq(token1.id))
  }

  "can only see own tokens" in {
    val user1 = createUser()
    val token1 = createToken(createTokenForm(user = user1))

    val user2 = createUser()
    val token2 = createToken(createTokenForm(user = user2))

    tokensDao.findAll(Authorization.User(user1.id)).map(_.id) must be(Seq(token1.id))
    tokensDao.findAll(Authorization.User(user2.id)).map(_.id) must be(Seq(token2.id))
    tokensDao.findAll(Authorization.User(createUser().id)).map(_.id) must be(Nil)

  }

} 
Example 190
Source File: BinaryVersionsDaoSpec.scala    From dependency   with MIT License 5 votes vote down vote up
package db

import java.util.UUID

import util.DependencySpec

class BinaryVersionsDaoSpec extends DependencySpec {

  lazy val org = createOrganization()

  "upsert" in {
    val binary = createBinary(org)
    val version1 = binaryVersionsDao.upsert(systemUser, binary.id, "1.0")
    val version2 = binaryVersionsDao.upsert(systemUser, binary.id, "1.0")
    val version3 = binaryVersionsDao.upsert(systemUser, binary.id, "1.1")

    version1.id must be(version2.id)
    version2.id must not be(version3.id)
  }

  "findById" in {
    val version = createBinaryVersion(org)()
    binaryVersionsDao.findById(version.id).map(_.id) must be(
      Some(version.id)
    )

    binaryVersionsDao.findById(UUID.randomUUID.toString) must be(None)
  }

  "findAll by ids" in {
    val version1 = createBinaryVersion(org)()
    val version2 = createBinaryVersion(org)()

    binaryVersionsDao.findAll(ids = Some(Seq(version1.id, version2.id))).map(_.id).sorted must be(
      Seq(version1.id, version2.id).sorted
    )

    binaryVersionsDao.findAll(ids = Some(Nil)) must be(Nil)
    binaryVersionsDao.findAll(ids = Some(Seq(UUID.randomUUID.toString))) must be(Nil)
    binaryVersionsDao.findAll(ids = Some(Seq(version1.id, UUID.randomUUID.toString))).map(_.id) must be(Seq(version1.id))
  }

  "delete" in {
    val binary = createBinary(org)
    val version1 = binaryVersionsDao.upsert(systemUser, binary.id, "1.0")
    binaryVersionsDao.delete(systemUser, version1)
    val version2 = binaryVersionsDao.upsert(systemUser, binary.id, "1.0")
    val version3 = binaryVersionsDao.upsert(systemUser, binary.id, "1.0")

    version1.id must not be(version2.id)
    version2.id must be(version3.id)
  }

} 
Example 191
Source File: LastEmailsDaoSpec.scala    From dependency   with MIT License 5 votes vote down vote up
package db

import java.util.UUID

import io.flow.dependency.v0.models.Publication
import util.DependencySpec

class LastEmailsDaoSpec extends  DependencySpec {

  "delete" in {
    val lastEmail = createLastEmail()
    lastEmailsDao.delete(systemUser, lastEmail)
    lastEmailsDao.findById(lastEmail.id) must be(None)
  }

  "record" in {
    val form = createLastEmailForm()
    val lastEmail1 = createLastEmail(form)
    val lastEmail2 = createLastEmail(form)
    lastEmail1.id must not be(lastEmail2.id)

    lastEmailsDao.findById(lastEmail1.id) must be(None)
    lastEmailsDao.findById(lastEmail2.id).map(_.id) must be(Some(lastEmail2.id))
  }

  "findByUserIdAndPublication" in {
    val form = createLastEmailForm()
    val lastEmail = createLastEmail(form)

    lastEmailsDao.findByUserIdAndPublication(form.userId, form.publication).map(_.id) must be(Some(lastEmail.id))
    lastEmailsDao.findByUserIdAndPublication(UUID.randomUUID.toString, form.publication).map(_.id) must be(None)
    lastEmailsDao.findByUserIdAndPublication(form.userId, Publication.UNDEFINED("other")).map(_.id) must be(None)
  }

} 
Example 192
Source File: UserIdentifiersDaoSpec.scala    From dependency   with MIT License 5 votes vote down vote up
package db

import java.util.UUID

import io.flow.dependency.v0.models.UserIdentifier
import io.flow.common.v0.models.User
import util.DependencySpec

class UserIdentifiersDaoSpec extends DependencySpec {

  def createUserIdentifier(): (User, UserIdentifier) = {
    val user = createUser()
    val userIdentifier = userIdentifiersDao.createForUser(systemUser, user)
    (user, userIdentifier)
  }

  "createForUser" in {
    val user = createUser()
    val identifier1 = userIdentifiersDao.createForUser(systemUser, user)
    val identifier2 = userIdentifiersDao.createForUser(systemUser, user)

    identifier1.value must not be (identifier2.value)
    identifier1.user.id must be(user.id)
    identifier2.user.id must be(user.id)
    identifier1.value.length must be(60)
  }

  "findById" in {
    val (_, identifier) = createUserIdentifier()

    userIdentifiersDao.findById(identifier.id).map(_.id) must be(
      Some(identifier.id)
    )

    userIdentifiersDao.findById(UUID.randomUUID.toString) must be(None)
  }

  "findAll" must {
    "filter by ids" in {
      val (_, identifier1) = createUserIdentifier()
      val (_, identifier2) = createUserIdentifier()

      userIdentifiersDao.findAll(ids = Some(Seq(identifier1.id, identifier2.id))).map(_.id).sorted must be(
        Seq(identifier1.id, identifier2.id).sorted
      )

      userIdentifiersDao.findAll(ids = Some(Nil)) must be(Nil)
      userIdentifiersDao.findAll(ids = Some(Seq(UUID.randomUUID.toString))) must be(Nil)
      userIdentifiersDao.findAll(ids = Some(Seq(identifier1.id, UUID.randomUUID.toString))).map(_.id) must be(
        Seq(identifier1.id)
      )
    }

    "filter by identifier" in {
      val (_, identifier) = createUserIdentifier()

      userIdentifiersDao.findAll(value = Some(identifier.value)).map(_.id) must be(Seq(identifier.id))
      userIdentifiersDao.findAll(value = Some(createTestKey())) must be(Nil)
    }
  }
} 
Example 193
Source File: SubscriptionsDaoSpec.scala    From dependency   with MIT License 5 votes vote down vote up
package db

import java.util.UUID

import io.flow.dependency.v0.models.Publication
import util.DependencySpec

class SubscriptionsDaoSpec extends DependencySpec {

  "upsert" in {
    val form = createSubscriptionForm()
    subscriptionsDao.upsertByUserIdAndPublication(systemUser, form).rightValue

    subscriptionsDao.upsertByUserIdAndPublication(systemUser, form)
    val subscription = subscriptionsDao.findByUserIdAndPublication(form.userId, form.publication).get

    val otherSubscription = createSubscription()
    subscription.id must not be (otherSubscription.id)
  }

  "findById" in {
    val subscription = createSubscription()
    subscriptionsDao.findById(subscription.id).map(_.id) must be(
      Some(subscription.id)
    )

    subscriptionsDao.findById(UUID.randomUUID.toString) must be(None)
  }

  "findByUserIdAndPublication" in {
    val subscription = createSubscription()
    subscriptionsDao.findByUserIdAndPublication(subscription.user.id, subscription.publication).map(_.id) must be(
      Some(subscription.id)
    )

    subscriptionsDao.findByUserIdAndPublication(UUID.randomUUID.toString, subscription.publication).map(_.id) must be(None)
    subscriptionsDao.findByUserIdAndPublication(subscription.user.id, Publication.UNDEFINED("other")).map(_.id) must be(None)
  }

  "findAll by ids" in {
    // Create subscriptions for two different users so unique constraint on (user_id, publication) is not violated 
    val subscription1 = createSubscription(user = createUser())
    val subscription2 = createSubscription(user = createUser())

    subscriptionsDao.findAll(ids = Some(Seq(subscription1.id, subscription2.id))).map(_.id) must be(
      Seq(subscription1.id, subscription2.id)
    )

    subscriptionsDao.findAll(ids = Some(Nil)) must be(Nil)
    subscriptionsDao.findAll(ids = Some(Seq(UUID.randomUUID.toString))) must be(Nil)
    subscriptionsDao.findAll(ids = Some(Seq(subscription1.id, UUID.randomUUID.toString))).map(_.id) must be(Seq(subscription1.id))
  }

  "findAll by identifier" in {
    val user = createUser()
    val identifier = userIdentifiersDao.latestForUser(systemUser, user).value
    val subscription = createSubscription(createSubscriptionForm(user = user))

    subscriptionsDao.findAll(identifier = Some(identifier)).map(_.id) must be(Seq(subscription.id))
    subscriptionsDao.findAll(identifier = Some(createTestKey())) must be(Nil)
  }

  "findAll by minHoursSinceLastEmail" in {
    val user = createUser()
    val subscription = createSubscription(
      createSubscriptionForm(user = user, publication = Publication.DailySummary)
    )

    subscriptionsDao.findAll(
      id = Some(subscription.id),
      minHoursSinceLastEmail = Some(1)
    ).map(_.id) must be(Seq(subscription.id))

    createLastEmail(createLastEmailForm(user = user, publication = Publication.DailySummary))

    subscriptionsDao.findAll(
      id = Some(subscription.id),
      minHoursSinceLastEmail = Some(1)
    ) must be(Nil)
  }

} 
Example 194
Source File: LibrariesSpec.scala    From dependency   with MIT License 5 votes vote down vote up
package controllers

import java.util.UUID

import io.flow.common.v0.models.UserReference
import _root_.util.{DependencySpec, MockDependencyClient}

class LibrariesSpec extends DependencySpec with MockDependencyClient {

  import scala.concurrent.ExecutionContext.Implicits.global

  lazy val org = createOrganization()
  lazy val library1 = createLibrary(org)()
  lazy val library2 = createLibrary(org)()
  lazy val client = identifiedClient(UserReference(systemUser.id))

  "GET /libraries by id" in  {
    await(
      client.libraries.get(id = Some(library1.id))
    ).map(_.id) must contain theSameElementsAs (
      Seq(library1.id)
      )

    await(
      client.libraries.get(id = Some(UUID.randomUUID.toString))
    ).map(_.id) must be(
      Nil
    )
  }

  "GET /libraries by groupId" in  {
    await(
      client.libraries.get(groupId = Some(library1.groupId))
    ).map(_.groupId) must contain theSameElementsAs (
      Seq(library1.groupId)
      )

    await(
      client.libraries.get(groupId = Some(UUID.randomUUID.toString))
    ) must be(
      Nil
    )
  }

  "GET /libraries by artifactId" in  {
    await(
      client.libraries.get(artifactId = Some(library1.artifactId))
    ).map(_.artifactId) must contain theSameElementsAs Seq(library1.artifactId)

    await(
      client.libraries.get(artifactId = Some(UUID.randomUUID.toString))
    ) must be(
      Nil
    )
  }

  "GET /libraries/:id" in  {
    await(client.libraries.getById(library1.id)).id must be(library1.id)
    await(client.libraries.getById(library2.id)).id must be(library2.id)

    expectNotFound {
      client.libraries.getById(UUID.randomUUID.toString)
    }
  }

  "POST /libraries" in  {
    val form = createLibraryForm(org)()
    val library = await(client.libraries.post(form))
    library.groupId must be(form.groupId)
    library.artifactId must be(form.artifactId)
  }

  "POST /libraries validates duplicate" in  {
    expectErrors(
      client.libraries.post(
        createLibraryForm(org)().copy(
          groupId = library1.groupId,
          artifactId = library1.artifactId
        )
      )
    ).genericErrors.flatMap(_.messages) must contain theSameElementsAs Seq("Library with this group id and artifact id already exists")
  }

  "DELETE /libraries" in  {
    val library = createLibrary(org)()
    await(
      client.libraries.deleteById(library.id)
    ) must be(())

    expectNotFound(
      client.libraries.getById(library.id)
    )

    expectNotFound(
      client.libraries.deleteById(library.id)
    )
  }

} 
Example 195
Source File: BinariesSpec.scala    From dependency   with MIT License 5 votes vote down vote up
package controllers

import java.util.UUID

import _root_.util.{DependencySpec, MockDependencyClient}

class BinariesSpec extends DependencySpec with MockDependencyClient {

  import scala.concurrent.ExecutionContext.Implicits.global

  lazy val org = createOrganization()
  lazy val binary1 = createBinary(org)()
  lazy val binary2 = createBinary(org)()

  "GET /binaries by id" in  {
    await(
      identifiedClient().binaries.get(id = Some(binary1.id))
    ).map(_.id) must contain theSameElementsAs  Seq(binary1.id)

    await(
      identifiedClient().binaries.get(id = Some(UUID.randomUUID.toString))
    ).map(_.id) must be(
      Nil
    )
  }

  "GET /binaries by name" in  {
    await(
      identifiedClient().binaries.get(name = Some(binary1.name.toString))
    ).map(_.name) must contain theSameElementsAs Seq(binary1.name)

    await(
      identifiedClient().binaries.get(name = Some(binary1.name.toString.toUpperCase))
    ).map(_.name) must contain theSameElementsAs Seq(binary1.name)

    await(
      identifiedClient().binaries.get(name = Some(UUID.randomUUID.toString))
    ) must be(
      Nil
    )
  }

  "GET /binaries/:id" in  {
    await(identifiedClient().binaries.getById(binary1.id)).id must be(binary1.id)
    await(identifiedClient().binaries.getById(binary2.id)).id must be(binary2.id)

    expectNotFound {
      identifiedClient().binaries.getById(UUID.randomUUID.toString)
    }
  }

  "POST /binaries" in  {
    val form = createBinaryForm(org)
    val binary = await(identifiedClient().binaries.post(form))
    binary.name must be(form.name)
  }

  "POST /binaries validates duplicate name" in  {
    expectErrors(
      identifiedClient().binaries.post(createBinaryForm(org).copy(name = binary1.name))
    ).genericErrors.flatMap(_.messages) must contain theSameElementsAs Seq("Binary with this name already exists")
  }

  "DELETE /binaries" in  {
    val binary = createBinary(org)()
    await(
      identifiedClient().binaries.deleteById(binary.id)
    ) must be(())

    expectNotFound(
      identifiedClient().binaries.getById(binary.id)
    )

    expectNotFound(
      identifiedClient().binaries.deleteById(binary.id)
    )
  }

} 
Example 196
Source File: SubscriptionsSpec.scala    From dependency   with MIT License 5 votes vote down vote up
package controllers

import java.util.UUID

import _root_.util.{DependencySpec, MockDependencyClient}

class SubscriptionsSpec extends DependencySpec with MockDependencyClient {

  import scala.concurrent.ExecutionContext.Implicits.global

  private[this] lazy val defaultUser1 = createUser()
  private[this] lazy val defaultUser1Identifier = createUserIdentifier(defaultUser1)
  private[this] val defaultSubscription1 = createSubscription(createSubscriptionForm(defaultUser1))
  private[this] lazy val defaultUser2 = createUser()
  private[this] lazy val defaultUser2Identifier = createUserIdentifier(defaultUser2)
  private[this] val defaultSubscription2 = createSubscription(createSubscriptionForm(defaultUser2))

  "GET /subscriptions by identifier" in {
    await(
      identifiedClient().subscriptions.get(identifier = Some(defaultUser1Identifier.value))
    ).map(_.id) must contain theSameElementsAs Seq(defaultSubscription1.id)

    await(
      identifiedClient().subscriptions.get(identifier = Some(defaultUser2Identifier.value))
    ).map(_.id) must contain theSameElementsAs Seq(defaultSubscription2.id)

    await(
      identifiedClient().users.get(id = Some(UUID.randomUUID.toString))
    ).map(_.id) must be(
      Nil
    )
  }

  "DELETE /subscriptions/:id by identifier" in {
    val user = createUser()
    val user1Identifier = createUserIdentifier(user)
    val subscription = createSubscription(createSubscriptionForm(user))

    await(
      identifiedClient().subscriptions.deleteById(id = subscription.id, identifier = Some(user1Identifier.value))
    )
    subscriptionsDao.findById(subscription.id) must be(empty)
  }
} 
Example 197
Source File: ProjectsSpec.scala    From dependency   with MIT License 5 votes vote down vote up
package controllers

import java.util.UUID

import io.flow.common.v0.models.UserReference
import _root_.util.{DependencySpec, MockDependencyClient}

class ProjectsSpec extends DependencySpec with MockDependencyClient {

  import scala.concurrent.ExecutionContext.Implicits.global

  "GET /projects by id" in  {
    val org = createOrganization()
    val project1 = createProject(org)
    val client = identifiedClient(UserReference(systemUser.id))
    val x: Seq[io.flow.dependency.v0.models.Project] = await(client.projects.get(id = Option(project1.id)))
//    println("###" + x)
    x.map(_.id) must contain theSameElementsAs Seq(project1.id)

  }

  "GET /projects by id that does not exist" in  {
    await(
      identifiedClient().projects.get(id = Option(UUID.randomUUID.toString))
    ).map(_.id) must be(Nil)
  }

} 
Example 198
Source File: LibraryArtifactProviderSpec.scala    From dependency   with MIT License 5 votes vote down vote up
package io.flow.dependency.api.lib

import java.util.UUID

import io.flow.dependency.v0.models.{Library, OrganizationSummary}
import util.DependencySpec

class LibraryArtifactProviderSpec extends DependencySpec {

  def makeLibrary(
    groupId: String = UUID.randomUUID.toString,
    artifactId: String = UUID.randomUUID.toString
  ): Library = {
    Library(
      id = UUID.randomUUID.toString,
      organization = orgSummary,
      groupId = groupId,
      artifactId = artifactId,
      resolver = makeResolverSummary()
    )
  }

  private[this] lazy val provider = init[DefaultLibraryArtifactProvider]
  private[this] lazy val orgSummary = OrganizationSummary(
    id = UUID.randomUUID.toString,
    key = s"z-test-${UUID.randomUUID.toString.toLowerCase}"
  )

  "parseUri" in {
    val library = makeLibrary(groupId = "com.github.tototoshi", artifactId = "scala-csv")
    val resolution = provider.resolve(organizationId = orgSummary.id, groupId = library.groupId, artifactId = library.artifactId).getOrElse {
      sys.error("Could not find scala-csv library")
    }
    resolution.versions.find { v =>
      v.tag.value == "1.2.2" && v.crossBuildVersion.map(_.value).contains("2.11")
    }.map(_.tag.value) must be(Some("1.2.2"))
  }

  "swagger" in {
    val library = makeLibrary(groupId = "io.swagger", artifactId = "swagger-parser")
    val resolution = provider.resolve(organizationId = orgSummary.id, groupId = library.groupId, artifactId = library.artifactId).getOrElse {
      sys.error("Could not find swagger-parser library")
    }
    val tags = resolution.versions.map(_.tag.value)
    tags.contains("1.0.4") must be(true)
    tags.contains("1.0.13") must be(true)
    tags.contains("0.0.139") must be(false)
  }

} 
Example 199
Source File: Factories.scala    From dependency   with MIT License 5 votes vote down vote up
package util

import java.util.UUID

import io.flow.dependency.v0.models.{OrganizationSummary, ProjectSummary, ResolverSummary, Visibility}

trait Factories {

  def makeName(): String = {
    s"Z Test ${UUID.randomUUID.toString}"
  }

  def makeKey(): String = {
    s"z-test-${UUID.randomUUID.toString.toLowerCase}"
  }

  def makeOrganizationSummary(
    id: String = UUID.randomUUID.toString,
    key: String = makeKey()
  ) = OrganizationSummary(
    id = id,
    key = key
  )

  def makeProjectSummary(
    id: String = UUID.randomUUID.toString,
    org: OrganizationSummary = makeOrganizationSummary(),
    name: String = makeName()
  ) = ProjectSummary(
    id = id,
    organization = org,
    name = name
  )

  def makeResolverSummary(
    id: String = UUID.randomUUID.toString,
    org: OrganizationSummary = makeOrganizationSummary(),
  ) = ResolverSummary(
    id = id,
    organization = Some(org),
    visibility = Visibility.Private,
    uri = "http://" + makeKey() + ".test.flow.io"
  )

} 
Example 200
Source File: TransactionActor.scala    From changestream   with MIT License 5 votes vote down vote up
package changestream.actors

import java.util.UUID

import akka.actor.{ Actor, ActorRef, ActorRefFactory }
import changestream.events.MutationWithInfo

import changestream.events._
import kamon.Kamon
import org.slf4j.LoggerFactory

class TransactionActor(getNextHop: ActorRefFactory => ActorRef) extends Actor {
  protected val log = LoggerFactory.getLogger(getClass)
  protected val batchSizeMetric = Kamon.histogram("changestream.binlog_event.row_count")
  protected val transactionSizeMetric = Kamon.histogram("changestream.transaction.row_count")

  protected val nextHop = getNextHop(context)

  
  protected var mutationCount: Long = 1
  protected var currentGtid: Option[String] = None
  protected var previousMutation: Option[MutationWithInfo] = None

  def receive = {
    case BeginTransaction =>
      log.debug("Received BeginTransacton")
      mutationCount = 1
      currentGtid = Some(UUID.randomUUID.toString)
      previousMutation = None

    case Gtid(guid) =>
      log.debug("Received GTID for transaction: {}", guid)
      currentGtid = Some(guid)

    case event: MutationWithInfo =>
      log.debug("Received Mutation for tableId: {}", event.mutation.tableId)
      batchSizeMetric.record(event.mutation.rows.length)

      currentGtid match {
        case None =>
          nextHop ! event
        case Some(gtid) =>
          previousMutation.foreach { mutation =>
            log.debug("Adding transaction info and forwarding to the {} actor.", nextHop.path.name)
            nextHop ! mutation
          }
          previousMutation = Some(event.copy(
            transaction = Some(TransactionInfo(
              gtid = gtid,
              currentRow = mutationCount
            ))
          ))
          mutationCount += event.mutation.rows.length
      }

    case CommitTransaction(position) =>
      log.debug("Received Commit with position {}", position)
      previousMutation.foreach { mutation =>
        log.debug("Adding transaction info and forwarding to the {} actor.", nextHop.path.name)
        nextHop ! mutation.copy(
          transaction = mutation.transaction.map { txInfo =>
            txInfo.copy(lastMutationInTransaction = true)
          },
          // TODO: this is unfortunate... because we are now essentially saving the "last safe position" we are guaranteed to replay events when we shut down un-gracefully
          nextPosition = mutation.nextPosition.split(":")(0) + ":" + position.toString
        )
      }
      transactionSizeMetric.record(mutationCount)
      mutationCount = 1
      currentGtid = None
      previousMutation = None

    case RollbackTransaction =>
      log.debug("Received Rollback")

      // TODO: this probably doesn't work for mysql configurations that send a rollback event (vs only sending committed events).. consider removing the rollback handling
      previousMutation.foreach { mutation =>
        log.debug("Adding transaction info and forwarding to the {} actor.", nextHop.path.name)
        nextHop ! mutation.copy(
          transaction = mutation.transaction.map { txInfo =>
            txInfo.copy(lastMutationInTransaction = true)
          }
        )
      }
      transactionSizeMetric.record(mutationCount)
      mutationCount = 1
      currentGtid = None
      previousMutation = None
  }
}