How to obtain databse url etc without the heroku C

2019-09-07 18:38发布

问题:

I am using Heroku PostgreSQL in my Java application and obtain the database url, username, database name, and password like so

Properties props = new Properties();
props.setProperty("sslmode","require");
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("heroku config:get DATABASE_URL -a myMegaCoolApplication");
BufferedReader br = new BufferedReader(new InputStreamReader(pr.getInputStream()));
Pattern p = Pattern.compile("(postgres)://([^:]+):([^@]+)@(.*)");
Matcher m = p.matcher(br.readLine());
m.find();
props.setProperty("user",m.group(2));
props.setProperty("password",m.group(3));
conn = DriverManager.getConnection("jdbc:"+m.group(1)+"ql://"+m.group(4),props);

Here one needs to have the heroku tool installed on a local machine. Can I do without it? The goal is to be able to ship the Java jar-file alone, without the requiring the user to install heroku.

回答1:

You can make an HTTP request to the Heroku Platform API to retrieve config vars for an app.

A convenient way to do this is with the heroku.jar client library. For example

HerokuAPI api = new HerokuAPI(apiKey);
Map<String, String> config = api.listConfig("myExistingApp");
for (Map.Entry<String, String> var : config.entrySet()) {
    System.out.println(var.getKey() + "=" + var.getValue());
}