0

We're working on deploying a Java project to Heroku that uses MongoDB. According to the Heroku docs, the DB connection parameters are read from an environment variable, MONGOHQ_URL. When I run the project in Netbeans on my laptop, how do I set this variable?

I tried adding it as a VM option with -DMONGOHQ_URL=... in Run -> Set Project Configuration -> Customize -> Run and as well in Actions -> Run project and Run file via main(), but to no avail. When the program reads it with System.getvar it's not set.

Wolfram Arnold
  • 7,159
  • 5
  • 44
  • 64
  • 1
    You could switch from using env vars to using Java system properties and just pass the env vars into system properties when you run on Heroku. – James Ward Apr 17 '12 at 18:04
  • @JamesWard thanks. How do I set a Java system property? – Wolfram Arnold Apr 17 '12 at 18:14
  • That depends on how you are starting your app on Heroku. But it will likely be adding something like the following to your Procfile: `-Dmongourl=${MONGOHQ_URL}` – James Ward Apr 18 '12 at 09:28
  • I'm just following the tutorial using MongoHQ. That wasn't the problem. The problem was to be able to continue running the app locally. – Wolfram Arnold Apr 18 '12 at 16:44
  • 1
    What I meant is that you could use only a Java system property in your code and then set it from an env var on Heroku and from a launch config in NetBeans. – James Ward Apr 18 '12 at 23:14
  • Got it. That's what I ended up doing in my solution below. Thanks again. – Wolfram Arnold Apr 21 '12 at 14:29

2 Answers2

0

You can set it in your netbeans.conf file. Add the line:

export MONGOHQ_URL=...

There's an example here: http://sunng.info/blog/2009/12/setting-environment-variables-for-netbeans/.

kris
  • 23,024
  • 10
  • 70
  • 79
  • Thanks. There is no way to set this on a per-project basis? I don't want this to be a global setting for all NetBeans apps. – Wolfram Arnold Apr 17 '12 at 19:01
0

Ok, I figured it out. This may be obvious to Java coders, but I'm not one, so here is what I cobbled together.

    String mongo_url = System.getenv("MONGOHQ_URL");
    // If env var not set, try reading from Java "system properties"
    if (mongo_url == null) {
        mongo_url = System.getProperty("MONGOHQ_URL");
    }

    MongoURI mongoURI = new MongoURI(mongo_url);
    this.db = mongoURI.connectDB();

    // Only authenticate if username or password provided
    if (!"".equals(mongoURI.getUsername()) || mongoURI.getPassword().length > 0) {
        Boolean success = this.db.authenticate(mongoURI.getUsername(), mongoURI.getPassword());  

        if (!success) {
            System.out.println("MongoDB Authentication failed");
            return;
        }
    }
    this.my_collection = db.getCollection("my_collection");
Wolfram Arnold
  • 7,159
  • 5
  • 44
  • 64