SQL and HTTP

Two parts of a real program need something outside the language: a database needs a JDBC driver, and an HTTP client needs a server and a network. This image has neither, so the lesson shows the API and the real failure it meets here, which is the honest starting point of both.

groovy.sql and a missing driver

Sql.newInstance takes a JDBC URL and the driver class. The jar is not in this image, so the call fails before it reaches a database:

sql.groovy

import groovy.sql.Sql def sql = Sql.newInstance('jdbc:sqlite::memory:', '', '', 'org.sqlite.JDBC') println sql.firstRow('select 1 as one')

groovy sql.groovy

Caught: java.lang.ClassNotFoundException: org.sqlite.JDBC
java.lang.ClassNotFoundException: org.sqlite.JDBC
at sql.run(sql.groovy:3)
exit status: 1

The message names the class, not the database: nothing on the class path provides org.sqlite.JDBC. Add the driver jar and the same script connects; with PostgreSQL the class is org.postgresql.Driver and the URL starts with jdbc:postgresql:. The Sql object then has eachRow, execute and withTransaction, all closing the statement for you.

An HTTP client

The shortest client is URL.text, and the modern one is java.net.http.HttpClient. The block below is a fragment, not a program: the course does not run it, because the answer of a remote server changes between runs and the page would show a value no reader can compare with.

http.groovy

class Fetch { static String page(String address) { new URL(address).text } static String status(String address) { def connection = new URL(address).openConnection() as HttpURLConnection connection.requestMethod = 'HEAD' "${connection.responseCode} ${connection.responseMessage}" } }

groovy http.groovy

URL.text is enough for a page, and an HttpURLConnection gives the status line. Neither sets a timeout by default, which is the first thing to add to a real client: without one a request can wait forever. For a JSON API, read the body with JsonSlurper from the JSON lesson.

Related

Article author: Arthur Isaev