This commit is contained in:
Mikołaj Krenc 2023-12-16 22:53:34 +01:00
commit ef726f68c2
16 changed files with 443 additions and 0 deletions

38
.gitignore vendored Normal file
View File

@ -0,0 +1,38 @@
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### 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

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>

13
.idea/misc.xml Normal file
View File

@ -0,0 +1,13 @@
<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_17" default="true" project-jdk-name="17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

65
pom.xml Normal file
View File

@ -0,0 +1,65 @@
<?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.example</groupId>
<artifactId>Projekt-nr-1</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.10</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.12.3</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0.1</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.1</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,24 @@
package projekt;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
public class CityCoordinatesLoader {
public static Map<String, Coordinates> loadCityCoordinates(String jsonFilePath) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.readValue(new File(jsonFilePath),
new TypeReference<Map<String, Coordinates>>() {
});
} catch (IOException e) {
e.printStackTrace();
return Collections.emptyMap();
}
}
}

View File

@ -0,0 +1,22 @@
package projekt;
public class Coordinates {
private double lat;
private double lon;
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLon() {
return lon;
}
public void setLon(double lon) {
this.lon = lon;
}
}

View File

@ -0,0 +1,21 @@
package projekt;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.File;
import java.io.IOException;
public class DataSaver {
public static void saveDataAsJson(String data, String filePath) {
ObjectMapper mapper = new ObjectMapper();
try {
ObjectNode dataNode = mapper.createObjectNode();
dataNode.put("weatherData", data);
mapper.writeValue(new File(filePath), dataNode);
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,56 @@
package projekt;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class DataSaver2 {
public static void saveAsJson(String data, String filePath) {
ObjectMapper mapper = new ObjectMapper();
ObjectNode node = mapper.createObjectNode();
node.put("weatherData", data);
try {
mapper.writeValue(new File(filePath), node);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void saveAsXml(org.w3c.dom.Document doc, String filePath) {
try {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filePath));
transformer.transform(source, result);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void saveAsPdf(String data, String filePath) {
Document pdfDocument = new Document();
try {
PdfWriter.getInstance(pdfDocument, new FileOutputStream(filePath));
pdfDocument.open();
pdfDocument.add(new Paragraph(data));
pdfDocument.close();
} catch (FileNotFoundException | DocumentException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,112 @@
package projekt;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
import java.util.*;
public class Main {
public static void main(String[] args) {
try {
String jsonFilePath = "src/main/resources/miasta.json";
String chosenCity;
String temperature = "", pressure = "", humidity = "";
Map<String, Coordinates> cityCoordinatesMap = CityCoordinatesLoader.loadCityCoordinates(jsonFilePath);
List<String> miasta = new ArrayList<>(cityCoordinatesMap.keySet());
Set<String> formatyZapisu = new HashSet<>(Arrays.asList("PDF", "JSON", "XML"));
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("P-Podaj miasto, Z-Zakończ");
String opcja1 = scan.nextLine();
switch (opcja1) {
case "P":
chosenCity = wybierzMiastoIWyswietlDane(scan, miasta);
WeatherService weatherService = new WeatherService();
Coordinates coords = cityCoordinatesMap.get(chosenCity);
String xmlString = weatherService.getWeatherData(String.valueOf(coords.getLat()), String.valueOf(coords.getLon()));
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new StringReader(xmlString)));
doc.getDocumentElement().normalize();
temperature = getAttributeValue(doc, "temperature", "value");
pressure = getAttributeValue(doc, "pressure", "value");
humidity = getAttributeValue(doc, "humidity", "value");
System.out.println("Temperatura: " + temperature + "°C");
System.out.println("Ciśnienie: " + pressure + " hPa");
System.out.println("Wilgotność: " + humidity + "%");
break;
case "Z":
if (wybierzFormatIZapisz(scan, formatyZapisu, temperature, pressure, humidity)) {
return;
}
break;
default:
System.out.println("Podano niedostępną opcję!");
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String wybierzMiastoIWyswietlDane(Scanner scan, List<String> miasta) {
String miasto;
while (true) {
System.out.println("Dostępne miasta: " + String.join(", ", miasta));
miasto = scan.nextLine();
if (miasta.contains(miasto)) {
break;
} else {
System.out.println("Nie można wyświetlić danych dla podanego miasta.");
}
}
return miasto;
}
private static boolean wybierzFormatIZapisz(Scanner scan, Set<String> formatyZapisu, String temperature, String pressure, String humidity) {
while (true) {
System.out.print("Podaj format zapisu [PDF, JSON, XML]: ");
String opcja2 = scan.nextLine();
if (formatyZapisu.contains(opcja2)) {
System.out.println("Zapis w formacie " + opcja2);
String danePogodowe = temperature + "°C, " + pressure + "hPa, " + humidity + "%";
if (Objects.equals(opcja2, "PDF")) {
DataSaver2.saveAsPdf(danePogodowe, "src/main/resources/pogoda.pdf");
} else if (Objects.equals(opcja2, "JSON")) {
DataSaver2.saveAsJson(danePogodowe, "src/main/resources/pogoda.json");
} else if (Objects.equals(opcja2, "XML")) {
Document weatherDoc = XmlCreator.createWeatherDocument(temperature, pressure, humidity);
if (weatherDoc != null) {
DataSaver2.saveAsXml(weatherDoc, "src/main/resources/pogoda.xml");
}
}
return true;
} else {
System.out.println("Podano niewłaściwy format!");
}
}
}
private static String getAttributeValue(Document doc, String tagName, String attribute) {
NodeList nodeList = doc.getElementsByTagName(tagName);
if (nodeList != null && nodeList.getLength() > 0) {
Element element = (Element) nodeList.item(0);
return element.getAttribute(attribute);
}
return "";
}
}

View File

@ -0,0 +1,31 @@
package projekt;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class WeatherService {
private static final String API_KEY = "d1c62029fc387217638fd3deda524ece";
private static final String BASE_URL = "https://api.openweathermap.org/data/2.5/weather";
public String getWeatherData(String lat, String lon) {
String url = String.format("%s?lat=%s&lon=%s&appid=%s&units=metric&mode=xml", BASE_URL, lat, lon, API_KEY);
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet request = new HttpGet(url);
try (CloseableHttpResponse response = httpClient.execute(request)) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}

View File

@ -0,0 +1,36 @@
package projekt;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
public class XmlCreator {
public static Document createWeatherDocument(String temperature, String pressure, String humidity) {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("WeatherData");
doc.appendChild(rootElement);
appendWeatherElement(doc, rootElement, "Temperatura", temperature);
appendWeatherElement(doc, rootElement, "Ciśnienie", pressure);
appendWeatherElement(doc, rootElement, "Wilgotność", humidity);
return doc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static void appendWeatherElement(Document doc, Element parent, String name, String value) {
Element element = doc.createElement(name);
element.appendChild(doc.createTextNode(value));
parent.appendChild(element);
}
}

View File

@ -0,0 +1,7 @@
{
"Warszawa": {"lat": 52.2298, "lon": 21.0118},
"Szczecin": {"lat": 53.4285, "lon": 14.5528},
"Łódź": {"lat": 51.7592, "lon": 19.4560},
"Poznań": {"lat": 52.4064, "lon": 16.9252},
"Białystok": {"lat": 53.1325, "lon": 23.1688}
}

View File

@ -0,0 +1 @@
{"weatherData":"7.8°C, 1028hPa, 88%"}

View File

@ -0,0 +1 @@
{"weatherData":"7.8°C, 1028hPa, 88%"}

View File

@ -0,0 +1 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?><WeatherData><Temperature>20</Temperature><Pressure>1013</Pressure><Humidity>80</Humidity></WeatherData>