add RequestObject class and option to sync weather with coordinates

This commit is contained in:
Jack Fitch
2023-04-22 20:44:34 -04:00
parent b086fa8143
commit f94cb36afe
4 changed files with 81 additions and 65 deletions

View File

@@ -4,7 +4,7 @@ plugins {
} }
group = 'io.github.Jack1424' group = 'io.github.Jack1424'
version = '1.2.0' version = '1.2.1'
repositories { repositories {
mavenCentral() mavenCentral()

View File

@@ -9,14 +9,7 @@ import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.server.ServerCommandEvent; import org.bukkit.event.server.ServerCommandEvent;
import org.bukkit.plugin.java.JavaPlugin; 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.ZoneId;
import java.time.zone.ZoneRulesException; import java.time.zone.ZoneRulesException;
import java.util.*; import java.util.*;
@@ -122,19 +115,14 @@ public final class RealTimeWeather extends JavaPlugin implements Listener {
long weatherSyncInterval; long weatherSyncInterval;
String apiKey = getConfig().getString("APIKey"); String apiKey = getConfig().getString("APIKey");
String zipCode = getConfig().getString("ZipCode"); String lat = getConfig().getString("Latitude"), lon = getConfig().getString("Longitude");
String countryCode = getConfig().getString("CountryCode");
String lat, lon;
try { try {
weatherSyncInterval = getConfig().getLong("WeatherSyncInterval"); 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(); RequestObject request = new RequestObject(apiKey, lat, lon);
con.setRequestMethod("GET");
con.connect();
int response = con.getResponseCode(); int response = request.getResponseCode();
if (response > 499) { if (response > 499) {
logger.severe("There was a server error when requesting weather information. Please try again later"); logger.severe("There was a server error when requesting weather information. Please try again later");
throw new Exception("Server/client error"); throw new Exception("Server/client error");
@@ -153,10 +141,6 @@ public final class RealTimeWeather extends JavaPlugin implements Listener {
throw new Exception("Configuration error"); 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) { } catch (Exception e) {
debug(e.getMessage()); debug(e.getMessage());
logger.severe("Disabling weather sync..."); logger.severe("Disabling weather sync...");
@@ -172,50 +156,22 @@ public final class RealTimeWeather extends JavaPlugin implements Listener {
getServer().getScheduler().scheduleSyncRepeatingTask(this, () -> { getServer().getScheduler().scheduleSyncRepeatingTask(this, () -> {
debug("Syncing weather..."); debug("Syncing weather...");
boolean rain = false, thunder = false;
try { 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))); RequestObject request = new RequestObject(apiKey, lat, lon);
JSONArray conditions = (JSONArray) obj.get("weather");
for (Object rawCondition : conditions) { debug("Setting weather (Rain: " + request.isRaining() + ", Thunder: " + request.isThundering() + ")...");
JSONObject condition = (JSONObject) rawCondition; for (World world : getServer().getWorlds())
int id = Integer.parseInt(String.valueOf(condition.get("id"))); if (world.getEnvironment().equals(World.Environment.NORMAL)) {
debug("Weather ID: " + id); world.setStorm(request.isRaining());
world.setThundering(request.isThundering());
while (id >= 10)
id /= 10;
if (!rain)
rain = id == 2 || id == 3 || id == 5 || id == 6;
if (!thunder)
thunder = id == 2;
} }
} catch (Exception e) { } catch (Exception e) {
logger.severe("There was an error when attempting to get weather information"); logger.severe("There was an error when attempting to get weather information");
debug(e.getMessage()); 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); }, 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) { private void debug(String message) {
if (debug) { if (debug) {
logger.info("[DEBUG] " + message); logger.info("[DEBUG] " + message);

View File

@@ -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;
}
}

View File

@@ -1,24 +1,23 @@
# RealTimeWeather Configuration File (v1) # RealTimeWeather Configuration File (v2)
# Configure RTM below BEFORE using it
################################# TIME SYNC SETTINGS ################################################################# ################################# TIME SYNC SETTINGS #################################################################
# Set to true to enable time syncing, or false to disable # # Set to true to enable time syncing, or false to disable #
SyncTime: false SyncTime: false
# # #
# You can change the time between time syncs from the default (5 seconds) below # # You can change the time between time syncs from the default (5 seconds) below #
TimeSyncInterval: 100 TimeSyncInterval: 100
# # # #
# Enter the time zone that you want to sync your world(s) with # # Enter the time zone that you want to sync your world(s) with #
# This location CAN be different from your chosen weather location # # 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 # # 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 ############################################################## ################################# WEATHER SYNC SETTINGS ##############################################################
# Set to true to enable weather syncing, or false to disable # # Set to true to enable weather syncing, or false to disable #
SyncWeather: false SyncWeather: false
# # #
# You can change the time between weather syncs from the default (5 minutes) below # # 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 # # 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/ # # 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 # # 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 # # Finally, paste the API key below and DO NOT SHARE IT WITH OTHERS #
APIKey: 'API_KEY' 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 # # Enter the latitude and longitude of the location that you want to sync your world(s) weather with #
ZipCode: '10001' # NOTE: You can find the latitude and longitude of a location at https://www.latlong.net/ #
CountryCode: 'US' Latitude: '0'
Longitude: '0'
# # # #
###################################################################################################################### ######################################################################################################################
# Set to true for various console messages when time and weather sync are executed # 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 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 # 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 # Note: Java exceptions and fatal plugin errors will still be logged regardless of the debug value
Debug: false Debug: false