package com.mx.hbasefile.hadoop.hdfs.boot;

import com.mx.hbasefile.hadoop.hdfs.api.HdfsTemplate;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.URI;

/**
 * @ClassName HdfsAutoConfiguration
 * @Author zzrdark
 * @Date 2019-08-14 17:24
 * @Description TODO
 **/
@Configuration
@EnableConfigurationProperties(HdfsConfigProperties.class)
@ConditionalOnClass(FileSystem.class)
public class HdfsAutoConfiguration {

    @Autowired
    private HdfsConfigProperties hdfsConfigProperties;

    @Bean
    @ConditionalOnMissingBean(FileSystem.class)
    public FileSystem fileSystem(){
        try {
            org.apache.hadoop.conf.Configuration conf = new org.apache.hadoop.conf.Configuration();

            conf.addResource(new Path(hdfsConfigProperties.getHadoopConfigDir()+"/core-site.xml"));
            conf.addResource(new Path(hdfsConfigProperties.getHadoopConfigDir()+"/hdfs-site.xml"));
            return FileSystem.get(new URI(hdfsConfigProperties.getHdfsUrl()),conf);
        } catch (Exception e) {
            e.printStackTrace();
            //TODO 日志
        }
        return null;
    }

    @Bean
    public HdfsTemplate hdfsTemplate(@Autowired FileSystem fileSystem){

        HdfsTemplate hdfsTemplate = new HdfsTemplate(fileSystem,hdfsConfigProperties);
        return hdfsTemplate;
    }

}
