Skip to content

Instantly share code, notes, and snippets.

@ramn
Created November 3, 2014 21:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ramn/9c64827a105a2519b584 to your computer and use it in GitHub Desktop.
Save ramn/9c64827a105a2519b584 to your computer and use it in GitHub Desktop.
Scala sys.process example, reading bytes back (create png from Dot)
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