Created
November 3, 2014 21:52
-
-
Save ramn/9c64827a105a2519b584 to your computer and use it in GitHub Desktop.
Scala sys.process example, reading bytes back (create png from Dot)
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.ByteArrayInputStream | |
import java.io.ByteArrayOutputStream | |
import scala.sys.process._ | |
import scala.concurrent.ExecutionContext.Implicits.global | |
import scala.concurrent.Future | |
import scala.concurrent.blocking | |
import scala.concurrent.Await | |
import scala.concurrent.duration._ | |
val dot = """ | |
graph { | |
node [shape=box3d]; | |
a [color=green]; | |
a -- b; | |
a -- c; | |
b -- c; | |
a -- e; | |
f -- g [color=red]; | |
} | |
""" | |
case class Dot(code: String) { | |
def getBytes: Array[Byte] = code.getBytes | |
} | |
def buildGraph(dot: Dot): Future[Array[Byte]] = { | |
val outStream = new ByteArrayOutputStream | |
val inStream = new ByteArrayInputStream(dot.getBytes) | |
val procBuilder = Seq("dot", "-T", "png") #< inStream #> outStream | |
val exitcodeFut = Future { blocking { procBuilder.! } } | |
exitcodeFut.map { _ => | |
inStream.close | |
outStream.close | |
outStream.toByteArray | |
} | |
} | |
val pngData: Array[Byte] = Await.result(buildGraph(Dot(dot)), 10.seconds) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment