一段读取 excel 自动生成 hive load shell 脚本的代码

自动化是程序员的天性,这里是一段小代码自动化手工重复的工作。

package collect;

import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.io.Files;
import com.google.common.io.LineProcessor;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * All rights Reserved, Designed By Migu.cn
 *
 * @Description: 读取表 Excel 信息,自动生成动态分区脚本
 * @Author: Yao
 * @Date: 2018/5/8 9:27
 * @Version: v0.1
 */
public class AutoGenSh {

    public static final String template_file = "dynamicLoadTemplate.txt";
    public static final String interface_name = "%interface_name%";
    public static final String date = "%date%";
    public static final String table_name = "%ods_table_name%";
    public static final String file_name = "%file_name%";
    public static final String tmpTableName = "%tmp_table_name%";
    public static final String start_index = "%startIndex%";
    public static final String column_list = "%column_list%";


    static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//可以方便地修改日期格式


    public static void main(String[] args) {
        // read config from configfile
        String currentDir = System.getProperty("user.dir");
        File[] confFiles = new File(currentDir).listFiles(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.endsWith(".conf");
            }
        });

        for (File conf : confFiles) {
            String confName = conf.getName();

            // read config find interfaceName and fileName;
            try {
                List<String> lines = Files.readLines(conf, Charsets.UTF_8);
                final String interfaceName = lines.get(0).substring(lines.get(0).indexOf("=") + 1);
                final String fileName = lines.get(1).substring(lines.get(1).indexOf("=") + 1);
                final String tableName = confName.substring(0, confName.indexOf("."));

                // find start index from filename
                final int startDateIndex = findDateIndex(fileName);

                // extract columns from excel
                String excelPath = currentDir + File.separator + tableName + ".xlsx";
                // don't miss last ,
                File excelFile = new File(excelPath);
                final String columns = extractColumns(excelFile) + ",";


                // final text after replace
                final List<String> replaceResult = new ArrayList<>();
                final String currentDate = dateFormat.format(new Date());

                File templateFile = new File(currentDir + File.separator + template_file);
                Files.readLines(templateFile, Charsets.UTF_8, new LineProcessor<List<String>>() {
                    public boolean processLine(String s) throws IOException {
                        s = s.replace(interface_name, interfaceName)
                                .replace(date, currentDate)
                                .replace(table_name, tableName)
                                .replace(tmpTableName, tableName + "tmp")
                                .replace(column_list, columns)
                                .replace(file_name, fileName)
                                .replace(start_index, startDateIndex + "");
                        return replaceResult.add(s);
                    }

                    public List<String> getResult() {
                        return replaceResult;
                    }
                });

                String shText = Joiner.on("\n").join(replaceResult);

                // export sh file
                // mkdir and move file
                String newDir = currentDir + File.separator + tableName;
                new File(newDir).mkdirs();

                // move xlsx and conf
                conf.renameTo(new File(newDir + "/" + conf.getName()));

                File eFile = new File(excelPath);
                eFile.renameTo(new File(newDir + "/" + eFile.getName()));

                String destShFile = newDir + "/" + tableName + "_2ods.sh";
                Files.write(shText.getBytes(), new File(destShFile));
                System.out.println("success export sh file: " + destShFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    /**
     * extract columns from excel
     *
     * @param templateFile
     * @return
     */
    private static String extractColumns(File templateFile) {
        Workbook excel = null;
        try {
            List<String> list = new ArrayList<String>();
            excel = WorkbookFactory.create(templateFile);
            Sheet sheet = excel.getSheetAt(0);
            for (int i = 0; i <= sheet.getLastRowNum(); i++) {
                Cell cell = sheet.getRow(i).getCell(0);
                String value = cell.getStringCellValue();

                // skip filename filedname in_date
                if (!value.toLowerCase().contains("filename")
                        && !value.toLowerCase().contains("in_date")
                        && !value.toLowerCase().contains("fieldname")) {
                    list.add("  " + value);
                }
            }

            return Joiner.on(",\n").join(list);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        } finally {
            if (excel != null) {
                try {
                    excel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 从文件名中获取 substring start index
     *
     * @param fileName i-client-base_content_20180503_ssms_000000.txt
     * @return
     */
    private static int findDateIndex(String fileName) {
        if (fileName.contains("YYYYMMDD")) {
            return fileName.indexOf("YYYYMMDD") + 1;
        }

        String extractDateRegex = "(\\d{8})";
        Matcher matcher = Pattern.compile(extractDateRegex).matcher(fileName);
        if (matcher.find()) {
            String date = matcher.group(1);
            return fileName.indexOf(date) + 1;
        }

        return -1;
    }
}

Shell 脚本模板定义如下

#!/bin/sh
#
#***************************************************************************************************
# **  文件名称:   %interface_name% 入 hive ods
# **  功能描述:   从临时表加载 动态分区
# **              
# **  创建者:     Chen Yao
# **  创建日期:   %date%
# **  修改日志:   
# **  修改日期          修改人          修改内容
# ** -----------------------------------------------------------------------------------------------
# **
# **  China Mobile(Chengdu) Information Technology Co., Ltd.
# **  All Rights Reserved.
#***************************************************************************************************
export LANG=en_US.UTF-8
export HIVE_HOME=`echo $HIVE_HOME`
export PATH=$PATH:$HIVE_HOME/bin

#参数配置

#初始化表名
source_table_tmp=%tmp_table_name%

#结果表 
target_table=%ods_table_name%

#echo "drop table if exists ;
# i-client-base_content_20180503_ssms_000000.txt
echo "
use mgwh_mgplusmigrate_ods;
set hive.exec.dynamic.partition=true;
set hive.exec.dynamic.partition.mode=nonstrict;

insert into ${target_table} partition(dayid)
select filename,
  from_unixtime(unix_timestamp(),'yyyy-MM-dd HH:mm:ss'),
%column_list%
  substr(filename,%startIndex%,8) as dayid
  from ${source_table_tmp};" | hive &&

exit 0
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,366评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,521评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,689评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,925评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,942评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,727评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,447评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,349评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,820评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,990评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,127评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,812评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,471评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,017评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,142评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,388评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,066评论 2 355

推荐阅读更多精彩内容

  • 官网 中文版本 好的网站 Content-type: text/htmlBASH Section: User ...
    不排版阅读 4,383评论 0 5
  • 22年12月更新:个人网站关停,如果仍旧对旧教程有兴趣参考 Github 的markdown内容[https://...
    tangyefei阅读 35,184评论 22 257
  • feisky云计算、虚拟化与Linux技术笔记posts - 1014, comments - 298, trac...
    不排版阅读 3,855评论 0 5
  • 关于Mongodb的全面总结 MongoDB的内部构造《MongoDB The Definitive Guide》...
    中v中阅读 31,938评论 2 89
  • 风兮兮的那个飘逸 太阳又一次普照 那是爱与水的交流 波光粼粼 眺望湖水,以观鲁湖。 路以正,月不明。 惊拍海浪,风雨行。
    米澜盛若阅读 230评论 0 3