Start learning free

LESSON 148 OF 173 · BACKEND: SHIPPING IT

Settings from the Environment

Practice

The shop's code is the same on your computer and on the server, but a few settings differ: the port it listens on, and where the database file is. Don't write them into the code. The server hands them to the program as environment variables: named text values that every program it starts can read.

In Java, System.getenv() gives them as a Map<String, String>. Its getOrDefault(name, default) gives you a variable's text, or the default when it isn't set. The values are always text, so a number needs Integer.parseInt. For example, a program that reads how many times to retry and how to greet:

int retries = Integer.parseInt(System.getenv().getOrDefault("RETRIES", "3"));
String greeting = System.getenv().getOrDefault("GREETING", "Hello");

Your run() prints the settings the server would use. Then the check calls your loadSettings() three times, with different variables set, and prints what it returns:

Port: 8000
Database: shop.db
Nothing set (your computer):
{port=8000, database_path=shop.db}
PORT=5000 and DATABASE_PATH=/data/shop.db (the server):
{port=5000, database_path=/data/shop.db}
Only PORT=10000:
{port=10000, database_path=shop.db}

Your task: above run(), write the static method loadSettings(). It reads PORT as an int, with the default "8000", and DATABASE_PATH, with the default "shop.db", and returns them in a Map<String, Object> with the keys "port" and "database_path". In run(), call it once and print the two settings after Port: and Database: .


Assignment
Follow the Coding Tutorial to read PORT and DATABASE_PATH from the environment with defaults, return them in a map, and print the settings the server would use.


Hint
System.getenv().getOrDefault works like a HashMap's getOrDefault. Put the port inside Integer.parseInt( ), but not the path: a path is text. Until the method returns its map, javac stops with missing return statement.


STEP 1 OF 7
    Ctrl + Enter to check