Skip to content

Instantly share code, notes, and snippets.

@vnktsh
Created November 25, 2015 03:10
Show Gist options
  • Save vnktsh/cd3ea020d81f5f82febd to your computer and use it in GitHub Desktop.
Save vnktsh/cd3ea020d81f5f82febd to your computer and use it in GitHub Desktop.
package main.scala.spray.server.actor.service.impl
import scala.collection.mutable.Map
import akka.actor.Actor
import akka.actor.ActorRef
import spray.json._
import spray.can.Http
import spray.http._
import spray.util._
import spray.http.HttpHeaders._
import HttpMethods._
import MediaTypes._
//111import spray.http.ContentTypes._
import DefaultJsonProtocol._
import main.scala.common._
//
class RequestListenerService(name: String, localAddress: String, localAkkaMessagePort: Int, akkaServerAddress: String, akkaServerPort: Int, followers: Array[Int], requestMap: Map[String, ActorRef]) extends Actor {
val selfPath = "akka.tcp://SprayServer@" + localAddress + ":" + localAkkaMessagePort + "/user/" + name
val akkaServerPath = "akka.tcp://AkkaServer@" + akkaServerAddress + ":" + akkaServerPort + "/user/"
def receive = {
case _: Http.Connected => sender ! Http.Register(self)
//Sample request
case HttpRequest(GET, Uri.Path("/"), _, _, _) =>
sender ! index
case HttpRequest(GET, Uri.Path("/ping"), _, _, _) =>
sender ! HttpResponse(entity = "PONG!")
case HttpRequest(POST, Uri.Path(path), header, entity, protocol) if path startsWith "/ping" =>
println("PING")
val args: Array[String] = path.split("/")
println(header)
val payload = entity.asString
println(payload)
val jsonPayload = payload.asJson
val map = jsonPayload.convertTo[scala.collection.immutable.Map[String, String]] //Either[String, List[String]]]]
val value = map.get("text").get
println(value)
sender ! HttpResponse(entity = HttpEntity(`application/json`, """{ received : """ + value + """}"""))
//USER REGISTRATION
//Register single user to akka server
case HttpRequest(POST, Uri.Path(path), header, entity, protocol) if path startsWith "/registeruser" =>
val args: Array[String] = path.split("/")
val userName = args(2)
var done = false
var uuid: String = ""
while (!done) {
uuid = java.util.UUID.randomUUID().toString()
if (requestMap.get(uuid) == None) {
requestMap += uuid -> sender
done = true
}
}
//send request to akka server
val akkaServer = context.actorSelection(akkaServerPath + "UserRegistrationRouter")
akkaServer ! RegisterUser(uuid, userName, selfPath)
case Complete(requestUUID: String) =>
requestMap.remove(requestUUID).get ! HttpResponse()
//Register multiple users to akka server
case HttpRequest(POST, Uri.Path(path), header, entity, protocol) if path startsWith "/userregistration" =>
val payloadMap = entity.asString.asJson.convertTo[scala.collection.immutable.Map[String, String]]
val ip = payloadMap.get("ip").get
val clients = payloadMap.get("clients").get.toInt
//val clientFactoryPath = payloadMap.get("clientFactoryPath").get
val sampleSize = payloadMap.get("sampleSize").get.toInt
val peakActorName = payloadMap.get("peakActorName").get
val peakActorFollowersCount = payloadMap.get("peakActorFollowersCount").get.toInt
var done = false
var uuid: String = ""
while (!done) {
uuid = java.util.UUID.randomUUID().toString()
if (requestMap.get(uuid) == None) {
requestMap += uuid -> sender
done = true
}
}
//send request to akka server
val akkaServer = context.actorSelection(akkaServerPath + "UserRegistrationRouter")
akkaServer ! RegisterUsers(uuid, ip, clients, selfPath, followers, sampleSize, peakActorName, peakActorFollowersCount)
case Start(requestUUID: String) =>
requestMap.remove(requestUUID).get ! HttpResponse()
//TWEET SERVICES
//POST Update
case HttpRequest(POST, Uri.Path(path), header, entity, protocol) if path startsWith "/tweet/update" =>
println("Tweet")
val args: Array[String] = path.split("/")
val service = args(1)
val endPoint = "POST" + args(2)
val userName = args(3)
val payloadMap = entity.asString.asJson.convertTo[scala.collection.immutable.Map[String, String]]
val tweetText = payloadMap.get("text").get
var done = false
var uuid: String = ""
while (!done) {
uuid = java.util.UUID.randomUUID().toString()
if (requestMap.get(uuid) == None) {
requestMap += uuid -> sender
done = true
}
}
//send request to akka server
val akkaServer = context.actorSelection(akkaServerPath + "TweetsServiceRouter")
akkaServer ! new AkkaRequest(uuid, selfPath, endPoint, userName, "", tweetText)
//POST Update Response from akka server
case PostUpdateResponse(requestUUID: String) =>
requestMap.remove(requestUUID).get ! HttpResponse()
//TIMELINE SERVICES
//GET Usertimeline Request to akka server
case HttpRequest(GET, Uri.Path(path), header, entity, protocol) if path startsWith "/timeline/usertimeline" =>
val args: Array[String] = path.split("/")
val service = args(1)
val endPoint = "GET" + args(2)
val userName = args(3)
var done = false
var uuid: String = ""
while (!done) {
uuid = java.util.UUID.randomUUID().toString()
if (requestMap.get(uuid) == None) {
requestMap += uuid -> sender
done = true
}
}
val akkaRequest = new AkkaRequest(uuid, selfPath, endPoint, userName, "", "")
val akkaServer = context.actorSelection(akkaServerPath + "TimelineServiceRouter")
akkaServer ! akkaRequest
//Response from akka server for Usertimeline
case LoadUserTimelineResp(requestUUID: String, tweets: Map[String, String]) =>
requestMap.remove(requestUUID).get ! HttpResponse(entity = HttpEntity(`application/json`, """{ received : """ + tweets + """}"""))
//GET Hometimeline Request to akka server
case HttpRequest(GET, Uri.Path(path), header, entity, protocol) if path startsWith "/timeline/hometimeline" =>
val args: Array[String] = path.split("/")
val service = args(1)
val endPoint = "GET" + args(2)
val userName = args(3)
var done = false
var uuid: String = ""
while (!done) {
uuid = java.util.UUID.randomUUID().toString()
if (requestMap.get(uuid) == None) {
requestMap += uuid -> sender
done = true
}
}
val akkaRequest = new AkkaRequest(uuid, selfPath, endPoint, userName, "", "")
val akkaServer = context.actorSelection(akkaServerPath + "TimelineServiceRouter")
akkaServer ! akkaRequest
//Response from akka server for Hometimeline
case LoadHomeTimelineResp(requestUUID: String, tweets: Map[String, String]) =>
requestMap.remove(requestUUID).get ! HttpResponse(entity = HttpEntity(`application/json`, """{ received : """ + tweets + """}"""))
}
lazy val index = HttpResponse(
entity = HttpEntity(`text/html`,
<html>
<body>
<h1>Say hello to <i>spray-can</i>!</h1>
<p>Defined resources:</p>
<ul>
<li><a href="/ping">/ping</a></li>
<li><a href="/stream">/stream</a></li>
<li><a href="/server-stats">/server-stats</a></li>
<li><a href="/crash">/crash</a></li>
<li><a href="/timeout">/timeout</a></li>
<li><a href="/timeout/timeout">/timeout/timeout</a></li>
<li><a href="/stop">/stop</a></li>
</ul>
<p>Test file upload</p>
<form action ="/file-upload" enctype="multipart/form-data" method="post">
<input type="file" name="datafile" multiple=""></input>
<br/>
<input type="submit">Submit</input>
</form>
</body>
</html>.toString()
)
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment