Java tutorial
/* * The MIT License * * Copyright 2014 Stephen Stafford <clothcat@gmail.com>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.clothcat.hpoolauto; import com.google.gson.GsonBuilder; import com.google.gson.JsonParser; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.PrintWriter; import java.util.logging.Level; import java.util.logging.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; /** * Functionality that wraps JSON objects and writes them to the filsystem * * @author Stephen Stafford <clothcat@gmail.com> */ public class JsonFileHelper { /** * Reads a JSON Object from the filename passed. * * When we store json files we add three lines of comment in a wrapping array, * so we remove them here and return the json object contained in the wrapper. * * @param filename * @return */ public static JSONObject readFromFile(String filename) { try { HLogger.log(Level.FINEST, "Attempting to reaad JSON from " + filename); File f = new File(Constants.JSON_FILEPATH + filename); // if the file sn't there then return an empty JSONObject if (!f.exists()) { HLogger.log(Level.FINEST, "File did not exist, returning an " + "empty JSONObject"); return new JSONObject(); } HLogger.log(Level.FINEST, "Constructing JSONArray"); JSONArray ja = new JSONArray(new JSONTokener(new FileReader(f))); HLogger.log(Level.FINEST, "Array fetched:\n" + prettify(ja.toString())); // the actual JSONObject we want is element 3 since there are three // lines of comment that start the array HLogger.log(Level.FINEST, "Unwrapping and returning: \n" + prettify(ja.getJSONObject(3).toString())); return ja.getJSONObject(3); } catch (FileNotFoundException | JSONException ex) { HLogger.log(Level.SEVERE, "Caught exception in JsonFileHelper.readFromFile.", ex); Logger.getLogger(JsonFileHelper.class.getName()).log(Level.SEVERE, null, ex); } // if we get here someting is seriously broken! HLogger.log(Level.SEVERE, "Reached the bottom of JsonFileHelper.readFromFile" + "(String filename) method. Something majorly fucked up!"); throw new RuntimeException( "Reached the bottom of JsonFileHelper." + "readFromFile(String filename) method."); } public static void writeToFile(JSONObject jo, String filename) { HLogger.log(Level.FINEST, "Attempting to write json to " + filename + "\n" + jo.toString()); // an array wrapper that we use to allow us to put a comment at the top // of the file to tell people not to edit JSONArray ja = new JSONArray(); ja.put("This file is part of the HyperPool Automation Tool (HAT)"); ja.put(" 2014 Stephen Stafford all rights wossnamed"); ja.put("DO NOT EDIT THIS FILE BY HAND. BAD THINGS WILL HAPPEN!!"); ja.put(jo); HLogger.log(Level.FINEST, "After wrapping with comments array json looks " + "like: \n" + prettify(ja.toString())); String s = ja.toString(); s = prettify(s); File f = new File(Constants.JSON_FILEPATH); f.mkdirs(); f = new File(Constants.JSON_FILEPATH + filename); HLogger.log(Level.FINEST, "Attempting to write to file: " + filename); try (PrintWriter p = new PrintWriter(f)) { p.println(s); HLogger.log(Level.FINEST, "Wrote to file: " + filename); } catch (FileNotFoundException ex) { HLogger.log(Level.SEVERE, "Caught exception whilst trying to write to " + "file: " + filename, ex); Logger.getLogger(JsonFileHelper.class.getName()).log(Level.SEVERE, null, ex); } } /** * Pretty print the passed string and return ut as a string */ public static String prettify(String json) { return new GsonBuilder().setPrettyPrinting().create().toJson(new JsonParser().parse(json)); } }