Skip to content

Commit

Permalink
Implemented weather service.
Browse files Browse the repository at this point in the history
  • Loading branch information
geraldywz committed Mar 7, 2022
1 parent 69c6942 commit 091ab67
Show file tree
Hide file tree
Showing 6 changed files with 141 additions and 32 deletions.
2 changes: 0 additions & 2 deletions SCHEMA.SQL
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@ CREATE TABLE workouts(
waypoints VARCHAR(256) NOT NULL,
distance DECIMAL(7, 2) NOT NULL,
start DATETIME NOT NULL,
weather VARCHAR(64) NOT NULL,
weather_last_updated DATETIME NOT NULL,
user_id INT NOT NULL,
PRIMARY KEY(id),
FOREIGN KEY(user_id) REFERENCES users(id)
Expand Down
46 changes: 46 additions & 0 deletions src/main/java/tfip/strava/controller/WeatherRestController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package tfip.strava.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

import java.util.Optional;

import com.google.gson.Gson;

import tfip.strava.model.Weather;
import tfip.strava.service.WeatherApiService;

@RestController
@RequestMapping(path = API_WEATHER_ENDPOINT, produces = MediaType.APPLICATION_JSON_VALUE)
public class WeatherRestController {

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

@Autowired
private WeatherApiService weatherSvc;

@GetMapping()
public ResponseEntity<String> getAllUsers() {
Optional<Weather> weather = weatherSvc.getWeather();
if (weather.isEmpty()) {
logger.info("FORECAST >>>>> NOT AVAILABLE.");
return ResponseEntity
.notFound()
.build();
} else {
logger.info("FORECAST >>>>> RETRIEVED.");
return ResponseEntity
.ok()
.body(new Gson()
.toJson(weather.get()));
}
}
}
59 changes: 59 additions & 0 deletions src/main/java/tfip/strava/model/Weather.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package tfip.strava.model;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Weather {

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

private String description;
private double temp;

public Weather() {
}

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

public String getDescription() {
return this.description;
}

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

public double getTemp() {
return this.temp;
}

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

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(),

openWeather
.get("main")
.getAsJsonObject()
.get("temp")
.getAsDouble());
}
}
1 change: 0 additions & 1 deletion src/main/java/tfip/strava/repo/RouteRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -58,5 +58,4 @@ public List<Route> getRoutes(int userId) {
logger.info("DB FETCHING ROUTES >>>>> user_id: " + userId);
return routes;
}

}
60 changes: 31 additions & 29 deletions src/main/java/tfip/strava/service/WeatherApiService.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,40 @@
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import tfip.strava.model.Weather;

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

import java.util.Objects;
import java.util.Optional;

@Service
public class WeatherApiService {

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

public String getDirections(String origin, String destination) {
return getDirections(origin, destination, null);
}
private final String appId;

public String getDirections(String origin, String destination, String[] waypoints) {
final String url = generateURI(origin, destination, waypoints);
logger.info("GMap API URL >>>>> " + url);
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));
}
}

return getResponse(url);
public Optional<Weather> getWeather() {
Optional<Weather> weather = Optional.empty();
final String url = generateURI();
logger.info("OWM API URL >>>>> " + url);
try {
weather = Optional.of(Weather.toWeather(
getResponse(url)));
} catch (Exception e) {
e.printStackTrace();
}
return weather;
}

private String getResponse(String url) {
Expand All @@ -44,28 +61,13 @@ private String getResponse(String url) {
return json;
}

private String generateURI(String origin, String destination, String[] waypoints) {
UriComponentsBuilder uriBuilder = UriComponentsBuilder
.fromUriString("ipsumlorem.com")
.queryParam("origin", origin)
.queryParam("destination", destination);

if (waypoints != null && waypoints.length > 0) {
String pipe = "|";
String wp = "";
for (int i = 0; i < waypoints.length; i++) {
wp = wp.concat(waypoints[i]);
if (waypoints.length > 1 && i != waypoints.length - 1) {
wp = wp.concat(pipe);
}
}
uriBuilder = uriBuilder.queryParam("waypoints", wp);
}

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

public String genLatLng(String lat, String lng) {
return (lat + "," + lng).trim().replace(" ", "");
}
}
5 changes: 5 additions & 0 deletions src/main/java/tfip/strava/util/Constants.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,10 @@ public class Constants {
// API Related
public static final String API_ROUTE_ENDPOINT = "/api/route";
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";

}

0 comments on commit 091ab67

Please sign in to comment.