|
| 1 | +import java.io.IOException; |
| 2 | +import javax.servlet.ServletException; |
| 3 | +import javax.servlet.http.*; |
| 4 | +import org.eclipse.jetty.server.Server; |
| 5 | +import org.eclipse.jetty.servlet.*; |
| 6 | +import java.net.URI; |
| 7 | +import java.net.URISyntaxException; |
| 8 | +import java.sql.*; |
| 9 | + |
| 10 | +public class Main extends HttpServlet { |
| 11 | + @Override |
| 12 | + protected void doGet(HttpServletRequest req, HttpServletResponse resp) |
| 13 | + throws ServletException, IOException { |
| 14 | + |
| 15 | + if (req.getRequestURI().endsWith("/db")) { |
| 16 | + showDatabase(req,resp); |
| 17 | + } else { |
| 18 | + showHome(req,resp); |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + private void showHome(HttpServletRequest req, HttpServletResponse resp) |
| 23 | + throws ServletException, IOException { |
| 24 | + resp.getWriter().print("Hello from Java!"); |
| 25 | + } |
| 26 | + |
| 27 | + private void showDatabase(HttpServletRequest req, HttpServletResponse resp) |
| 28 | + throws ServletException, IOException { |
| 29 | + try { |
| 30 | + Connection connection = getConnection(); |
| 31 | + |
| 32 | + Statement stmt = connection.createStatement(); |
| 33 | + stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)"); |
| 34 | + stmt.executeUpdate("INSERT INTO ticks VALUES (now())"); |
| 35 | + ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); |
| 36 | + |
| 37 | + String out = "Hello!\n"; |
| 38 | + while (rs.next()) { |
| 39 | + out += "Read from DB: " + rs.getTimestamp("tick") + "\n"; |
| 40 | + } |
| 41 | + |
| 42 | + resp.getWriter().print(out); |
| 43 | + } catch (Exception e) { |
| 44 | + resp.getWriter().print("There was an error: " + e.getMessage()); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + private Connection getConnection() throws URISyntaxException, SQLException { |
| 49 | + URI dbUri = new URI(System.getenv("DATABASE_URL")); |
| 50 | + |
| 51 | + String username = dbUri.getUserInfo().split(":")[0]; |
| 52 | + String password = dbUri.getUserInfo().split(":")[1]; |
| 53 | + String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath(); |
| 54 | + |
| 55 | + return DriverManager.getConnection(dbUrl, username, password); |
| 56 | + } |
| 57 | + |
| 58 | + public static void main(String[] args) throws Exception{ |
| 59 | + Server server = new Server(Integer.valueOf(System.getenv("PORT"))); |
| 60 | + ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); |
| 61 | + context.setContextPath("/"); |
| 62 | + server.setHandler(context); |
| 63 | + context.addServlet(new ServletHolder(new Main()),"/*"); |
| 64 | + server.start(); |
| 65 | + server.join(); |
| 66 | + } |
| 67 | +} |
0 commit comments