56 lines
1.6 KiB
Java
56 lines
1.6 KiB
Java
package de.ph87.electro.circuit;
|
|
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
|
|
import javax.imageio.ImageIO;
|
|
import java.awt.image.BufferedImage;
|
|
import java.io.*;
|
|
|
|
import static de.ph87.electro.circuit.CircuitPainter.paintCircuit;
|
|
|
|
@Slf4j
|
|
public class CircuitIOService {
|
|
|
|
private static final ObjectMapper objectMapper = new ObjectMapper().findAndRegisterModules();
|
|
|
|
public static void save(final Circuit circuit) {
|
|
if (!circuit.isDirty()) {
|
|
return;
|
|
}
|
|
if (circuit.getFile() == null) {
|
|
circuit.setFile(new File("./data/%s.json".formatted(circuit.getCreated())));
|
|
}
|
|
try {
|
|
if (circuit.getFile().getParentFile().mkdirs()) {
|
|
log.info("Directory created: {}", circuit.getFile().getParent());
|
|
}
|
|
CircuitIOService.serialize(circuit, new FileOutputStream(circuit.getFile()));
|
|
circuit.setDirty(false);
|
|
} catch (IOException e) {
|
|
log.error(e.toString());
|
|
}
|
|
|
|
final BufferedImage img = paintCircuit(circuit, 1920, 1080);
|
|
try {
|
|
ImageIO.write(img, "PNG", circuit.getPreviewFile());
|
|
} catch (IOException e) {
|
|
log.error(e.toString());
|
|
}
|
|
}
|
|
|
|
public static Circuit load(final File file) throws IOException {
|
|
return load(null, new FileInputStream(file));
|
|
}
|
|
|
|
public static Circuit load(final File file, final InputStream stream) throws IOException {
|
|
final CircuitDto dto = objectMapper.readValue(stream, CircuitDto.class);
|
|
return new Circuit(file, dto);
|
|
}
|
|
|
|
public static void serialize(final Circuit circuit, final OutputStream stream) throws IOException {
|
|
objectMapper.writeValue(stream, new CircuitDto(circuit));
|
|
}
|
|
|
|
}
|