Processes, Networking and HTTP

37.1 Running External Processes

def out = "git --version".execute().text
println out
def proc = ["ls", "-la"].execute()
proc.waitFor()
println "exit: ${proc.exitValue()}\n${proc.in.text}"
def p = "grep groovy".execute() 
p.withWriter { it << "groovy rocks\njava\n" }
println p.text
def chained = "ps aux".execute() | "grep java".execute()        // pipe processes
chained.waitFor()
def sout = new StringBuilder(), serr = new StringBuilder()
def pr = "mvn -v".execute()
pr.consumeProcessOutput(sout, serr)
pr.waitForOrKill(10_000)
def withEnv = "printenv MY_VAR".execute(["MY_VAR=1"], new File("."))

37.2 HTTP

Libraries: http-builder-ng (Groovy DSL HTTP client), OkHttp, Apache HttpClient 5, Micronaut HTTP client.

// GDK URL helpers
def body = new URL("https://httpbin.org/get").getText(connectTimeout: 5000, readTimeout: 5000, requestProperties: [Accept: "application/json"])

// JDK 11+ HttpClient
import java.net.http.*
def client = HttpClient.newHttpClient()
def req = HttpRequest.newBuilder(URI.create("https://httpbin.org/post"))
    .header("Content-Type", "application/json")
    .POST(HttpRequest.BodyPublishers.ofString('{"a":1}'))
    .build()
def resp = client.send(req, HttpResponse.BodyHandlers.ofString())
println resp.statusCode()
println new groovy.json.JsonSlurper().parseText(resp.body()).json

37.3 Sockets

def server = new ServerSocket(9000)
Thread.start {
    server.accept { socket ->
        socket.withStreams { input, output ->
            def line = input.newReader().readLine()
            output << "echo: $line\n"
        }
    }
}
new Socket("localhost", 9000).withStreams { input, output ->
    output << "hello\n"
    println input.newReader().readLine()
}