简体   繁体   中英

How do I set the MONGOHQ_URL environment variable in the run configuration of Netbeans?

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.

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/ .

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM