Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.Whatever.setup;
- import com.example.Whatever.WhateverApplication;
- import lombok.Getter;
- import lombok.NonNull;
- import org.json.simple.JSONObject;
- import org.json.simple.parser.JSONParser;
- import org.json.simple.parser.ParseException;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import java.io.File;
- import java.io.FileReader;
- import java.io.IOException;
- public class JSONUpdater {
- @NonNull private String configFilePath;
- @Getter private JSONObject configuration;
- private long timestamp;
- private static final transient Logger logger =
- LoggerFactory.getLogger(WhateverApplication.class);
- /**
- * This instantiates the JSONUpdater. Trigger {@link JSONUpdater#update()} before active use.
- * @param configFilePath the path to the configuration file in JSON format
- */
- public JSONUpdater (String configFilePath) {
- this.configFilePath = configFilePath;
- this.timestamp = 0;
- }
- /**
- * update the fields
- * @throws IOException if an error occurred while opening / reading the file
- * @throws ParseException if an error occurred parsing the JSON file
- */
- public void update() throws IOException, ParseException {
- long latestTimestamp = getLatestTimestamp(this.configFilePath);
- if (this.timestamp == latestTimestamp)
- return;
- logger.info("Configuration file was modified. " +
- "Current timestamp: " + this.timestamp
- + " | New timestamp: " + latestTimestamp);
- this.configuration = this.parse(this.configFilePath);
- logger.trace("JSON Parsing done");
- this.timestamp = latestTimestamp;
- }
- private long getLatestTimestamp(String configFilePath) {
- return new File(configFilePath).lastModified();
- }
- private JSONObject parse(String configFilePath) throws IOException, ParseException {
- JSONParser jsonParser = new JSONParser();
- return (JSONObject) jsonParser.parse(new FileReader(configFilePath));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment