Skip to content

Commit

Permalink
Adding http
Browse files Browse the repository at this point in the history
  • Loading branch information
sbarbernephila committed Nov 15, 2016
1 parent a1ae6aa commit acb9b25
Show file tree
Hide file tree
Showing 6 changed files with 642 additions and 127 deletions.
555 changes: 489 additions & 66 deletions AkkaHttp/.idea/workspace.xml

Large diffs are not rendered by default.

14 changes: 8 additions & 6 deletions AkkaHttp/README.txt
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
Good example
chat

https://github.com/dnvriend/akka-http-test
http://www.diversit.eu/2015/07/using-akka-http-to-perform-rest-call.html
http://alexkuang.com/blog/2016/04/26/writing-an-api-client-with-akka-http/
https://markatta.com/codemonkey/blog/2016/04/18/chat-with-akka-http-websockets/
https://markatta.com/codemonkey/blog/2016/10/02/chat-with-akka-http-websockets/

POST
http://stackoverflow.com/questions/32757605/idiomatic-way-to-create-a-basic-http-post-request-with-akka-http

TESTING WEB SOCKET STUFF

1. Run server
2. Browse to ChatTestClient.Html in browser
3. Open Postman to http://localhost:8080/dowork this should send some responses to the websocket client opened in browser
54 changes: 3 additions & 51 deletions AkkaHttp/clientside/src/main/scala-2.11/Demo.scala
Original file line number Diff line number Diff line change
@@ -1,56 +1,8 @@
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model._
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.ActorMaterializer
import akka.stream.scaladsl._
import scala.concurrent.{Await, Future}
import concurrent.ExecutionContext.Implicits.global
import common.{Item, JsonSupport}
import concurrent.duration._
import scala.io.StdIn

object Demo extends App with JsonSupport {

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

val httpClient = Http().outgoingConnection(host = "localhost", port = 8080)

//+++++++++++++++++++++++++++++++++++++++++++++++
// GET http://localhost:8080/randomitem
//+++++++++++++++++++++++++++++++++++++++++++++++
val randomItemUrl = s"""/randomitem"""
private val flowGet : Future[Item] =
Source.single(HttpRequest(method = HttpMethods.GET,uri = Uri(randomItemUrl)))
.via(httpClient)
.mapAsync(1)(response => Unmarshal(response.entity).to[Item])
.runWith(Sink.head)
val start = System.currentTimeMillis()
val result = Await.result(flowGet, 5 seconds)
val end = System.currentTimeMillis()
println(s"Result in ${end-start} millis: $result")


//+++++++++++++++++++++++++++++++++++++++++++++++
// POST http://localhost:8080/saveitem
//+++++++++++++++++++++++++++++++++++++++++++++++
val saveItemUrl = s"""/saveitem"""
val itemToSave = Item("newItemHere",12)
val flowPost = for {
requestEntity <- Marshal(itemToSave).to[RequestEntity]
response <-
Source.single(HttpRequest(method = HttpMethods.POST,uri = Uri(saveItemUrl), entity = requestEntity))
.via(httpClient)
.mapAsync(1)(response => Unmarshal(response.entity).to[Item])
.runWith(Sink.head)
} yield response
val startPost = System.currentTimeMillis()
val resultPost = Await.result(flowPost, 5 seconds)
val endPost = System.currentTimeMillis()
println(s"Result in ${endPost-startPost} millis: $resultPost")

object Demo extends App {

val regularRoutesDemo = new RegularRoutesDemo()
regularRoutesDemo.Run()
StdIn.readLine()
}
64 changes: 64 additions & 0 deletions AkkaHttp/clientside/src/main/scala-2.11/RegularRoutesDemo.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model._
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.ActorMaterializer
import akka.stream.scaladsl._
import scala.concurrent.{Await, Future}
import concurrent.ExecutionContext.Implicits.global
import common.{Item, JsonSupport}
import concurrent.duration._
import scala.io.StdIn

class RegularRoutesDemo extends JsonSupport {

def Run() : Unit = {
implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()

val httpClient = Http().outgoingConnection(host = "localhost", port = 8080)

//+++++++++++++++++++++++++++++++++++++++++++++++
// GET http://localhost:8080/randomitem
//+++++++++++++++++++++++++++++++++++++++++++++++
val randomItemUrl = s"""/randomitem"""
val flowGet : Future[Item] =
Source.single(
HttpRequest(
method = HttpMethods.GET,
uri = Uri(randomItemUrl))
)
.via(httpClient)
.mapAsync(1)(response => Unmarshal(response.entity).to[Item])
.runWith(Sink.head)
val start = System.currentTimeMillis()
val result = Await.result(flowGet, 5 seconds)
val end = System.currentTimeMillis()
println(s"Result in ${end-start} millis: $result")


//+++++++++++++++++++++++++++++++++++++++++++++++
// POST http://localhost:8080/saveitem
//+++++++++++++++++++++++++++++++++++++++++++++++
val saveItemUrl = s"""/saveitem"""
val itemToSave = Item("newItemHere",12)
val flowPost = for {
requestEntity <- Marshal(itemToSave).to[RequestEntity]
response <-
Source.single(
HttpRequest(
method = HttpMethods.POST,
uri = Uri(saveItemUrl),
entity = requestEntity)
)
.via(httpClient)
.mapAsync(1)(response => Unmarshal(response.entity).to[Item])
.runWith(Sink.head)
} yield response
val startPost = System.currentTimeMillis()
val resultPost = Await.result(flowPost, 5 seconds)
val endPost = System.currentTimeMillis()
println(s"Result in ${endPost-startPost} millis: $resultPost")
}
}
46 changes: 42 additions & 4 deletions AkkaHttp/serverside/src/main/scala-2.11/Demo.scala
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
import akka.NotUsed
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.http.scaladsl.server.Directives
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Flow
import common.{Item, JsonSupport}
import scala.io.StdIn
import scala.concurrent.Future
import akka.http.scaladsl.model.ws.{Message, TextMessage}
import akka.stream._
import akka.stream.scaladsl._


object Demo extends App with Directives with JsonSupport {

Expand All @@ -14,6 +20,19 @@ object Demo extends App with Directives with JsonSupport {
// needed for the future flatMap/onComplete in the end
implicit val executionContext = system.dispatcher



val (websocketSink, websocketSource) =
MergeHub.source[String].toMat(BroadcastHub.sink[String])(Keep.both).run()

val websocketFlow: Flow[Message, Message, NotUsed] =
Flow[Message].mapAsync(1) {
// transform websocket message to domain message (string)
case TextMessage.Strict(text) => Future.successful(text)
case streamed: TextMessage.Streamed => streamed.textStream.runFold("")(_ ++ _)
}.via(Flow.fromSinkAndSource(websocketSink, websocketSource))
.map[Message](string => TextMessage(string))

val route =
path("hello") {
get {
Expand All @@ -34,15 +53,34 @@ object Demo extends App with Directives with JsonSupport {
complete(item)
}
}
} ~
path("websocket") {
get {
handleWebSocketMessages(websocketFlow)
}
} ~
path("sendmessagetowebsocket" / IntNumber) { msgCount =>
post {
for(i <- 0 until msgCount)
{
Source.single(s"sendmessagetowebsocket $i").runWith(websocketSink)
}
complete("done")
}
}

val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)

val (host, port) = ("localhost", 8080)
val bindingFuture = Http().bindAndHandle(route, host, port)

bindingFuture.onFailure {
case ex: Exception =>
println(s"$ex Failed to bind to $host:$port!")
}

println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
StdIn.readLine() // let it run until user presses return
bindingFuture
.flatMap(_.unbind()) // trigger unbinding from the port
.onComplete(_ => system.terminate()) // and shutdown when done


}
36 changes: 36 additions & 0 deletions AkkaHttp/serverside/src/main/scala-2.11/WebSocketTestClient.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.3.min.js"
integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo="
crossorigin="anonymous"></script>
<title>Chat</title>
</head>
<body>
<textarea id="message"></textarea>
<button id="send">Send</button>
<ul id="messages"></ul>


<script language="javascript">
var $messages = $("#messages"),
$send = $("#send"),
$message = $("#message"),
connection = new WebSocket('ws://localhost:8080/websocket')
$send.prop("disabled",true)
connection.onopen = function () {
$send.prop("disabled",false)
$messages.prepend($("<li>Connected</li>"))
$send.on('click', function() {
var text = $message.val()
$message.val("")
connection.send(text)
})
}
connection.onerror = function (error) { console.log('WebSocket Error ', error) }
connection.onmessage = function (event) {
$messages.prepend($("<li>" + event.data + "</li>"))
}
</script>
</body>
</html>
Contact GitHub

0 comments on commit acb9b25

Please sign in to comment.