Reading and Writing Configuration Files with JSON-P

JSON-P ships with Java EE 8 and is already included in the API:


<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>8.0</version>
    <scope>provided</scope>
</dependency>    
In standalone applications, like e.g. CLI, you will have to add the SPI (Service Provider Implementation) dependency:

<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1.4</version>
</dependency>    
JsonReader reads the configuration from InputStream:

    public final static String CONFIGURATION_FILE = "duke-config.json";

    public static JsonObjectBuilder load() throws FileNotFoundException {
        try (JsonReader reader = Json.createReader(new FileInputStream(CONFIGURATION_FILE))) {
            return Json.createObjectBuilder(reader.readObject());
        }
    }    
and the JsonWrite serializes an in-memory instance into a stream:

    public static void write(JsonObject configuration) {
        try (JsonWriter writer = Json.createWriter(new FileOutputStream(CONFIGURATION_FILE))) {
            writer.writeObject(configuration);
        } catch (FileNotFoundException ex){}
    }    
An JsonObject is a typed Map<String, JsonValue>, the values can be directly access with a key:

public static String getValue(String key) {
    JsonObject configuration = null;
    try {
        configuration = load().build();
    } catch (FileNotFoundException ex) {    }
    return configuration.getString(key);
}
jwtenizr.sh uses the above approach (see Configuration.java to store the private and public keys, issuer, as well as the JWT location.

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.


Web Apps, SPA, PWA with vanilla Java Script (ES 6+), CSS 3 and WebStandards only. As simple as possible, but not simpler. See you at: (Progressive) Web apps, Single Page Apps and WebStandards airhacks workshops at MUC airport, Winter Edition

airhacks.fm the podcast:

Stay in touch: airhacks.news.

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
realworldpatterns.com
...the last 150 posts
...the last 10 comments
License