use of io.github.binaryoverload.JSONConfig in project FlareBot by FlareBot.
the class CurrencyConversionUtil method getNormalCurrency.
private static CurrencyComparison getNormalCurrency(String from, String to) throws IOException {
Response response = WebUtils.get(new Request.Builder().get().url(CurrencyApiRoutes.NormalApi.LATEST_WITH_SYMBOLS_AND_BASE.getCompiledUrl(to, from)));
if (!response.isSuccessful() || response.body() == null)
return null;
JSONConfig config = new JSONConfig(response.body().byteStream());
response.close();
if (config.getString("base").isPresent() && config.getDouble("rates." + to).isPresent()) {
Double conversion = config.getDouble("rates." + to).getAsDouble();
return new CurrencyComparison(from, to, conversion);
}
return null;
}
use of io.github.binaryoverload.JSONConfig in project FlareBot by FlareBot.
the class CurrencyConversionUtil method getCryptoCurrency.
private static CurrencyComparison getCryptoCurrency(String from, String to) throws IOException {
Response res = WebUtils.get(new Request.Builder().get().url(CurrencyApiRoutes.CrytoApi.BASIC_TICKER.getCompiledUrl(from, to)));
if (!res.isSuccessful() || res.body() == null)
return null;
JSONConfig config = new JSONConfig(res.body().byteStream());
res.close();
if (config.getBoolean("success").isPresent() && config.getBoolean("success").get()) {
String price = config.getString("ticker.price").get();
Double priceDouble;
try {
priceDouble = Double.parseDouble(price);
} catch (NumberFormatException e) {
return null;
}
return new CurrencyComparison(from, to, priceDouble);
}
return null;
}
use of io.github.binaryoverload.JSONConfig in project FlareBot by FlareBot.
the class FlareBot method main.
public static void main(String[] args) {
Spark.port(8080);
try {
File file = new File("config.json");
if (!file.exists() && !file.createNewFile())
throw new IllegalStateException("Can't create config file!");
try {
config = new JSONConfig(new File("config.json"), '.', new char[] { '-', '_', '<', '>', '@' });
} catch (NullPointerException e) {
LOGGER.error("Invalid JSON!", e);
System.exit(1);
}
} catch (IOException e) {
LOGGER.error("Unable to create config.json!", e);
System.exit(1);
}
List<String> required = new ArrayList<>();
required.add("bot.token");
required.add("cassandra.username");
required.add("cassandra.password");
required.add("misc.yt");
required.add("redis.host");
required.add("redis.port");
required.add("redis.password");
required.add("sentry.dsn");
boolean good = true;
for (String req : required) {
if (config.getString(req) != null) {
if (!config.getString(req).isPresent()) {
good = false;
LOGGER.error("Missing required json " + req);
}
} else {
good = false;
LOGGER.error("Missing required json " + req);
}
}
if (!good) {
LOGGER.error("One or more of the required JSON objects where missing. Exiting to prevent problems");
System.exit(1);
}
new CassandraController(config);
new RedisController(config);
FlareBot.youtubeApi = config.getString("misc.yt").get();
if (config.getArray("options").isPresent()) {
for (JsonElement em : config.getArray("options").get()) {
if (em.getAsString() != null) {
if (em.getAsString().equals("tb")) {
FlareBot.testBot = true;
}
if (em.getAsString().equals("debug")) {
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME)).setLevel(Level.DEBUG);
}
}
}
}
SentryClient sentryClient = Sentry.init(config.getString("sentry.dsn").get() + "?stacktrace.app.packages=stream.flarebot.flarebot");
sentryClient.setEnvironment(testBot ? "TestBot" : "Production");
sentryClient.setServerName(testBot ? "Test Server" : "Production Server");
sentryClient.setRelease(GitHandler.getLatestCommitId());
if (!config.getString("misc.apiKey").isPresent() || config.getString("misc.apiKey").get().isEmpty())
apiEnabled = false;
Thread.setDefaultUncaughtExceptionHandler(((t, e) -> LOGGER.error("Uncaught exception in thread " + t, e)));
Thread.currentThread().setUncaughtExceptionHandler(((t, e) -> LOGGER.error("Uncaught exception in thread " + t, e)));
try {
(instance = new FlareBot()).init();
} catch (Exception e) {
e.printStackTrace();
}
}
use of io.github.binaryoverload.JSONConfig in project FlareBot by FlareBot.
the class GuildWrapperLoader method load.
@Override
@ParametersAreNonnullByDefault
public GuildWrapper load(String id) {
long start = System.currentTimeMillis();
ResultSet set = CassandraController.execute("SELECT data FROM " + FlareBotManager.instance().GUILD_DATA_TABLE + " WHERE guild_id = '" + id + "'");
GuildWrapper wrapper;
Row row = set != null ? set.one() : null;
String json = null;
JSONConfig data;
try {
if (row != null) {
json = row.getString("data");
if (json.isEmpty() || json.equalsIgnoreCase("null")) {
return new GuildWrapper(id);
}
data = new JSONConfig(parser.parse(json).getAsJsonObject(), '.', ALLOWED_SPECIAL_CHARACTERS);
if (data.getLong("dataVersion").isPresent() && data.getLong("dataVersion").getAsLong() == 0)
data = firstMigration(data);
wrapper = FlareBot.GSON.fromJson(data.getObject().toString(), GuildWrapper.class);
} else
return new GuildWrapper(id);
} catch (Exception e) {
if (json == null) {
FlareBot.LOGGER.error(Markers.TAG_DEVELOPER, "Failed to load GuildWrapper!!\n" + "Guild ID: " + id + "\n" + "Guild JSON: " + (row != null ? row.getString("data") : "New guild data!") + "\n" + "Error: " + e.getMessage(), e);
return null;
}
try {
data = new JSONConfig(parser.parse(json).getAsJsonObject(), '.', ALLOWED_SPECIAL_CHARACTERS);
} catch (Exception e1) {
FlareBot.LOGGER.error(Markers.TAG_DEVELOPER, "Failed to load GuildWrapper!!\n" + "Guild ID: " + id + "\n" + "Guild JSON: " + json + "\n" + "Error: " + e.getMessage(), e);
throw new IllegalArgumentException("Invalid JSON! '" + json + "'", e1);
}
if (!data.getLong("dataVersion").isPresent()) {
try {
data = firstMigration(data);
} catch (Exception e1) {
FlareBot.LOGGER.error(Markers.TAG_DEVELOPER, "Failed to load GuildWrapper!!\n" + "Guild ID: " + id + "\n" + "Guild JSON: " + json + "\n" + "Error: " + e.getMessage(), e);
throw new IllegalArgumentException("Invalid JSON! '" + json + "'", e1);
}
data.set("dataVersion", 1);
}
long version = data.getLong("dataVersion").getAsLong();
if (version != GuildWrapper.DATA_VERSION) {
// Migrations
}
json = data.getObject().toString();
try {
wrapper = FlareBot.GSON.fromJson(json, GuildWrapper.class);
} catch (Exception e1) {
FlareBot.LOGGER.error(Markers.TAG_DEVELOPER, "Failed to load GuildWrapper!!\n" + "Guild ID: " + id + "\n" + "Guild JSON: " + json + "\n" + "Error: " + e1.getMessage(), e1);
return null;
}
}
long total = (System.currentTimeMillis() - start);
loadTimes.add(total);
if (total >= 200) {
Constants.getImportantLogChannel().sendMessage(MessageUtils.getEmbed().setColor(new Color(166, 0, 255)).setTitle("Long guild load time!", null).setDescription("Guild " + id + " loaded!").addField("Time", "Millis: " + System.currentTimeMillis() + "\nTime: " + LocalDateTime.now().toString(), false).addField("Load time", total + "ms", false).build()).queue();
}
return wrapper;
}
use of io.github.binaryoverload.JSONConfig in project FlareBot by FlareBot.
the class GuildWrapperLoader method firstMigration.
private JSONConfig firstMigration(JSONConfig data) {
if (data.getSubConfig("permissions.groups").isPresent()) {
List<Group> groups = new ArrayList<>();
data.setAllowedSpecialCharacters(ALLOWED_SPECIAL_CHARACTERS);
JSONConfig config = data.getSubConfig("permissions.groups").get();
for (String s : config.getKeys(false)) {
if (config.getElement(s).isPresent()) {
groups.add(FlareBot.GSON.fromJson(config.getElement(s).get().getAsJsonObject().toString(), Group.class));
}
}
data.set("permissions.groups", groups);
}
return data;
}
Aggregations