PROG_LAB5-7/src/main/java/me/zinch/files/DbController.java

74 lines
2.5 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package me.zinch.files;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DatabindException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import me.zinch.exceptions.DbInitializationException;
import me.zinch.models.Product;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;
import java.util.Map;
public class DbController {
private static final XmlMapper xmlMapper = XmlMapper.builder().addModule(new JavaTimeModule()).build();
private static final String path;
static {
Map<String, String> env = System.getenv();
path = env.getOrDefault("DB_FILE", "");
xmlMapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL);
}
private static class Products {
@JacksonXmlElementWrapper(useWrapping = false)
@JacksonXmlProperty(localName = "Product")
private List<Product> products;
public Products() {}
public Products(List<Product> list) {
this.products = list;
}
public List<Product> getProducts() {
return products;
}
}
public static List<Product> loadDb() throws IOException {
try {
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(path));
Products collection = xmlMapper.readValue(bufferedInputStream, Products.class);
bufferedInputStream.close();
return collection.getProducts();
} catch (FileNotFoundException e) {
throw new FileNotFoundException("Не удалось найти файл " + path);
} catch (DatabindException e) {
throw new DbInitializationException();
} catch (IOException e) {
throw new IOException("Произошла неожиданная ошибка во время работы с файлом!");
}
}
public static void saveDb(List<Product> list) throws IOException {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(path));
xmlMapper.writeValue(outputStreamWriter, new Products(list));
outputStreamWriter.close();
} catch (FileNotFoundException e) {
throw new FileNotFoundException(e.getMessage());
} catch (IOException e) {
throw new IOException(e);
}
}
}