Commit 39e3e66a authored by Christopher Bohn's avatar Christopher Bohn 🤔
Browse files

Cleaning up

- Renamed `Main` to `Demonstration` and introduced a menu
- Updated JavaDoc to reflect which data sets each method pertains to
- Cleaned up code to extract Longs and Doubles from JSON
parent 8fd5534c
package edu.unl.cse.soft160.json_connections;
import edu.unl.cse.soft160.json_connections.connection.FileConnection;
import edu.unl.cse.soft160.json_connections.connection.RestConnection;
import edu.unl.cse.soft160.json_connections.connector.OpenWeatherConnector;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.IOException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
public class Demonstration {
public static void main(String... args) {
String apiKey = null;
try {
apiKey = RestConnection.getApiKey("openweathermap");
} catch (IOException ioException) {
System.err.println("IO Exception: " + ioException.getClass());
System.err.println("\t" + ioException.getMessage());
System.err.println("Caused by: " + ioException.getCause());
System.err.println("\t" + ioException.getCause().getMessage());
}
Scanner scanner = new Scanner(System.in);
List<String> dataSets = new ArrayList<>(OpenWeatherConnector.allowableDataSets);
for (int i = 0; i < dataSets.size(); ++i) {
System.out.println((i + 1) + ". " + dataSets.get(i));
}
System.out.print(System.lineSeparator() + "Please enter the desired data set: ");
int choice = scanner.nextInt();
scanner.nextLine();
String dataSet = dataSets.get(choice - 1);
OpenWeatherConnector weather = new OpenWeatherConnector(dataSet, apiKey);
Instant now = Instant.now();
String query; // this is a might be a candidate for a switch expression
switch (dataSet) { // (https://docs.oracle.com/en/java/javase/17/language/switch-expressions.html)
case "weather": // but Java 11 doesn't have that feature
case "forecast":
query = "zip=68588";
break;
case "air_pollution":
case "air_pollution/forecast":
query = "lat=40.81506358&lon=-96.7048613";
break;
case "air_pollution/history":
Instant yesterday = now.minus(1, ChronoUnit.DAYS);
Instant twoDaysAgo = now.minus(2, ChronoUnit.DAYS);
query = "lat=40.81506358&lon=-96.7048613&start=" +
twoDaysAgo.getEpochSecond() + "&end=" + yesterday.getEpochSecond();
break;
default:
System.err.println("The " + dataSet + " dataset is not currently supported.");
query = "";
}
System.out.println("Requesting data at " + now);
String data = null;
try {
data = weather.retrieveData(query);
} catch (IOException ioException) {
System.err.println("IO Exception: " + ioException.getClass());
System.err.println("\t" + ioException.getMessage());
System.err.println("Caused by: " + ioException.getCause());
if (ioException.getCause() != null) {
System.err.println("\t" + ioException.getCause().getMessage());
}
}
System.out.println("Raw JSON: " + data);
System.out.println("Location: " + weather.getLatitude() + " latitude, " + weather.getLongitude() + " " +
"longitude");
Date currentTimeStamp = weather.getTimestamp();
System.out.println("Current timestamp: " +
(currentTimeStamp == OpenWeatherConnector.IMPOSSIBLE_DATE ? "not present" : currentTimeStamp));
System.out.println("Available timestamps: " + weather.getTimeStamps());
Date timestamp;
switch (dataSet) {
case "weather":
System.out.println("It is currently " + weather.getWeatherCategories());
System.out.println("Specifically, it is " + weather.getWeatherDescriptions());
System.out.println("The temperature is " + weather.getTemperature() + "K");
System.out.println("Factoring in the relative humidity of " + weather.getHumidity() + "%, it feels " +
"like " + weather.getFeelsLike() + "K");
System.out.println("That probably also factored in winds, which are " + weather.getWindSpeed() + "m/s" +
" from " + weather.getWindDirection() + "˚, gusting to " + weather.getWindGust() + "m/s");
System.out.println("Visibility is " + weather.getVisibility() + "m");
System.out.println("The pressure is " + weather.getPressure() + "hPa");
System.out.println("Cloud cover is " + weather.getCloudCover() + "%");
System.out.println("Precipitation in the last hour has been " + weather.getOneHourRainfall() + "mm of" +
" rain and " + weather.getOneHourSnowfall() + "mm of snow.");
System.out.println("If three-hour precipitation data is reported, it's " +
weather.getThreeHourRainfall() + "mm of rain and " + weather.getThreeHourSnowfall() + "mm of " +
"snow. (You might not want to trust those values if they match the 1-hour precipitation.)");
break;
case "forecast":
timestamp = weather.getTimeStamps().get(weather.getTimeStamps().size() / 2);
System.out.println("At " + timestamp + " it will be ");
break;
case "air_pollution":
System.out.println("The current air quality is " + weather.getAirQualityIndex() +
" pollutant concentration");
System.out.println("CO: " + weather.getCarbonMonoxide() + " μg/m3");
System.out.println("NO: " + weather.getNitrogenMonoxide() + " μg/m3");
System.out.println("NO2: " + weather.getNitrogenDioxide() + " μg/m3");
System.out.println("O3: " + weather.getOzone() + " μg/m3");
System.out.println("SO2: " + weather.getSulfurDioxide() + " μg/m3");
System.out.println("NH3: " + weather.getAmmonia() + " μg/m3");
System.out.println("Fine particulate matter: " + weather.getFineParticulateMatter() + " μg/m3");
System.out.println("Coarse particulate matter: " + weather.getCoarseParticulateMatter() + " μg/m3");
break;
case "air_pollution/history":
case "air_pollution/forecast":
timestamp = weather.getTimeStamps().get(weather.getTimeStamps().size() / 2);
System.out.println("The air quality at " + timestamp +
(timestamp.toInstant().isBefore(now) ? " was " : " will be ") +
weather.getAirQualityIndex(timestamp) + " pollutant concentration");
System.out.println("CO: " + weather.getCarbonMonoxide(timestamp) + " μg/m3");
System.out.println("NO: " + weather.getNitrogenMonoxide(timestamp) + " μg/m3");
System.out.println("NO2: " + weather.getNitrogenDioxide(timestamp) + " μg/m3");
System.out.println("O3: " + weather.getOzone(timestamp) + " μg/m3");
System.out.println("SO2: " + weather.getSulfurDioxide(timestamp) + " μg/m3");
System.out.println("NH3: " + weather.getAmmonia(timestamp) + " μg/m3");
System.out.println("Fine particulate matter: " + weather.getFineParticulateMatter(timestamp) + " " +
"μg/m3");
System.out.println("Coarse particulate matter: " + weather.getCoarseParticulateMatter(timestamp) + " " +
"μg/m3");
break;
}
System.out.print(System.lineSeparator() + "Do you wish to save this data to a file (Y)/N? ");
String answer = scanner.nextLine();
if (answer.equals("") || answer.toUpperCase().charAt(0) != 'N') {
System.out.print("What shall the file's name be? ");
String filename = scanner.nextLine();
if (!filename.endsWith(".json")) {
filename += ".json";
}
FileConnection fileConnection = new FileConnection(dataSet);
try {
System.out.println("Saving...");
fileConnection.save(filename, (JSONObject)new JSONParser().parse(data));
System.out.println("\t" + filename + " saved");
} catch (ParseException | IOException exception) {
exception.printStackTrace();
}
} else {
System.out.println("Not saving data.");
}
scanner.close();
}
}
package edu.unl.cse.soft160.json_connections;
import edu.unl.cse.soft160.json_connections.connection.FileConnection;
import edu.unl.cse.soft160.json_connections.connection.RestConnection;
import edu.unl.cse.soft160.json_connections.connector.OpenWeatherConnector;
import org.json.simple.parser.ParseException;
import java.io.IOException;
public class Main {
public static void main(String... args) {
String apiKey = null;
try {
apiKey = RestConnection.getApiKey("openweathermap");
} catch (IOException ioException) {
System.err.println("IO Exception: " + ioException.getClass());
System.err.println("\t" + ioException.getMessage());
System.err.println("Caused by: " + ioException.getCause());
System.err.println("\t" + ioException.getCause().getMessage());
}
/* Using OpenWeatherConnector */
/*
// OpenWeatherConnector weather = new OpenWeatherConnector("weather", apiKey);
OpenWeatherConnector weather = new OpenWeatherConnector("air_pollution/history", apiKey);
String data = null;
try {
data = weather.retrieveData("lat=40.81506358&lon=-96.7048613&start=1606223802&end=1606482999");
// data = weather.retrieveData("website-example.json");
} catch (IOException ioException) {
System.err.println("IO Exception: " + ioException.getClass());
System.err.println("\t" + ioException.getMessage());
System.err.println("Caused by: " + ioException.getCause());
System.err.println("\t" + ioException.getCause().getMessage());
}
System.out.println(data);
System.out.println(weather.getWeatherCategories());
System.out.println("Temperature: " + weather.getTemperature() + "K");
System.out.println("Cloud cover: " + weather.getCloudCover() + "%");
System.out.println("Timestamp: " + weather.getTimestamp());
*/
/* Creating file copies of live data */
RestConnection restConnection = new RestConnection("http", "api.openweathermap.org", "/data/2.5/air_pollution/history", apiKey);
FileConnection fileConnection = new FileConnection("air_pollution");
try {
fileConnection.save("air_pollution-unl-historical.json",
restConnection.get("lat=40.81506358&lon=-96.7048613&start=1606223802&end=1606482999"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
package edu.unl.cse.soft160.json_connections.connection;
import edu.unl.cse.soft160.json_connections.Main;
import edu.unl.cse.soft160.json_connections.Demonstration;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
......@@ -30,7 +30,7 @@ public class RestConnection implements Connection {
public static String getApiKey(String apiKeyName) throws IOException {
JSONObject apiKeyJson;
try (InputStreamReader inputStreamReader = new InputStreamReader(Objects.requireNonNull(
Main.class.getClassLoader().getResourceAsStream(FILENAME)))) {
Demonstration.class.getClassLoader().getResourceAsStream(FILENAME)))) {
apiKeyJson = (JSONObject)new JSONParser().parse(inputStreamReader);
} catch (NullPointerException nullPointerException) {
FileNotFoundException newException = new FileNotFoundException("File " + FILENAME + " not found.");
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment