package com.ihooyah.flume.sink;

import com.ihooyah.flume.sink.util.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.flume.*;
import org.apache.flume.conf.Configurable;
import org.apache.flume.sink.AbstractSink;
import org.mortbay.util.ajax.JSON;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 描述 检测到flumechannls中的文件并处理生成新文件保存
 *
 * @author fatiaojie
 * @date 2020/4/2 11:07
 */
public class DirFtpSink extends AbstractSink implements Configurable {

    /**
     * 文件保存地址
     */
    private String fileDir;

    @Override
    public Status process() throws EventDeliveryException {

        Status status = Status.READY;
        Channel channel = this.getChannel();
        Transaction transaction = channel.getTransaction();

        try {
            transaction.begin();
            Event event = channel.take();
            if (event != null) {
                String body = new String(event.getBody(), "UTF-8");
                if (StringUtils.isNotBlank(body)) {
                    /**
                     * 处理文件内容并保存为新文件 新文件后缀为_result.json
                     */
                    body += "该数据已被处理过...";
                    createTempFile(fileDir+File.separator+System.currentTimeMillis()+"_result.json",body.getBytes());
                }
                System.out.println(body);
            }
            transaction.commit();
        } catch (Exception e) {
            transaction.rollback();
            status = Status.BACKOFF;
            e.printStackTrace();
        } finally {
            transaction.close();
        }
        return status;
    }

    @Override
    public void configure(Context context) {
        this.fileDir = context.getString("file_dir");
    }

    public static File createTempFile(String filePath, byte[] data) throws IOException
    {
        File file = new File(filePath);
        if (!file.getParentFile().exists())
        {
            file.getParentFile().mkdirs();
        }
        if (!file.exists())
        {
            file.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(data, 0, data.length);
        fos.flush();
        fos.close();
        return file;
    }
}
