Skip to content

Feature/improving code (#1) #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,7 @@ play-scala

# OSX specific
.DS_Store

loadtest/phantom/results
loadtest/quill/results
logs
70 changes: 35 additions & 35 deletions app/controllers/GroupController.scala
Original file line number Diff line number Diff line change
@@ -1,40 +1,41 @@
package controllers

import java.util.{Locale, UUID}
import java.util.UUID
import javax.inject.Inject

import akka.actor.ActorSystem
import javax.inject._

import com.typesafe.config.ConfigFactory
import db.phantom.model.GroupId
import dto.{ErrorCode, ErrorResponse, GroupResponse, QuillGroupResponse}
import play.api.i18n.Lang

import scala.concurrent.Future
import com.google.inject.Singleton
import db.model.GroupId
import dto.{ErrorCode, ErrorResponse, GroupResponse}
import play.api.libs.json.{JsError, Json}
import play.api.mvc.{Action, AnyContent, Controller}
import services.{GroupIdNotFound, GroupService, RepositoryFailure, QuillGroupService}
import play.api.mvc.{Action, Controller, Results}
import services.{GroupService, QuillGroupService}
import db.model.JsonProtocol._

import scala.annotation.tailrec
import scala.concurrent.ExecutionContext
import scala.concurrent.{ExecutionContext, Future}

class GroupController @Inject()(actorSystem: ActorSystem, service: GroupService, service2: QuillGroupService)(implicit exec: ExecutionContext) extends Controller {
@Singleton
class GroupController @Inject()(
actorSystem: ActorSystem,
service: GroupService,
service2: QuillGroupService
)(implicit exec: ExecutionContext) extends Controller {

val created = Json.obj("status" -> "created")

def getGroup(groupId: UUID) = Action.async { implicit req =>
service.listGroups(groupId)
.map {
case Right(a) =>
Ok(GroupResponse(groupId, a).toJson)
case Left(e) =>
ServiceUnavailable(
ErrorResponse(
ErrorCode.DBServiceNotAvailable,
List(ErrorCode.LookupMsgs(ErrorCode.DBServiceNotAvailable) + " " + e.toString)
).toJson
)
}
service.listGroups(groupId)
.map {
case Right(a) =>
Ok(GroupResponse(groupId, a).asJValue())
case Left(e) =>
Results.BadRequest(
ErrorResponse(
ErrorCode.DBServiceNotAvailable,
List(ErrorCode.LookupMsgs(ErrorCode.DBServiceNotAvailable) + " " + e.toString)
).asJValue()
)
}
}

def saveGroup(groupId: UUID) = Action.async(parse.json) { request =>
Expand All @@ -52,14 +53,13 @@ class GroupController @Inject()(actorSystem: ActorSystem, service: GroupService,
service
.insertGroup(groupIdObj)
.map {
case Right(_) =>
Created(Json.obj("status" -> "created"))
case Right(_) => Created(created)
case Left(e) =>
ServiceUnavailable(
Results.BadRequest(
ErrorResponse(
ErrorCode.ServiceError,
List(ErrorCode.LookupMsgs(ErrorCode.DBServiceNotAvailable) + " " + e.toString)
).toJson
).asJValue()
)
}
})
Expand All @@ -69,19 +69,19 @@ class GroupController @Inject()(actorSystem: ActorSystem, service: GroupService,
service2.listGroups(groupId)
.map {
case Right(a) =>
Ok(QuillGroupResponse(groupId, a).toJson)
Ok(GroupResponse(groupId, a).asJValue())
case Left(e) =>
ServiceUnavailable(
ErrorResponse(
ErrorCode.DBServiceNotAvailable,
List(ErrorCode.LookupMsgs(ErrorCode.DBServiceNotAvailable) + " " + e.toString)
).toJson
).asJValue()
)
}
}

def saveGroup2(groupId: UUID) = Action.async(parse.json) { request =>
request.body.validate[db.quill.model.GroupId].fold({ errors =>
request.body.validate[GroupId].fold({ errors =>
Future.successful(
BadRequest(
Json.obj(
Expand All @@ -96,13 +96,13 @@ class GroupController @Inject()(actorSystem: ActorSystem, service: GroupService,
.insertGroup(quillGroupIdObj)
.map {
case Right(_) =>
Created(Json.obj("status" -> "created"))
Created(created)
case Left(e) =>
ServiceUnavailable(
ErrorResponse(
ErrorCode.ServiceError,
List(ErrorCode.LookupMsgs(ErrorCode.DBServiceNotAvailable) + " " + e.toString)
).toJson
).asJValue()
)
}
})
Expand Down
9 changes: 9 additions & 0 deletions app/db/model/GroupId.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package db.model

import java.util.{Date, UUID}

case class GroupId(
groupId: UUID,
id: UUID,
createTs: Date
)
35 changes: 35 additions & 0 deletions app/db/model/JsonProtocol.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package db.model

import java.text.SimpleDateFormat
import java.util.{Date, TimeZone}

import dto.ErrorCode.ErrorCode
import dto.{EnumerationHelpers, ErrorCode, ErrorResponse, GroupResponse}
import play.api.libs.json._

class JsonProtocol {

implicit lazy val format = Json.format[ErrorResponse]

val sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
sdf.setTimeZone(TimeZone.getTimeZone("UTC"))

implicit lazy val dateFormat: Format[Date] = new Format[Date] {
override def reads(json: JsValue): JsResult[Date] = json.validate[String].filter(_.nonEmpty).map(sdf.parse)

override def writes(o: Date): JsValue = JsString(sdf.format(o))
}

implicit lazy val groupIdFormat: OFormat[GroupId] = Json.format[GroupId]

implicit lazy val groupResponseFormat = Json.format[GroupResponse]

implicit lazy val enumReads: Reads[ErrorCode] = EnumerationHelpers.enumReads(ErrorCode)
implicit lazy val enumWrites: Writes[ErrorCode] = EnumerationHelpers.enumWrites
}

object JsonProtocol extends JsonProtocol {
implicit class JsonHelper[T](val obj: T) extends AnyVal {
def asJValue()(implicit writes: Writes[T]): JsValue = Json.toJson(obj)
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package db.phantom.model
package db.phantom

import java.util.UUID

Expand All @@ -8,16 +8,24 @@ import org.joda.time.DateTime

import scala.concurrent.Future

abstract class GroupIdTable extends CassandraTable[GroupIdTable, GroupId] with RootConnector {
abstract class GroupIdTable extends Table[GroupIdTable, GroupId] {

override def tableName: String = "group_id"

// First the partition key, which is also a Primary key in Cassandra.
object id extends UUIDColumn(this) with PartitionKey
object groupId extends UUIDColumn with PartitionKey {
override lazy val name = "group_id"
}

object id extends UUIDColumn with PrimaryKey {
override lazy val name = "id"
}

// Only keyed fields can be queried on
object groupId extends UUIDColumn(this) with PartitionKey {override lazy val name = "group_id"}
object createTs extends DateTimeColumn(this) with ClusteringOrder {override lazy val name = "create_ts"}

object createTs extends DateColumn with PrimaryKey {
override lazy val name = "create_ts"
}

def findByGroupId(groupId: UUID): Future[List[GroupId]] =
select
Expand All @@ -32,16 +40,6 @@ abstract class GroupIdTable extends CassandraTable[GroupIdTable, GroupId] with R
.consistencyLevel_=(ConsistencyLevel.ONE)
.one()

def save(groupId: GroupId): Future[ResultSet] = {
Console.println("Called Acouunt Entry Id Table save. ")
insert
.value(_.id, groupId.id)
.value(_.groupId, groupId.groupId)
.value(_.createTs, groupId.createTs)
.consistencyLevel_=(ConsistencyLevel.ONE)
.future()
}

def deleteById(groupId: UUID, id: UUID): Future[ResultSet] =
delete
.where(_.groupId eqs groupId)
Expand Down
2 changes: 1 addition & 1 deletion app/db/phantom/connector/Connector.scala
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,6 @@ object Connector {

ContactPoints(hosts)
.withClusterBuilder(builder)
.keySpace(keyspace, autoinit = false)
.keySpace(keyspace, autoinit = true)
}
}
32 changes: 0 additions & 32 deletions app/db/phantom/model/GroupId.scala

This file was deleted.

10 changes: 10 additions & 0 deletions app/db/phantom/package.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package db

import java.util.concurrent.Executors

import scala.concurrent.{ExecutionContext, ExecutionContextExecutor}

package object phantom {

implicit val ctx: ExecutionContextExecutor = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(8))
}
64 changes: 31 additions & 33 deletions app/db/phantom/repository/GroupIdRepository.scala
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
package db.phantom.repository
package db.phantom
package repository

import java.util.UUID

import com.outworkers.phantom.dsl._
import com.outworkers.phantom.connectors.CassandraConnection
import db.phantom.connector.Connector
import db.phantom.model._
import com.outworkers.phantom.dsl._
import com.typesafe.config.ConfigFactory

import java.util.UUID
import db.model._
import db.phantom.connector.Connector

import scala.concurrent.Future

Expand All @@ -24,11 +25,21 @@ trait GroupIdRepo {

}

class GroupIdRepository extends DatabaseProvider[GroupIdDB] with GroupIdRepo {
object GroupDatabase {

private val config = ConfigFactory.load()
private val useSSL: Boolean = config.getBoolean("db.cassandra.ssl")

def database = new GroupIdDB(Connector.connector(useSSL))
val db = new GroupIdDB({
Console.println("Initialising a database")
Connector.connector(useSSL)
})
}


class GroupIdRepository extends DatabaseProvider[GroupIdDB] with GroupIdRepo {

val database = GroupDatabase.db

/**
*
Expand All @@ -46,23 +57,20 @@ class GroupIdRepository extends DatabaseProvider[GroupIdDB] with GroupIdRepo {
.groupIds
.findById(groupId, id)

val saveQuery =
database.groupIds.insert
.p_value(_.groupId, ?)
.p_value(_.id, ?)
.p_value(_.createTs, ?)
.prepare()

/**
*
* @param ae
* @return
*/
def saveEntry(ae: GroupId): Future[Boolean] = {
database
.groupIds
.findById(ae.groupId, ae.id)
.flatMap {
case Some(x) => {
save(ae, false)
}
case None => {
save(ae, true)
}
}
save(ae, isNew = true)
}

/**
Expand All @@ -72,10 +80,7 @@ class GroupIdRepository extends DatabaseProvider[GroupIdDB] with GroupIdRepo {
* @return
*/
def save(gi: GroupId, isNew: Boolean): Future[Boolean] = {
database
.groupIds
.save(gi)
.flatMap (rs => database.groupIds.save(gi).map(_.wasApplied))
saveQuery.bind(gi).future() map (_ => true)
}

/**
Expand All @@ -87,15 +92,8 @@ class GroupIdRepository extends DatabaseProvider[GroupIdDB] with GroupIdRepo {
* @return
*/
def delete(groupId: UUID, id: UUID): Future[Boolean] = {
database
.groupIds
.deleteById(groupId, id)
.flatMap {
case rs => database.
groupIds.
deleteById(groupId, id).map(_.wasApplied())
}
for {
del2 <- database.groupIds.deleteById(groupId, id).map(_.wasApplied())
} yield del2
}


}
Loading