1- import com .heroku .sdk .jdbc .DatabaseUrl ;
1+ import com .zaxxer .hikari .HikariConfig ;
2+ import com .zaxxer .hikari .HikariDataSource ;
23import spark .ModelAndView ;
34import spark .template .freemarker .FreeMarkerEngine ;
45
56import java .sql .Connection ;
67import java .sql .ResultSet ;
7- import java .sql .SQLException ;
88import java .sql .Statement ;
99import java .util .ArrayList ;
1010import java .util .HashMap ;
1414
1515public class Main {
1616
17+ private static HikariDataSource dataSource ;
18+
1719 public static void main (String [] args ) {
1820
1921 port (Integer .valueOf (System .getenv ("PORT" )));
@@ -22,18 +24,22 @@ public static void main(String[] args) {
2224 get ("/hello" , (req , res ) -> "Hello World" );
2325
2426 get ("/" , (request , response ) -> {
25- Map <String , Object > attributes = new HashMap <>();
26- attributes .put ("message" , "Hello World!" );
27+ Map <String , Object > attributes = new HashMap <>();
28+ attributes .put ("message" , "Hello World!" );
29+
30+ return new ModelAndView (attributes , "index.ftl" );
31+ }, new FreeMarkerEngine ());
2732
28- return new ModelAndView (attributes , "index.ftl" );
29- }, new FreeMarkerEngine ());
33+ String jdbcUrl = System .getenv ("JDBC_DATABASE_URL" );
34+ if (jdbcUrl != null ) {
35+ HikariConfig config = new HikariConfig ();
36+ config .setJdbcUrl (jdbcUrl );
37+ dataSource = new HikariDataSource (config );
38+ }
3039
3140 get ("/db" , (req , res ) -> {
32- Connection connection = null ;
3341 Map <String , Object > attributes = new HashMap <>();
34- try {
35- connection = DatabaseUrl .extract ().getConnection ();
36-
42+ try (Connection connection = dataSource .getConnection ()) {
3743 Statement stmt = connection .createStatement ();
3844 stmt .executeUpdate ("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)" );
3945 stmt .executeUpdate ("INSERT INTO ticks VALUES (now())" );
@@ -49,8 +55,6 @@ public static void main(String[] args) {
4955 } catch (Exception e ) {
5056 attributes .put ("message" , "There was an error: " + e );
5157 return new ModelAndView (attributes , "error.ftl" );
52- } finally {
53- if (connection != null ) try {connection .close ();} catch (SQLException e ){}
5458 }
5559 }, new FreeMarkerEngine ());
5660
0 commit comments