Created
July 26, 2017 07:40
-
-
Save rajeevprasanna/079813d9951da3016828b83f8fd09695 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.{FileInputStream, InputStream} | |
import java.nio.ByteBuffer | |
import java.security.MessageDigest | |
import java.util.concurrent.TimeUnit | |
import akka.actor.ActorSystem | |
import akka.http.scaladsl.Http | |
import akka.http.scaladsl.model.HttpMethods.GET | |
import akka.http.scaladsl.model.{HttpRequest, HttpResponse} | |
import akka.stream.ActorMaterializer | |
import akka.stream.scaladsl.{Sink, StreamConverters} | |
import scala.concurrent.{Await, Future} | |
import scala.concurrent.duration._ | |
object Test extends App { | |
implicit def system:ActorSystem = ActorSystem() | |
implicit def materializer:ActorMaterializer = ActorMaterializer() | |
implicit def executionContext = system.dispatcher | |
//Method 1 : Erring function : | |
def emptyMessageDigest : MessageDigest = MessageDigest getInstance "SHA-256" | |
val updateDigest : (MessageDigest, ByteBuffer) => MessageDigest = | |
(messageDigest, byteBuffer) => { | |
messageDigest update byteBuffer | |
messageDigest | |
} | |
def messageDigestSink : Sink[ByteBuffer, Future[MessageDigest]] = Sink.fold(emptyMessageDigest)(updateDigest) | |
def responseBodyToDigest: HttpResponse => Future[MessageDigest] = (_:HttpResponse).entity.dataBytes.map(_.asByteBuffer).runWith(messageDigestSink) | |
val url = s"https://blog.jdriven.com/wp-content/uploads/2015/04/scala-snippet.png" | |
val result:Future[MessageDigest] = Http().singleRequest(HttpRequest(GET, uri = url)).flatMap(responseBodyToDigest) | |
Await.result(result, 1000.seconds) | |
result.flatMap(x => { | |
println(s"digest ===> ${x.digest}") | |
val d = x.digest() | |
val res = String.format("%064x", new java.math.BigInteger(1, d)) | |
println(res) | |
Future.successful(10) | |
}) | |
//Method 2: Working output | |
def digestx(inStream: InputStream, algorithm: String="SHA-256"): Array[Byte] = { | |
val md = MessageDigest.getInstance(algorithm) | |
val buffer = new Array[Byte](1024) | |
Iterator.continually { inStream.read(buffer) } | |
.takeWhile(_ != -1) | |
.foreach { md.update(buffer, 0, _) } | |
val d = md.digest | |
val res = String.format("%064x", new java.math.BigInteger(1, d)) | |
println(s"hash from method 2 : ${res}") | |
d | |
} | |
val req = Http().singleRequest(HttpRequest(GET, uri = url)).flatMap(resp => { | |
val inputStream: InputStream = resp.entity.dataBytes | |
.runWith( | |
StreamConverters.asInputStream(FiniteDuration(3, TimeUnit.SECONDS)) | |
) | |
digestx(inputStream, "SHA-256") | |
Future.successful(2) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment