Friday, 6 March 2015

Reading VCAP_SERVICES Postgresql service credentials within Bluemix

The following shows how you can easily read the VCAP_SERVICES postgresql credentials within your Java Code using the maven repo. This assumes your using the ElephantSQL Postgresql service. A single connection won't be ideal but for demo purposes might just be all you need.

1. First add the maven dependency as follows. This will add WebSphere Application Server Liberty Profile to your project

  
<dependency>
        <groupId>com.ibm.tools.target</groupId>
        <artifactId>was-liberty</artifactId>
        <version>LATEST</version>
        <type>pom</type>
        <scope>provided</scope>
</dependency>

2. In your code , something as follows gets you the Connection details to make a JDBC connection withinyou java code.
  
private static Connection getConnection() throws Exception 
{
 Map<String, String> env = System.getenv();
 
 if (env.containsKey("VCAP_SERVICES")) {

  JSONObject vcap = (JSONObject) JSON.parse(env.get("VCAP_SERVICES"));
  JSONObject service = null;
  
  // We don't know exactly what the service is called,
  // but it will contain "elephantsql"
  for (Object key : vcap.keySet()) {
   String keyStr = (String) key;
   if (keyStr.toLowerCase().contains("elephantsql")) {
    service = (JSONObject) ((JSONArray) vcap.get(keyStr)).get(0);
    break;
   }
  }
  
  if (service != null) {
   JSONObject creds = (JSONObject) service.get("credentials");
   URI uri = URI.create((String) creds.get("uri"));
   String url = "jdbc:postgresql://" + uri.getHost() + ":" +
            uri.getPort() +
            uri.getPath();
   String username = uri.getUserInfo().split(":")[0];
   String password = uri.getUserInfo().split(":")[1];
   return DriverManager.getConnection(url, username, password);
  }
 }
 
 throw new Exception("No ElephantSQL service URL found. Make sure you " +
      "have bound the correct services to your app.");
}

No comments: