All Downloads are FREE. Search and download functionalities are using the official Maven repository.

ch.fritteli.maze.generator.renderer.pdffile.PDFFileRenderer Maven / Gradle / Ivy

Go to download

A-Maze-R, The Maze Generator. It is a library for generating mazes in various output formats.

The newest version!
package ch.fritteli.maze.generator.renderer.pdffile;

import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.renderer.Renderer;
import ch.fritteli.maze.generator.renderer.pdf.PDFRenderer;
import io.vavr.control.Option;
import io.vavr.control.Try;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.NoSuchElementException;

@Slf4j
public class PDFFileRenderer implements Renderer {

    @NotNull
    private static final PDFRenderer PDF_RENDERER = PDFRenderer.newInstance();
    @NotNull
    private Option targetFile;

    private PDFFileRenderer() {
        this.targetFile = Try
                .of(() -> Files.createTempFile("maze_", ".pdf"))
                .onFailure(ex -> log.error("Unable to set default target file.", ex))
                .toOption();
    }

    @NotNull
    public static PDFFileRenderer newInstance() {
        return new PDFFileRenderer();
    }

    public boolean isTargetFileDefinedAndWritable() {
        return this.targetFile
                .map(Path::toFile)
                .exists(File::canWrite);
    }

    @NotNull
    public PDFFileRenderer setTargetFile(@NotNull final Path targetFile) {
        this.targetFile = Option.of(targetFile);
        return this;
    }

    @NotNull
    @Override
    public Path render(@NotNull final Maze maze) {
        if (!this.isTargetFileDefinedAndWritable()) {
            try {
                Files.createFile(this.targetFile.get());
            } catch (IOException | NoSuchElementException e) {
                throw new IllegalArgumentException("Cannot write to target file.", e);
            }
        }
        final ByteArrayOutputStream bytes = PDF_RENDERER.render(maze);
        final Path outputFile = this.targetFile.get();
        try {
            bytes.writeTo(Files.newOutputStream(outputFile));
        } catch (IOException e) {
            log.error("Failed writing to file " + outputFile.normalize(), e);
        }
        return outputFile;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy