Skip to content

Commit

Permalink
Updated implementation of Weather services.
Browse files Browse the repository at this point in the history
  • Loading branch information
geraldywz committed Mar 7, 2022
1 parent 69e53f1 commit e8a3378
Show file tree
Hide file tree
Showing 5 changed files with 181 additions and 56 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import static tfip.strava.util.Constants.*;

import java.util.List;
import java.util.Optional;

import com.google.gson.Gson;
Expand All @@ -29,7 +30,7 @@ public class WeatherRestController {

@GetMapping()
public ResponseEntity<String> getAllUsers() {
Optional<Weather> weather = weatherSvc.getWeather();
Optional<List<Weather>> weather = weatherSvc.getWeather();
if (weather.isEmpty()) {
logger.info("FORECAST >>>>> NOT AVAILABLE.");
return ResponseEntity
Expand Down
63 changes: 30 additions & 33 deletions src/main/java/tfip/strava/model/Weather.java
Original file line number Diff line number Diff line change
@@ -1,54 +1,51 @@
package tfip.strava.model;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class Weather {

private String description;
private double temp;
private String name;
private String forecast;
private double lat;
private double lng;

public Weather() {
}

public Weather(String description, double temp) {
this.description = description;
this.temp = temp;
public Weather(String name, double lat, double lng) {
this.name = name;
this.lat = lat;
this.lng = lng;
}

public String getName() {
return this.name;
}

public String getDescription() {
return this.description;
public void setName(String name) {
this.name = name;
}

public void setDescription(String description) {
this.description = description;
public String getForecast() {
return this.forecast;
}

public double getTemp() {
return this.temp;
public void setForecast(String forecast) {
this.forecast = forecast;
}

public void setTemp(double temp) {
this.temp = temp;
public double getLat() {
return this.lat;
}

public static Weather toWeather(String json) {
JsonObject openWeather = JsonParser
.parseString(json)
.getAsJsonObject();
return new Weather(
openWeather
.get("weather")
.getAsJsonArray()
.get(0)
.getAsJsonObject()
.get("description")
.getAsString(),
public void setLat(double lat) {
this.lat = lat;
}

openWeather
.get("main")
.getAsJsonObject()
.get("temp")
.getAsDouble());
public double getLng() {
return this.lng;
}

public void setLng(double lng) {
this.lng = lng;
}

}
73 changes: 73 additions & 0 deletions src/main/java/tfip/strava/model/Workout.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package tfip.strava.model;

import java.util.List;

import org.springframework.jdbc.support.rowset.SqlRowSet;

import tfip.strava.util.ListToStringConverter;

public class Workout {

private int id;
private Long start;
private List<String> waypoints;
private double distance;
private int user_id;

public Workout(int id, Long start, List<String> waypoints, double distance, int user_id) {
this.id = id;
this.start = start;
this.waypoints = waypoints;
this.distance = distance;
this.user_id = user_id;
}

public int getId() {
return this.id;
}

public void setId(int id) {
this.id = id;
}

public Long getStart() {
return this.start;
}

public void setStart(Long start) {
this.start = start;
}

public List<String> getWaypoints() {
return this.waypoints;
}

public void setWaypoints(List<String> waypoints) {
this.waypoints = waypoints;
}

public double getDistance() {
return this.distance;
}

public void setDistance(double distance) {
this.distance = distance;
}

public int getUser_id() {
return this.user_id;
}

public void setUser_id(int user_id) {
this.user_id = user_id;
}

public static Workout populate(SqlRowSet rs) {
return new Workout(
rs.getInt("id"),
rs.getDate("start").getTime(),
ListToStringConverter.toList(rs.getString("waypoints")),
rs.getDouble("distance"),
rs.getInt("user_id"));
}
}
94 changes: 75 additions & 19 deletions src/main/java/tfip/strava/service/WeatherApiService.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,31 +13,29 @@

import static tfip.strava.util.Constants.*;

import java.util.Objects;
import java.sql.Timestamp;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

@Service
public class WeatherApiService {

private final Logger logger = LoggerFactory.getLogger(WeatherApiService.class);

private final String appId;

public WeatherApiService() {
// appId = System.getenv(ENV_OPENWEATHERMAP_KEY);
appId = "a785a8a212098474da9f29d61abc06cf";
logger.info("OWM API KEY >>>>> " + appId);
if (Objects.isNull(appId) || appId.length() == 0) {
logger.warn("OWM Key is not set".formatted(ENV_OPENWEATHERMAP_KEY));
}
}

public Optional<Weather> getWeather() {
Optional<Weather> weather = Optional.empty();
public Optional<List<Weather>> getWeather() {
Optional<List<Weather>> weather = Optional.empty();
final String url = generateURI();
logger.info("OWM API URL >>>>> " + url);
try {
weather = Optional.of(Weather.toWeather(
weather = Optional.of(process(
getResponse(url)));
} catch (Exception e) {
e.printStackTrace();
Expand All @@ -63,11 +61,69 @@ private String getResponse(String url) {

private String generateURI() {
return UriComponentsBuilder
.fromUriString(URL_OPENWEATHERMAP_ENDPOINT)
.queryParam("q", "Singapore")
.queryParam("units", "metric")
.queryParam("appid", appId)
.fromUriString(URL_NEA_2HR_ENDPOINT)
.toUriString();
}

private List<Weather> process(String json) {
List<Weather> weatherMap = new LinkedList<>();
JsonObject neaWeather = JsonParser
.parseString(json)
.getAsJsonObject();

JsonArray metadata = neaWeather.get("area_metadata").getAsJsonArray();
for (JsonElement jsonElement : metadata) {
JsonObject w = jsonElement.getAsJsonObject();
weatherMap.add(
new Weather(
w.get("name")
.getAsString(),
w.get("label_location")
.getAsJsonObject()
.get("latitude")
.getAsDouble(),
w.get("label_location")
.getAsJsonObject()
.get("longitude")
.getAsDouble()));
}

Timestamp now = new Timestamp(
new java.util.Date()
.getTime());
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX");

JsonArray items = neaWeather.get("items").getAsJsonArray();
for (JsonElement jsonElement : items) {
JsonObject v = jsonElement
.getAsJsonObject()
.get("valid_period")
.getAsJsonObject();
ZonedDateTime start = ZonedDateTime.parse(
v.get("start").getAsString(),
formatter);
ZonedDateTime end = ZonedDateTime.parse(
v.get("end").getAsString(),
formatter);
if (start.toLocalDateTime().isBefore(now.toLocalDateTime()) &&
end.toLocalDateTime().isAfter(now.toLocalDateTime())) {
JsonArray x = jsonElement
.getAsJsonObject()
.get("forecasts")
.getAsJsonArray();
for (int i = 0; i < x.size(); i++) {
String forecast = x.get(i)
.getAsJsonObject()
.get("forecast")
.getAsString();
weatherMap
.get(i)
.setForecast(forecast);
}
break;
}
}
return weatherMap;
}

}
4 changes: 1 addition & 3 deletions src/main/java/tfip/strava/util/Constants.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ public class Constants {
public static final String API_USER_ENDPOINT = "/api/user";
public static final String API_WEATHER_ENDPOINT = "/api/weather";

public static final String ENV_OPENWEATHERMAP_KEY = "OWM_KEY";

public static final String URL_OPENWEATHERMAP_ENDPOINT = "http://api.openweathermap.org/data/2.5/weather";
public static final String URL_NEA_2HR_ENDPOINT = "https://api.data.gov.sg/v1/environment/2-hour-weather-forecast";

}

0 comments on commit e8a3378

Please sign in to comment.