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:
Post a Comment