Skip to content

Commit

Permalink
Get the current celsius degree of a city
Browse files Browse the repository at this point in the history
  • Loading branch information
sefadegirmenci committed Jul 20, 2022
1 parent ed06a68 commit 8b73afd
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.eistgeist.flightsystem.rest;

import com.eistgeist.flightsystem.service.WeatherService;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
@AllArgsConstructor
@CrossOrigin
public class WeatherController {
private WeatherService weatherService;

@GetMapping("weather/{cityName}")
public ResponseEntity<Float> getWeather(@PathVariable String cityName) {
float temperature = weatherService.getWeather(cityName);
if(temperature == 0) return new ResponseEntity<>((float)0, HttpStatus.valueOf(402));
return ResponseEntity.ok(temperature);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package com.eistgeist.flightsystem.service;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.StringTokenizer;

@Service
@AllArgsConstructor
public class WeatherService {

public float getWeather(String cityName) {
float temperature = 0;
try {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.version(HttpClient.Version.HTTP_2)
.uri(URI.create("http://api.weatherapi.com/v1/current.json?key=447cdd8e041443e3adb182013222007&q="+cityName+"&aqi=no"))
.GET()
.build();
HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
String weatherResponse = response.body().toString();
StringTokenizer tokenizer = new StringTokenizer(weatherResponse,", :");
while(tokenizer.hasMoreTokens()) {
String nextToken = tokenizer.nextToken();
if(nextToken.contains("temp_c")) {
System.out.println(nextToken);
String temperatureString = tokenizer.nextToken();
temperature= Float.parseFloat(temperatureString);
}
}
}
catch (Exception e) {
e.printStackTrace();
return temperature;
}
return temperature;
}
}

0 comments on commit 8b73afd

Please sign in to comment.