Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Integrate OpenWeatherMap API #12

Merged
merged 8 commits into from
May 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>project</groupId>
Expand All @@ -19,6 +18,11 @@
<artifactId>flatlaf</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.8</version>
</dependency>
</dependencies>

<properties>
Expand Down
2 changes: 2 additions & 0 deletions src/main/java/edu/project/Config.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
* location
*/
public class Config {
public static final String OPENWEATHERMAP_API_KEY = "23c541de6a2105ebf03f39791a6b7cd1";

public static final int WINDOW_INIT_WIDTH = 960;
public static final int WINDOW_INIT_HEIGHT = 640;
public static final int WINDOW_INIT_PADDING = 16;
Expand Down
10 changes: 9 additions & 1 deletion src/main/java/edu/project/Context.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
package edu.project;

import edu.project.api.WeatherApi;

/**
* Acts as the service locator for all the services in the project
*/
public class Context {
public final Store store = new Store();
public final Store store;
public final WeatherApi weatherApi;

public Context() {
this.store = new Store();
this.weatherApi = new WeatherApi();
}
}
5 changes: 3 additions & 2 deletions src/main/java/edu/project/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@

import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

import com.formdev.flatlaf.themes.FlatMacLightLaf;

import edu.project.components.App;
import edu.project.services.WeatherService;

import java.net.InetSocketAddress;
import java.net.Socket;
Expand All @@ -24,6 +23,8 @@ public static void main(String[] args) {
}

Context context = new Context();
new WeatherService(context);

App app = new App(context);
app.setVisible(true);
});
Expand Down
61 changes: 52 additions & 9 deletions src/main/java/edu/project/Store.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,18 @@
import java.util.ArrayList;
import java.util.Objects;
import java.util.function.Consumer;

import javax.swing.SwingUtilities;

import org.jxmapviewer.viewer.GeoPosition;

/**
* Acts as the container for the application state and provides a
* reactive interface for notifying any listeners (e.g. UI components) for any
* changes.
*/
public class Store {
import edu.project.api.WeatherCurrentData;
import edu.project.api.WeatherForecast5Data;

public class Store {
public Store() {
setLocation(new GeoPosition(Config.MAP_INIT_LAT, Config.MAP_INIT_LON));
}

/* Location */
/* location */

private GeoPosition location = new GeoPosition(0, 0);

Expand All @@ -42,4 +37,52 @@ public void setLocation(GeoPosition position) {
public void addLocationListener(Consumer<GeoPosition> listener) {
locationListeners.add(listener);
}

/* weather current data */

private WeatherCurrentData weatherCurrentData;

public WeatherCurrentData getWeatherCurrentData() {
return weatherCurrentData;
}

public void setWeatherCurrentData(WeatherCurrentData data) {
if (Objects.equals(weatherCurrentData, data))
return;

weatherCurrentData = data;
SwingUtilities.invokeLater(() -> {
weatherCurrentDataListeners.forEach(listener -> listener.accept(data));
});
}

private ArrayList<Consumer<WeatherCurrentData>> weatherCurrentDataListeners = new ArrayList<>();

public void addWeatherCurrentDataListener(Consumer<WeatherCurrentData> listener) {
weatherCurrentDataListeners.add(listener);
}

/* weather forecast data */

private WeatherForecast5Data weatherForecast5Data;

public WeatherForecast5Data getWeatherForecast5Data() {
return weatherForecast5Data;
}

public void setWeatherForecast5Data(WeatherForecast5Data data) {
if (Objects.equals(weatherForecast5Data, data))
return;

weatherForecast5Data = data;
SwingUtilities.invokeLater(() -> {
weatherForecast5DataListeners.forEach(listener -> listener.accept(data));
});
}

private ArrayList<Consumer<WeatherForecast5Data>> weatherForecast5DataListeners = new ArrayList<>();

public void addWeatherForecast5DataListener(Consumer<WeatherForecast5Data> listener) {
weatherForecast5DataListeners.add(listener);
}
}
59 changes: 59 additions & 0 deletions src/main/java/edu/project/api/WeatherApi.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package edu.project.api;

import com.google.gson.Gson;

import edu.project.Config;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class WeatherApi {
private static final String CURRENT_WEATHER_URL = "http://api.openweathermap.org/data/2.5/weather";
private static final String FORECAST_WEATHER_URL = "http://api.openweathermap.org/data/2.5/forecast";

public WeatherCurrentData getCurrentWeather(String city) throws IOException {
String urlString = CURRENT_WEATHER_URL + "?q=" + city + "&appid=" + Config.OPENWEATHERMAP_API_KEY;
return fetchWeatherData(urlString, WeatherCurrentData.class);
}

public WeatherForecast5Data getWeatherForecast(String city) throws IOException {
String urlString = FORECAST_WEATHER_URL + "?q=" + city + "&appid=" + Config.OPENWEATHERMAP_API_KEY;
return fetchWeatherData(urlString, WeatherForecast5Data.class);
}

public WeatherCurrentData getCurrentWeather(double lat, double lon) throws IOException {
String urlString = CURRENT_WEATHER_URL + "?lat=" + lat + "&lon=" + lon + "&appid="
+ Config.OPENWEATHERMAP_API_KEY;
return fetchWeatherData(urlString, WeatherCurrentData.class);
}

public WeatherForecast5Data getWeatherForecast(double lat, double lon) throws IOException {
String urlString = FORECAST_WEATHER_URL + "?lat=" + lat + "&lon=" + lon + "&appid="
+ Config.OPENWEATHERMAP_API_KEY;
return fetchWeatherData(urlString, WeatherForecast5Data.class);
}

private <T> T fetchWeatherData(String urlString, Class<T> clazz) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");

StringBuilder content;
try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
String inputLine;
content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
}

conn.disconnect();

String json = content.toString();
Gson gson = new Gson();
return gson.fromJson(json, clazz);
}
}
45 changes: 45 additions & 0 deletions src/main/java/edu/project/api/WeatherCurrentData.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package edu.project.api;

import com.google.gson.annotations.SerializedName;

public class WeatherCurrentData {
public String name;
public Main main;
public Wind wind;
public Clouds clouds;
public Rain rain;
public Sys sys;
public int visibility;
public long dt;

public static class Main {
public float temp;
public float feels_like;
public float temp_min;
public float temp_max;
public float pressure;
public int humidity;
public float sea_level;
public float grnd_level;
}

public static class Wind {
public float speed;
public int deg;
public float gust;
}

public static class Clouds {
public int all;
}

public static class Rain {
@SerializedName("1h")
public float one_hour;
}

public static class Sys {
public long sunrise;
public long sunset;
}
}
30 changes: 30 additions & 0 deletions src/main/java/edu/project/api/WeatherForecast5Data.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package edu.project.api;

import java.util.List;

public class WeatherForecast5Data {
public List<WeatherList> list;

public static class WeatherList {
public Main main;
public List<Weather> weather;
public Wind wind;
public String dt_txt;

public static class Main {
public float temp;
public float pressure;
public int humidity;
}

public static class Weather {
public String description;
public String icon;
}

public static class Wind {
public float speed;
public int deg;
}
}
}
12 changes: 6 additions & 6 deletions src/main/java/edu/project/components/GeoMap.java
daawaan4U marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelListener;
import java.io.IOException;
import java.util.HashSet;

import javax.swing.event.MouseInputListener;
Expand Down Expand Up @@ -32,16 +33,16 @@ public GeoMap(Context context) {
MouseWheelListener mouseWheelListener = new ZoomMouseWheelListenerCursor(this);
addMouseWheelListener(mouseWheelListener);

// Configure overlay marker
WaypointPainter<DefaultWaypoint> waypointPainter = new WaypointPainter<DefaultWaypoint>();
HashSet<DefaultWaypoint> waypoints = new HashSet<DefaultWaypoint>();
WaypointPainter<DefaultWaypoint> waypointPainter = new WaypointPainter<>();
HashSet<DefaultWaypoint> waypoints = new HashSet<>();
DefaultWaypoint waypoint = new DefaultWaypoint();
waypoints.add(waypoint);
waypointPainter.setWaypoints(waypoints);

try {
waypointPainter.setRenderer(new GeoMapMarker());
} catch (Exception exception) {
exception.printStackTrace(System.err);
} catch (IOException e) {
e.printStackTrace();
}

// Display overlay marker
Expand All @@ -57,7 +58,6 @@ public void mouseClicked(MouseEvent event) {
}
});

// Update waypoint on location change events from application state
context.store.addLocationListener(position -> {
waypoint.setPosition(position);
repaint();
Expand Down
18 changes: 4 additions & 14 deletions src/main/java/edu/project/components/GeoMapMarker.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.jxmapviewer.JXMapViewer;
import org.jxmapviewer.viewer.DefaultWaypoint;
import org.jxmapviewer.viewer.WaypointRenderer;
Expand All @@ -26,19 +24,11 @@ public void paintWaypoint(Graphics2D graphics, JXMapViewer map, DefaultWaypoint
graphics = (Graphics2D) graphics.create();
Point2D point = map.getTileFactory().geoToPixel(waypoint.getPosition(), map.getZoom());

graphics.drawImage(
markerShadowImage,
(int) point.getX() - 12,
(int) point.getY() - markerShadowImage.getHeight(),
null);

graphics.drawImage(
markerIconImage,
(int) point.getX() - markerIconImage.getWidth() / 2,
(int) point.getY() - markerIconImage.getHeight(),
null);
graphics.drawImage(markerShadowImage, (int) point.getX() - 12,
(int) point.getY() - markerShadowImage.getHeight(), null);
graphics.drawImage(markerIconImage, (int) point.getX() - markerIconImage.getWidth() / 2,
(int) point.getY() - markerIconImage.getHeight(), null);

graphics.dispose();
}

}
24 changes: 24 additions & 0 deletions src/main/java/edu/project/services/WeatherService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package edu.project.services;

import edu.project.Context;
import edu.project.api.WeatherCurrentData;
import edu.project.api.WeatherForecast5Data;

public class WeatherService {
public WeatherService(Context context) {
context.store.addLocationListener(position -> {
try {
double lat = position.getLatitude();
double lon = position.getLongitude();

WeatherCurrentData currentData = context.weatherApi.getCurrentWeather(lat, lon);
WeatherForecast5Data forecastData = context.weatherApi.getWeatherForecast(lat, lon);

context.store.setWeatherCurrentData(currentData);
context.store.setWeatherForecast5Data(forecastData);
} catch (Exception e) {
e.printStackTrace();
}
});
}
}
Loading