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

kr.jm.utils.flow.subscriber.JMFileSubscriber Maven / Gradle / Ivy

There is a newer version: 0.1.6.1
Show newest version
package kr.jm.utils.flow.subscriber;

import kr.jm.utils.JMFileAppender;
import kr.jm.utils.helper.JMJson;
import kr.jm.utils.helper.JMStream;

import java.nio.file.Path;
import java.util.function.Function;

/**
 * The type Jm file subscriber.
 *
 * @param  the type parameter
 */
public class JMFileSubscriber extends JMSubscriber implements
        AutoCloseable {

    private JMFileAppender fileAppender;

    /**
     * Instantiates a new Jm file subscriber.
     *
     * @param filePath the file path
     */
    public JMFileSubscriber(String filePath) {
        this(filePath, false);
    }

    /**
     * Instantiates a new Jm file subscriber.
     *
     * @param filePath         the file path
     * @param enableJsonString the enable json string
     */
    public JMFileSubscriber(String filePath, boolean enableJsonString) {
        this(filePath,
                enableJsonString ? JMJson::toJsonString : Object::toString);
    }

    /**
     * Instantiates a new Jm file subscriber.
     *
     * @param filePath         the file path
     * @param toStringFunction the to string function
     */
    public JMFileSubscriber(String filePath,
            Function toStringFunction) {
        this.fileAppender = new JMFileAppender(filePath);
        setDataConsumer(o -> JMStream.buildStream(o).map(toStringFunction)
                .forEach(this.fileAppender::appendLine));
    }

    /**
     * Gets file path.
     *
     * @return the file path
     */
    public Path getFilePath() {
        return this.fileAppender.getFilePath();
    }

    @Override
    public void close() {
        this.fileAppender.close();
    }
}