Config.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package uk.ac.ic.wlgitbridge.application;
  2. import com.google.gson.Gson;
  3. import com.google.gson.JsonElement;
  4. import com.google.gson.JsonObject;
  5. import com.google.gson.JsonParseException;
  6. import uk.ac.ic.wlgitbridge.application.exception.InvalidConfigFileException;
  7. import uk.ac.ic.wlgitbridge.writelatex.api.request.base.JSONSource;
  8. import java.io.FileReader;
  9. import java.io.IOException;
  10. /**
  11. * Created by Winston on 05/12/14.
  12. */
  13. public class Config implements JSONSource {
  14. private int port;
  15. private String rootGitDirectory;
  16. private String apiKey;
  17. private String username;
  18. private String password;
  19. private String hostname;
  20. private String serviceName;
  21. public Config(String configFilePath) throws InvalidConfigFileException, IOException {
  22. try {
  23. fromJSON(new Gson().fromJson(new FileReader(configFilePath), JsonElement.class));
  24. } catch (JsonParseException e) {
  25. throw new IOException();
  26. }
  27. }
  28. @Override
  29. public void fromJSON(JsonElement json) {
  30. JsonObject configObject = json.getAsJsonObject();
  31. port = getElement(configObject, "port").getAsInt();
  32. rootGitDirectory = getElement(configObject, "rootGitDirectory").getAsString();
  33. apiKey = getElement(configObject, "apiKey").getAsString();
  34. username = getOptionalString(configObject, "username");
  35. password = getOptionalString(configObject, "password");
  36. hostname = getElement(configObject, "hostname").getAsString();
  37. serviceName = getElement(configObject, "serviceName").getAsString();
  38. }
  39. public int getPort() {
  40. return port;
  41. }
  42. public String getRootGitDirectory() {
  43. return rootGitDirectory;
  44. }
  45. public String getAPIKey() {
  46. return apiKey;
  47. }
  48. public String getUsername() {
  49. return username;
  50. }
  51. public String getPassword() {
  52. return password;
  53. }
  54. public String getHostname() {
  55. return hostname;
  56. }
  57. private JsonElement getElement(JsonObject configObject, String name) {
  58. JsonElement element = configObject.get(name);
  59. if (element == null) {
  60. throw new RuntimeException(new InvalidConfigFileException(name));
  61. }
  62. return element;
  63. }
  64. private String getOptionalString(JsonObject configObject, String name) {
  65. JsonElement element = configObject.get(name);
  66. if (element == null || !element.isJsonPrimitive()) {
  67. return "";
  68. }
  69. return element.getAsString();
  70. }
  71. public String getServiceName() {
  72. return serviceName;
  73. }
  74. }