JSONConfig.java 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package xyz.spaceio.configutils;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.ObjectInputStream;
  7. import java.io.ObjectOutputStream;
  8. import java.lang.reflect.Type;
  9. import org.bukkit.plugin.Plugin;
  10. import com.google.gson.Gson;
  11. /**
  12. * A simple class for serializing/deserializing objects using Gson and managing
  13. * its file locations. The object class must be serializable
  14. *
  15. * @author MasterCake
  16. *
  17. */
  18. public class JSONConfig {
  19. private File dataFile;
  20. private Type typeToken;
  21. private Object objectToSerialize;
  22. /**
  23. * Creates a new JSONConfig
  24. *
  25. * @param type type of the object to store
  26. * @param objectToSerialize the actual object to store
  27. * @param parentPlugin the plugin instance calling this method
  28. */
  29. public JSONConfig(Type type, Object objectToSerialize, Plugin parentPlugin) {
  30. this.dataFile = new File(parentPlugin.getDataFolder().getPath() + "/" + "data.json");
  31. this.typeToken = type;
  32. this.objectToSerialize = objectToSerialize;
  33. }
  34. /**
  35. * Returns the JSON string representing the object
  36. *
  37. * @param obj
  38. * @return a JSON string
  39. */
  40. public String getJson() {
  41. Gson gson = new Gson();
  42. return gson.toJson(objectToSerialize, typeToken);
  43. }
  44. /**
  45. * Saves the object to disk, using the given file {@link #dataFile}
  46. *
  47. * @return the final file size in bytes
  48. */
  49. public long saveToDisk() {
  50. Gson gson = new Gson();
  51. try {
  52. FileOutputStream fout = new FileOutputStream(dataFile);
  53. ObjectOutputStream oos = new ObjectOutputStream(fout);
  54. oos.writeObject(gson.toJson(objectToSerialize, typeToken));
  55. fout.close();
  56. oos.close();
  57. } catch (IOException e) {
  58. // TODO Auto-generated catch block
  59. e.printStackTrace();
  60. }
  61. return dataFile.length();
  62. }
  63. /**
  64. * Reads the JSON string from the file and serializes it to an object
  65. *
  66. * @return the object
  67. */
  68. public Object getObject() {
  69. Object c = null;
  70. if (dataFile.exists()) {
  71. try {
  72. FileInputStream fin = new FileInputStream(dataFile);
  73. ObjectInputStream ois = new ObjectInputStream(fin);
  74. Gson gson = new Gson();
  75. c = gson.fromJson((String) ois.readObject(), typeToken);
  76. ois.close();
  77. fin.close();
  78. } catch (Exception e) {
  79. // TODO Auto-generated catch block
  80. e.printStackTrace();
  81. }
  82. return c;
  83. } else {
  84. return null;
  85. }
  86. }
  87. }