final commit project v1

This commit is contained in:
Adam Gulczyński 2023-12-15 23:51:44 +01:00
commit 2486e64be2
26 changed files with 793 additions and 0 deletions

2
.env Normal file
View File

@ -0,0 +1,2 @@
API_KEY=620e5e3fe298cdf4c0e435e2c8f4eb8e
BASE_PATH=/Users/adamgulczynski/IdeaProjects/project1/src/main/java/org/adamgulczynski/

2
.env.example Normal file
View File

@ -0,0 +1,2 @@
API_KEY=
BASE_PATH=

29
.gitignore vendored Normal file
View File

@ -0,0 +1,29 @@
### IntelliJ IDEA ###
out/
!**/src/main/**/out/
!**/src/test/**/out/
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

8
.idea/.gitignore vendored Normal file
View File

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

17
.idea/aws.xml Normal file
View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="accountSettings">
<option name="activeProfile" value="profile:default" />
<option name="activeRegion" value="eu-central-1" />
<option name="recentlyUsedProfiles">
<list>
<option value="profile:default" />
</list>
</option>
<option name="recentlyUsedRegions">
<list>
<option value="eu-central-1" />
</list>
</option>
</component>
</project>

13
.idea/compiler.xml Normal file
View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="project1" />
</profile>
</annotationProcessing>
</component>
</project>

7
.idea/encodings.xml Normal file
View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
</project>

View File

@ -0,0 +1,64 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyCompatibilityInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ourVersions">
<value>
<list size="7">
<item index="0" class="java.lang.String" itemvalue="3.7" />
<item index="1" class="java.lang.String" itemvalue="3.8" />
<item index="2" class="java.lang.String" itemvalue="3.9" />
<item index="3" class="java.lang.String" itemvalue="3.10" />
<item index="4" class="java.lang.String" itemvalue="3.11" />
<item index="5" class="java.lang.String" itemvalue="3.10" />
<item index="6" class="java.lang.String" itemvalue="3.11" />
</list>
</value>
</option>
</inspection_tool>
<inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredPackages">
<value>
<list size="24">
<item index="0" class="java.lang.String" itemvalue="httpx" />
<item index="1" class="java.lang.String" itemvalue="six" />
<item index="2" class="java.lang.String" itemvalue="python-dateutil" />
<item index="3" class="java.lang.String" itemvalue="aiofiles" />
<item index="4" class="java.lang.String" itemvalue="h11" />
<item index="5" class="java.lang.String" itemvalue="MarkupSafe" />
<item index="6" class="java.lang.String" itemvalue="numpy" />
<item index="7" class="java.lang.String" itemvalue="rfc3986" />
<item index="8" class="java.lang.String" itemvalue="click" />
<item index="9" class="java.lang.String" itemvalue="Jinja2" />
<item index="10" class="java.lang.String" itemvalue="sniffio" />
<item index="11" class="java.lang.String" itemvalue="demjson" />
<item index="12" class="java.lang.String" itemvalue="addict" />
<item index="13" class="java.lang.String" itemvalue="pandas" />
<item index="14" class="java.lang.String" itemvalue="starlette" />
<item index="15" class="java.lang.String" itemvalue="certifi" />
<item index="16" class="java.lang.String" itemvalue="pytz" />
<item index="17" class="java.lang.String" itemvalue="uvicorn" />
<item index="18" class="java.lang.String" itemvalue="itsdangerous" />
<item index="19" class="java.lang.String" itemvalue="justpy" />
<item index="20" class="java.lang.String" itemvalue="websockets" />
<item index="21" class="java.lang.String" itemvalue="httpcore" />
<item index="22" class="java.lang.String" itemvalue="idna" />
<item index="23" class="java.lang.String" itemvalue="psycopg2" />
</list>
</value>
</option>
</inspection_tool>
<inspection_tool class="PyUnresolvedReferencesInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredIdentifiers">
<list>
<option value="blog.models.Post.objects" />
<option value="reviews.models.Review.objects" />
<option value="django.db.models.fields.related.OneToOneField.email" />
<option value="accounts.models.UserProfile.objects" />
<option value="accounts.models.User.DoesNotExist" />
<option value="vendor.models.Vendor.objects" />
</list>
</option>
</inspection_tool>
</profile>
</component>

25
.idea/jarRepositories.xml Normal file
View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="com.e-iceblue" />
<option name="name" value="e-iceblue" />
<option name="url" value="https://repo.e-iceblue.com/nexus/content/groups/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://repo.maven.apache.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
</component>
</project>

12
.idea/misc.xml Normal file
View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="openjdk-21" project-jdk-type="JavaSDK" />
</project>

7
README.md Normal file
View File

@ -0,0 +1,7 @@
# Java pracownia project 1
### Działanie programu:
Po uruchomieniu programu, w konsoli należy wybrac jedno z miast (wielkość liter nie ma znaczenie)
Dane dotyczace miast znajduja sie w pliku `data.json`
Informacje w konsoli sa wuyswietlane po kolei i przy każdym etapie prosza o konkretna czynnosc.

84
pom.xml Normal file
View File

@ -0,0 +1,84 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>org.adamgulczynski</groupId>
<artifactId>project1</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.13.0</version>
</dependency>
<dependency>
<groupId>io.github.cdimascio</groupId>
<artifactId>dotenv-java</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20230227</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf</artifactId>
<version>9.12.0</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.12.4</version> <!-- Use the latest version available -->
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>2.1.7</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,52 @@
package org.adamgulczynski;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class DataFetcher {
private final String apiKey;
public DataFetcher(String apiKey) {
this.apiKey = apiKey;
}
public String fetchWeather(double latitude, double longitude) throws IllegalArgumentException {
if (latitude > 90 || latitude < -90) {
throw new IllegalArgumentException();
} else if (longitude > 180 || longitude < -180) {
throw new IllegalArgumentException();
}
String urlStr = "https://api.openweathermap.org/data/2.5/weather?lat="
+ latitude + "&lon=" + longitude + "&appid=" + this.apiKey;
try {
URL url = new URL(urlStr);
// Open a connection to the URL
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set the request method to GET
connection.setRequestMethod("GET");
// Read the response from the server
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}

View File

@ -0,0 +1,54 @@
package org.adamgulczynski;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonReader {
private Map<String, Map<String, Double>> dataMap;
public Map<String, Map<String, Double>> readFile(String filePath) {
// Create a map to store the data
Map<String, Map<String, Double>> cityDataMap = new HashMap<>();
try {
// Create ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
// Read JSON array from file into JsonNode
JsonNode jsonArray = objectMapper.readTree(new File(filePath));
for (JsonNode jsonNode : jsonArray) {
String city = jsonNode.get("city").asText();
double lat = jsonNode.get("lat").asDouble();
double lon = jsonNode.get("lon").asDouble();
// Create a map for latitude and longitude
Map<String, Double> latLngMap = new HashMap<>();
latLngMap.put("latitude", lat);
latLngMap.put("longitude", lon);
// Put the data into the main map
cityDataMap.put(city, latLngMap);
}
this.dataMap = cityDataMap;
} catch (IOException e) {
e.printStackTrace();
}
return cityDataMap;
}
public void printEntries() {
short index = 1;
Set<String> keys = this.dataMap.keySet();
for (String key : keys) {
System.out.println(index + ". " + key);
index++;
}
}
}

View File

@ -0,0 +1,97 @@
package org.adamgulczynski;
import java.util.*;
import io.github.cdimascio.dotenv.Dotenv;
public class Main {
public static void main(String[] args) {
// get env variables
Dotenv dotenv = Dotenv.load();
String basePath = dotenv.get("BASE_PATH");
String apiKey = dotenv.get("API_KEY");
// read city details from json file
JsonReader readJSON = new JsonReader();
Map<String, Map<String, Double>> cityDataMap = readJSON.readFile(basePath + "data.json");
// print available cities
System.out.println("Dostepne miasta:");
readJSON.printEntries();
DataFetcher dataFetcher = new DataFetcher(apiKey);
Scanner scanner = new Scanner(System.in);
List<WeatherData> weatherDataList = new ArrayList<>();
while (true) {
System.out.print("P-Podaj miasto, Z-Zakoncz: ");
String userInput = scanner.nextLine();
if (Objects.equals(userInput, "P") || Objects.equals(userInput, "p")) {
String chosenCity = scanner.nextLine().toLowerCase();
Map<String, Double> chosenCityData = (Map<String, Double>) cityDataMap.get(chosenCity);
if (cityDataMap.containsKey(chosenCity)) {
double latitude = (double) chosenCityData.get("latitude");
double longitude = (double) chosenCityData.get("longitude");
String weatherDataString;
try {
weatherDataString = dataFetcher.fetchWeather(latitude, longitude);
} catch (IllegalArgumentException e) {
System.out.println("Niepoprawne dane w pliku json");
continue;
}
System.out.println(weatherDataString);
// convert to WeatherData object
WeatherData weatherData = WeatherParser.parseWeatherToWeatherData(weatherDataString);
// display the data
System.out.println(weatherData);
// add data to a list, will be written to the file
weatherDataList.add(weatherData);
} else {
System.out.println("Nie ma takiego miasta.");
}
} else if (Objects.equals(userInput, "Z") || Objects.equals(userInput, "z")) {
label:
while (true) {
System.out.println("Do jakiego pliku chcesz zapisac dane? xml/json/pdf");
String userChoice = scanner.nextLine().toLowerCase();
String path = basePath + "weather";
switch (userChoice) {
case "xml":
WeatherData.writeToXmlFile(path, weatherDataList);
break label;
case "json":
WeatherData.writeToJsonFile(path, weatherDataList);
break label;
case "pdf":
WeatherData.writeToPdfFile(path, weatherDataList);
break label;
default:
System.out.println("Bledny format.");
break;
}
}
break;
} else {
System.out.println("Bledna wartosc, podaj 'P' lub 'Z'");
}
}
scanner.close();
}
}

View File

@ -0,0 +1,153 @@
package org.adamgulczynski;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import java.io.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
import java.util.List;
public class WeatherData {
@JsonProperty("miasto")
private final String city;
@JsonProperty("temperatura")
private final double temperature;
@JsonProperty("wilgotnosc")
private final int humidity;
@JsonProperty("wiatr")
private final double windSpeed;
@JsonProperty("zachmurzenie")
private final int clouds;
@JsonProperty("cisnienie")
private final int pressure;
public WeatherData(String city, double temperature, int humidity, double windSpeed, int clouds, int pressure) {
this.city = city;
this.temperature = temperature;
this.humidity = humidity;
this.windSpeed = windSpeed;
this.clouds = clouds;
this.pressure = pressure;
}
@Override
public String toString() {
return "Miasto: " + city + '\n' +
"Temperatura: " + temperature + " K\n" +
"Cisnienie: " + pressure + " hPa\n" +
"Wilgotnosc: " + humidity + "%\n" +
"Wiatr: " + windSpeed + " m/s\n" +
"Zachmurzenie: " + clouds + " %\n\n";
}
public String getCity() {
return city;
}
public double getTemperature() {
return temperature;
}
public int getHumidity() {
return humidity;
}
public double getWindSpeed() {
return windSpeed;
}
public int getClouds() {
return clouds;
}
public int getPressure() {
return pressure;
}
public static void writeToJsonFile(String filePath, List<WeatherData> weatherDataList) {
ObjectMapper objectMapper = new ObjectMapper();
String path = filePath + ".json";
try {
File file = new File(path);
ObjectWriter objectWriter = objectMapper.writer(new DefaultPrettyPrinter());
objectWriter.writeValue(file, weatherDataList);
System.out.println("Dane zapisane do: " + path);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void writeToXmlFile(String filePath, List<WeatherData> weatherDataList) {
XmlMapper xmlMapper = new XmlMapper();
String path = filePath + ".xml";
try {
File file = new File(path);
ObjectWriter objectWriter = xmlMapper.writerWithDefaultPrettyPrinter();
objectWriter.writeValue(file, weatherDataList);
System.out.println("Dane zapisane do: " + path);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void writeToTxtFile(String filePath, List<WeatherData> weatherDataList) {
StringBuilder content = new StringBuilder();
for (WeatherData data : weatherDataList) {
content.append(data.toString());
}
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath + ".txt"))) {
writer.write(content.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
public static void writeToPdfFile(String filePath, List<WeatherData> weatherDataList) {
// create .txt file
writeToTxtFile(filePath, weatherDataList);
BufferedReader input = null;
Document output = null;
try {
input = new BufferedReader(new FileReader(filePath + ".txt"));
output = new Document(PageSize.LETTER, 40, 40, 40, 40);
filePath = filePath + ".pdf";
PdfWriter.getInstance(output, new FileOutputStream(filePath));
output.open();
output.addAuthor("Adam Gulczynski");
output.addSubject("Projekt");
output.addTitle("Projekt");
String line = "";
while (null != (line = input.readLine())) {
System.out.println(line);
Paragraph p = new Paragraph(line);
p.setAlignment(Element.ALIGN_JUSTIFIED);
output.add(p);
}
System.out.println("Dane zapisane do: " + filePath);
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,20 @@
package org.adamgulczynski;
import org.json.JSONObject;
public class WeatherParser {
public static WeatherData parseWeatherToWeatherData(String response) {
JSONObject jsonObject = new JSONObject(response);
String city = jsonObject.getString("name");
double temperature = jsonObject.getJSONObject("main").getDouble("temp");
int humidity = jsonObject.getJSONObject("main").getInt("humidity");
double windSpeed = jsonObject.getJSONObject("wind").getDouble("speed");
int clouds = jsonObject.getJSONObject("clouds").getInt("all");
int pressure = jsonObject.getJSONObject("main").getInt("pressure");
return new WeatherData(city, temperature, humidity, windSpeed, clouds, pressure);
}
}

View File

@ -0,0 +1,37 @@
[
{
"city": "warsaw",
"lat": 52.2297,
"lon": 21.0122
},
{
"city": "london",
"lat": 51.5072,
"lon": 0.1276
},
{
"city": "poznan",
"lat": 52.41,
"lon": 16.93
},
{
"city": "berlin",
"lat": 52.52,
"lon": 13.41
},
{
"city": "barcelona",
"lat": 41.39,
"lon": 2.17
},
{
"city": "paris",
"lat": 48.86,
"lon": 2.35
},
{
"city": "stockholm",
"lat": 59.33,
"lon": 18.07
}
]

View File

@ -0,0 +1,110 @@
import org.adamgulczynski.DataFetcher;
import org.adamgulczynski.WeatherData;
import org.adamgulczynski.WeatherParser;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class WeatherDataTest {
@Test
void testWeatherRequestWithGoodCoordinates() throws IOException {
String sampleBody = """
{
"name": "london",
"main": {
"temp": 280.95,
"humidity": 79,
"pressure": 1038
},
"wind": {
"speed": 4.12
},
"clouds": {
"all": 100
}
}
""";
DataFetcher mockDataFetcher = mock(DataFetcher.class);
double lat = 12.2;
double lon = 22.3;
when(mockDataFetcher.fetchWeather(lat, lon))
.thenReturn(sampleBody);
WeatherData weatherData = WeatherParser.parseWeatherToWeatherData(mockDataFetcher.fetchWeather(lat, lon));
assertEquals(weatherData.getTemperature(), 280.95);
assertEquals(weatherData.getHumidity(), 79);
assertEquals(weatherData.getWindSpeed(), 4.12);
assertEquals(weatherData.getPressure(), 1038);
assertEquals(weatherData.getClouds(), 100);
}
@Test
void testWeatherRequestWithValidCoordinates() throws IOException {
String sampleBody = """
{
"name": "london",
"main": {
"temp": 280.95,
"humidity": 79,
"pressure": 1038
},
"wind": {
"speed": 4.12
},
"clouds": {
"all": 100
}
}
""";
DataFetcher mockDataFetcher = mock(DataFetcher.class);
double lat = 12.2;
double lon = 22.3;
when(mockDataFetcher.fetchWeather(lat, lon))
.thenReturn(sampleBody);
WeatherData weatherData = WeatherParser.parseWeatherToWeatherData(mockDataFetcher.fetchWeather(lat, lon));
assertEquals(weatherData.getTemperature(), 280.95);
assertEquals(weatherData.getHumidity(), 79);
assertEquals(weatherData.getWindSpeed(), 4.12);
assertEquals(weatherData.getPressure(), 1038);
assertEquals(weatherData.getClouds(), 100);
}
@Test
void testWeatherRequestWithInvalidLatitude() {
DataFetcher mockDataFetcher = new DataFetcher("tes");
// Using invalid coordinates
double invalidLat = 500.0;
double validLon = 22.3;
assertThrows(IllegalArgumentException.class, () -> {
mockDataFetcher.fetchWeather(invalidLat, validLon);
});
}
@Test
void testWeatherRequestWithInvalidLongitude() {
DataFetcher mockDataFetcher = new DataFetcher("tes");
// Using invalid coordinates
double validLat = 20.0;
double invalidLon = 522.3;
assertThrows(IllegalArgumentException.class, () -> {
mockDataFetcher.fetchWeather(validLat, invalidLon);
});
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.