Guest User

Untitled

a guest
May 30th, 2020
292
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.95 KB | None | 0 0
  1. package com.example.Whatever.setup;
  2.  
  3. import com.example.Whatever.WhateverApplication;
  4. import lombok.Getter;
  5. import lombok.NonNull;
  6. import org.json.simple.JSONObject;
  7. import org.json.simple.parser.JSONParser;
  8. import org.json.simple.parser.ParseException;
  9. import org.slf4j.Logger;
  10. import org.slf4j.LoggerFactory;
  11.  
  12. import java.io.File;
  13. import java.io.FileReader;
  14. import java.io.IOException;
  15.  
  16. public class JSONUpdater {
  17.   @NonNull private String configFilePath;
  18.   @Getter private JSONObject configuration;
  19.   private long timestamp;
  20.   private static final transient Logger logger =
  21.           LoggerFactory.getLogger(WhateverApplication.class);
  22.  
  23.   /**
  24.    * This instantiates the JSONUpdater. Trigger {@link JSONUpdater#update()} before active use.
  25.    * @param configFilePath the path to the configuration file in JSON format
  26.    */
  27.   public JSONUpdater (String configFilePath) {
  28.     this.configFilePath = configFilePath;
  29.     this.timestamp = 0;
  30.   }
  31.  
  32.   /**
  33.    * update the fields
  34.    * @throws IOException if an error occurred while opening / reading the file
  35.    * @throws ParseException if an error occurred parsing the JSON file
  36.    */
  37.   public void update() throws IOException, ParseException {
  38.     long latestTimestamp = getLatestTimestamp(this.configFilePath);
  39.     if (this.timestamp == latestTimestamp)
  40.       return;
  41.  
  42.     logger.info("Configuration file was modified. " +
  43.             "Current timestamp: " + this.timestamp
  44.             + " | New timestamp: " + latestTimestamp);
  45.     this.configuration = this.parse(this.configFilePath);
  46.     logger.trace("JSON Parsing done");
  47.     this.timestamp = latestTimestamp;
  48.   }
  49.  
  50.   private long getLatestTimestamp(String configFilePath) {
  51.     return new File(configFilePath).lastModified();
  52.   }
  53.  
  54.   private JSONObject parse(String configFilePath) throws IOException, ParseException {
  55.     JSONParser jsonParser = new JSONParser();
  56.     return (JSONObject) jsonParser.parse(new FileReader(configFilePath));
  57.   }
  58.  
  59. }
Advertisement
Add Comment
Please, Sign In to add comment