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

nbbrd.io.FileFormatter Maven / Gradle / Ivy

package nbbrd.io;

import internal.io.ComposeFileFormatter;
import internal.io.EncodingFileFormatter;
import internal.io.FunctionalFileFormatter;
import internal.io.LockingFileFormatter;
import internal.io.text.LegacyFiles;
import lombok.NonNull;
import nbbrd.design.StaticFactoryMethod;
import nbbrd.io.function.IOBiConsumer;
import nbbrd.io.function.IOFunction;
import nbbrd.io.function.IOSupplier;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
import java.util.zip.GZIPOutputStream;

public interface FileFormatter {

    default void formatFile(@NonNull T value, @NonNull File target) throws IOException {
        try (OutputStream resource = LegacyFiles.openOutputStream(target)) {
            formatStream(value, resource);
        }
    }

    default void formatPath(@NonNull T value, @NonNull Path target) throws IOException {
        Optional file = Resource.getFile(target);
        if (file.isPresent()) {
            formatFile(value, file.get());
        } else {
            formatStream(value, () -> Files.newOutputStream(target));
        }
    }

    default void formatStream(@NonNull T value, @NonNull IOSupplier target) throws IOException {
        try (OutputStream resource = LegacyFiles.openOutputStream(target)) {
            formatStream(value, resource);
        }
    }

    void formatStream(@NonNull T value, @NonNull OutputStream resource) throws IOException;

    default  @NonNull FileFormatter compose(@NonNull IOFunction before) {
        return new ComposeFileFormatter<>(this, before);
    }

    @StaticFactoryMethod
    static  @NonNull FileFormatter onFormattingStream(@NonNull IOBiConsumer function) {
        return new FunctionalFileFormatter<>(function);
    }

    @StaticFactoryMethod
    static  @NonNull FileFormatter onFormattingGzip(@NonNull FileFormatter formatter) {
        return new EncodingFileFormatter<>(formatter, GZIPOutputStream::new);
    }

    @StaticFactoryMethod
    static  @NonNull FileFormatter onFormattingLock(@NonNull FileFormatter formatter) {
        return new LockingFileFormatter<>(formatter);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy