JamesB
JamesB

Reputation: 529

java.lang.NullPointerException at java.net.URI$Parser.parse

I would like to connect to a Heroku Database and I tried to replicate the model like their tutorial: https://devcenter.heroku.com/articles/connecting-to-relational-databases-on-heroku-with-java#using-the-jdbc_database_url

When below line is executed

URI dbUri = new URI(System.getenv("postgresql://osnvehqhufnxzr:TS3Qt37c_HHbGRNKw3yk7g88fp@ec2-54-225-93-34.compute-1.amazonaws.com:5432/d39mfq0odt56bv?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory"));

I am getting the error

java.lang.NullPointerException
    at java.net.URI$Parser.parse(Unknown Source)
    at java.net.URI.<init>(Unknown Source)

How is this caused and how can I solve it?

Upvotes: 1

Views: 5759

Answers (1)

Mark Olsson
Mark Olsson

Reputation: 320

When you create the URI object, you're using System.getenv(), which attempts to get the value for a system environment variable called "postgresql://osnvehq...", which most certainly does not exist and was not your intention. Remove the System.getenv() and just use the url string.

Suggestion: Before the return with the connection, you might put in a few System.out.println() statements with your variables and check the console output to make sure the URL, username, and password is being extracted correctly from the URI.

Also, please say those aren't the real user and password to your database which are now exposed to the whole world... If those are real, you need to change them immediately - not here on SO, that cat is out of the bag already, change it in your actual database.

EDIT: Ok, I just looked at the heroku link, and what that tutorial is telling you is to use new URI(System.getenv("DATABASE_URL")) and leave the DATABASE_URL part as-is. That's an environment variable what will contain the actual connection information.

Upvotes: 2

Related Questions