Heroku Connect with Java Spark Framework

This article shows how to run Java Spark Framework based application with Heroku Connect.


Figure 1 : Heroku-Connect Data flow

Figure 1 show the how HerokuConnect Add-On interacts with Heroku Postgres and force.com behind the scenes

Running Locally

Make sure you have Java and Maven installed. Also, install the Heroku Toolbelt

$ git clone https://github.com/rajdeepd/heroku-connect-java-spark-sample
$ cd heroku-connect-java-spark-sample
$ mvn install
$ foreman start web

Your app should now be running on localhost:5000

If you’re going to use a database, ensure you have a local .env file that reads something like this:


Deploying to Heroku

$ heroku create
$ git push heroku master
$ heroku open

Adding Heroku Connect Add-On

Configure Heroku Connect Add-On. Command below configures Herok-Connect Add-On to the application.

$ heroku addons:create herokuconnect

Configure Herok Connect Add-On

  1. Setup Connection
  1. Enter Schema Name : This is the schema name underwhich database will be created.
  1. Trigger OAuth
  1. Enter Salesforce.com developer account credentials
  1. Create Mappings
  1. Create Mappings Contacts : Choose the fields in Salesforce Schema which need to be mapped to Postgres Database in the application.
  1. Explore Contacts in the Dashboard

Code for getting contacts

/contacts rest endpoint is tied to getting list of names from salesforce.contact and populating contacts.ftl.

get("/contacts", (req, res) -> {
       Connection connection = null;
       Map<String, Object> attributes = new HashMap<>();
       try {
         connection = DatabaseUrl.extract().getConnection();
         Statement stmt = connection.createStatement();

         ResultSet rs = stmt.executeQuery("SELECT name FROM salesforce.contact");

         ArrayList<String> output = new ArrayList<String>();
         while (rs.next()) {
           output.add( rs.getString("name"));
         attributes.put("results", output);
         return new ModelAndView(attributes, "contacts.ftl");
       } catch (Exception e) {
         attributes.put("message", "There was an error: " + e);
         return new ModelAndView(attributes, "error.ftl");
       } finally {
         if (connection != null) try{connection.close();} catch(SQLException e){}
     }, new FreeMarkerEngine());

Corresponding contacts.ftl file which is used to display html.

<!DOCTYPE html>
<#include "header.ftl">
<#include "nav.ftl">
<div class="container">
<#list results as x>
<li> ${x} </li>

Show Contacts

Browse to URL http://{your-app-name}.herokuapp.com/contacts to see the list of contact names.



In this tutorial we learnt how to configure a Spark Java Application to work with Heroku Connect.