diff --git a/build.gradle b/build.gradle index 3872488..340ad0c 100644 --- a/build.gradle +++ b/build.gradle @@ -4,7 +4,7 @@ plugins { } group = 'io.github.Jack1424' -version = '1.2.0' +version = '1.2.1' repositories { mavenCentral() diff --git a/src/main/java/io/github/jack1424/realtimeweather/RealTimeWeather.java b/src/main/java/io/github/jack1424/realtimeweather/RealTimeWeather.java index 20ba82e..c80c2d2 100644 --- a/src/main/java/io/github/jack1424/realtimeweather/RealTimeWeather.java +++ b/src/main/java/io/github/jack1424/realtimeweather/RealTimeWeather.java @@ -9,14 +9,7 @@ import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.server.ServerCommandEvent; import org.bukkit.plugin.java.JavaPlugin; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; -import javax.net.ssl.HttpsURLConnection; -import java.io.IOException; -import java.net.URL; import java.time.ZoneId; import java.time.zone.ZoneRulesException; import java.util.*; @@ -122,19 +115,14 @@ public final class RealTimeWeather extends JavaPlugin implements Listener { long weatherSyncInterval; String apiKey = getConfig().getString("APIKey"); - String zipCode = getConfig().getString("ZipCode"); - String countryCode = getConfig().getString("CountryCode"); - - String lat, lon; + String lat = getConfig().getString("Latitude"), lon = getConfig().getString("Longitude"); try { weatherSyncInterval = getConfig().getLong("WeatherSyncInterval"); - HttpsURLConnection con = (HttpsURLConnection) new URL(String.format("https://api.openweathermap.org/geo/1.0/zip?zip=%s,%s&appid=%s", zipCode, countryCode, apiKey)).openConnection(); - con.setRequestMethod("GET"); - con.connect(); + RequestObject request = new RequestObject(apiKey, lat, lon); - int response = con.getResponseCode(); + int response = request.getResponseCode(); if (response > 499) { logger.severe("There was a server error when requesting weather information. Please try again later"); throw new Exception("Server/client error"); @@ -153,10 +141,6 @@ public final class RealTimeWeather extends JavaPlugin implements Listener { throw new Exception("Configuration error"); } - - JSONObject obj = makeWeatherRequest(con.getURL()); - lat = String.valueOf(obj.get("lat")); - lon = String.valueOf(obj.get("lon")); } catch (Exception e) { debug(e.getMessage()); logger.severe("Disabling weather sync..."); @@ -172,50 +156,22 @@ public final class RealTimeWeather extends JavaPlugin implements Listener { getServer().getScheduler().scheduleSyncRepeatingTask(this, () -> { debug("Syncing weather..."); - boolean rain = false, thunder = false; try { - JSONObject obj = makeWeatherRequest(new URL(String.format("https://api.openweathermap.org/data/2.5/weather?lat=%s&lon=%s&appid=%s", lat, lon, apiKey))); - JSONArray conditions = (JSONArray) obj.get("weather"); + RequestObject request = new RequestObject(apiKey, lat, lon); - for (Object rawCondition : conditions) { - JSONObject condition = (JSONObject) rawCondition; - int id = Integer.parseInt(String.valueOf(condition.get("id"))); - debug("Weather ID: " + id); - - while (id >= 10) - id /= 10; - - if (!rain) - rain = id == 2 || id == 3 || id == 5 || id == 6; - if (!thunder) - thunder = id == 2; - } + debug("Setting weather (Rain: " + request.isRaining() + ", Thunder: " + request.isThundering() + ")..."); + for (World world : getServer().getWorlds()) + if (world.getEnvironment().equals(World.Environment.NORMAL)) { + world.setStorm(request.isRaining()); + world.setThundering(request.isThundering()); + } } catch (Exception e) { logger.severe("There was an error when attempting to get weather information"); debug(e.getMessage()); } - - debug("Setting weather (Rain: " + rain + ", Thunder: " + thunder + ")..."); - for (World world : getServer().getWorlds()) - if (world.getEnvironment().equals(World.Environment.NORMAL)) { - world.setStorm(rain); - world.setThundering(thunder); - } }, 0L, weatherSyncInterval); } - private JSONObject makeWeatherRequest(URL url) throws IOException, ParseException { - Scanner scanner = new Scanner(url.openStream()); - StringBuilder data = new StringBuilder(); - while (scanner.hasNext()) { - data.append(scanner.nextLine()); - } - scanner.close(); - - JSONParser parser = new JSONParser(); - return (JSONObject) parser.parse(data.toString()); - } - private void debug(String message) { if (debug) { logger.info("[DEBUG] " + message); diff --git a/src/main/java/io/github/jack1424/realtimeweather/RequestObject.java b/src/main/java/io/github/jack1424/realtimeweather/RequestObject.java new file mode 100644 index 0000000..5c494cf --- /dev/null +++ b/src/main/java/io/github/jack1424/realtimeweather/RequestObject.java @@ -0,0 +1,60 @@ +package io.github.jack1424.realtimeweather; + +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import javax.net.ssl.HttpsURLConnection; +import java.io.IOException; +import java.net.URL; +import java.util.Scanner; + +public class RequestObject { + private final int responseCode; + private boolean rain = false, thunder = false; + + public RequestObject(String apiKey, String lat, String lon) throws IOException, ParseException { + URL url = new URL(String.format("https://api.openweathermap.org/data/2.5/weather?lat=%s&lon=%s&appid=%s", lat, lon, apiKey)); + + HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); + con.setRequestMethod("GET"); + con.connect(); + responseCode = con.getResponseCode(); + if (responseCode > 399) + return; + + Scanner scanner = new Scanner(url.openStream()); + StringBuilder data = new StringBuilder(); + while (scanner.hasNext()) { + data.append(scanner.nextLine()); + } + scanner.close(); + + JSONArray conditions = (JSONArray) ((JSONObject) new JSONParser().parse(data.toString())).get("weather"); + + for (Object rawCondition : conditions) { + int id = Integer.parseInt(String.valueOf(((JSONObject) rawCondition).get("id"))); + + while (id >= 10) + id /= 10; + + if (!rain) + rain = id == 2 || id == 3 || id == 5 || id == 6; + if (!thunder) + thunder = id == 2; + } + } + + public int getResponseCode() { + return responseCode; + } + + public boolean isRaining() { + return rain; + } + + public boolean isThundering() { + return thunder; + } +} diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index adef2fb..b7d70d7 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -1,24 +1,23 @@ -# RealTimeWeather Configuration File (v1) -# Configure RTM below BEFORE using it +# RealTimeWeather Configuration File (v2) ################################# TIME SYNC SETTINGS ################################################################# # Set to true to enable time syncing, or false to disable # SyncTime: false -# +# # # You can change the time between time syncs from the default (5 seconds) below # TimeSyncInterval: 100 # # # Enter the time zone that you want to sync your world(s) with # # This location CAN be different from your chosen weather location # # You can find a full list of timezones here: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones#List # -Timezone: 'America/New_York' +Timezone: 'Etc/UTC' # # ###################################################################################################################### ################################# WEATHER SYNC SETTINGS ############################################################## # Set to true to enable weather syncing, or false to disable # SyncWeather: false -# +# # # You can change the time between weather syncs from the default (5 minutes) below # # Due to OpenWeather's restrictions, setting this value below 2400 (2 minutes) will cause problems # # You can find a handy tick calculator here: https://mapmaking.fr/tick/ # @@ -28,16 +27,17 @@ WeatherSyncInterval: 6000 # Then, create an API key at https://openweathermap.org/appid and copy it # # Finally, paste the API key below and DO NOT SHARE IT WITH OTHERS # APIKey: 'API_KEY' -# Enter the zip code and country code of the location that you want to sync your world(s) weather with # -# NOTE: A list of country codes can be found at https://en.wikipedia.org/wiki/ISO_3166-1#Current_codes # -ZipCode: '10001' -CountryCode: 'US' +# # +# Enter the latitude and longitude of the location that you want to sync your world(s) weather with # +# NOTE: You can find the latitude and longitude of a location at https://www.latlong.net/ # +Latitude: '0' +Longitude: '0' # # ###################################################################################################################### # Set to true for various console messages when time and weather sync are executed # This is useful if the plugin is not working, and you want to find out what's wrong # This will also provide java error messages when an error is caught and managed by RTM -# Note: There will be no messages during a time sync because they happen every second +# Note: There will be no messages during a time sync because they happen very frequently # Note: Java exceptions and fatal plugin errors will still be logged regardless of the debug value Debug: false