PRA2024/src/main/java/model/weatherForecast.java

105 lines
3.2 KiB
Java

package model;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
/*
Klasa weatherForecast zawierajaca metody pozwalajace na zapis do poszczegolnych formatow.
Obiekty tworzone poprzez wywolanie klasy zbierane sa do listy ulatwiajacej generacje plikow json i xml.
Do zapisu do pdf wykorzystywany jest plik temporary zbierajacy wywolane prognozy w formacie txt.
*/
public class weatherForecast {
public static final List<weatherForecast> allEntries = new ArrayList<>();
private final String cityName;
private final String description;
private final double temperature;
private final int pressure;
private final int humidity;
public weatherForecast(String cityName, String description, double temperature,
int pressure, int humidity) {
this.cityName = cityName;
this.description = description;
this.temperature = temperature;
this.pressure = pressure;
this.humidity = humidity;
allEntries.add(this);
}
public String prepareForecastString() {
String weatherForecastString = String.format("""
city: %s
description: %s
temperature[K]: %.2f
pressure[hPa]: %d
humidity[%%]: %d
--------------------""", this.cityName, this.description, this.temperature,
this.pressure, this.humidity);
return weatherForecastString;
}
public static void saveToJson(String outputFile) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File(outputFile), allEntries);
}
public static void saveToXml(String outputFile) throws IOException {
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.writeValue(new File(outputFile), allEntries);
}
public static void saveToPdf(String inputFile, String outputFile) {
try (BufferedReader br = new BufferedReader(new FileReader(inputFile))) {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(outputFile));
document.open();
String line;
while ((line = br.readLine()) != null) {
document.add(new Paragraph(line));
}
document.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static List<weatherForecast> getAllEntries() {
return new ArrayList<>(allEntries);
}
public String getCityName() {
return cityName;
}
public String getDescription() {
return description;
}
public double getTemperature() {
return temperature;
}
public int getPressure() {
return pressure;
}
public int getHumidity() {
return humidity;
}
}