一段讀取 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 信息,自動生成動態(tài)分區(qū)腳本
 * @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
# **  功能描述:   從臨時表加載 動態(tài)分區(qū)
# **              
# **  創(chuàng)建者:     Chen Yao
# **  創(chuàng)建日期:   %date%
# **  修改日志:   
# **  修改日期          修改人          修改內(nèi)容
# ** -----------------------------------------------------------------------------------------------
# **
# **  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

#參數(shù)配置

#初始化表名
source_table_tmp=%tmp_table_name%

#結(jié)果表 
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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末凹耙,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌毛萌,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,734評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件喝滞,死亡現(xiàn)場離奇詭異阁将,居然都是意外死亡,警方通過查閱死者的電腦和手機右遭,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評論 3 394
  • 文/潘曉璐 我一進店門做盅,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人窘哈,你說我怎么就攤上這事吹榴。” “怎么了滚婉?”我有些...
    開封第一講書人閱讀 164,133評論 0 354
  • 文/不壞的土叔 我叫張陵图筹,是天一觀的道長。 經(jīng)常有香客問我,道長远剩,這世上最難降的妖魔是什么扣溺? 我笑而不...
    開封第一講書人閱讀 58,532評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮瓜晤,結(jié)果婚禮上锥余,老公的妹妹穿的比我還像新娘。我一直安慰自己痢掠,他們只是感情好驱犹,可當我...
    茶點故事閱讀 67,585評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著志群,像睡著了一般着绷。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上锌云,一...
    開封第一講書人閱讀 51,462評論 1 302
  • 那天荠医,我揣著相機與錄音,去河邊找鬼桑涎。 笑死彬向,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的攻冷。 我是一名探鬼主播娃胆,決...
    沈念sama閱讀 40,262評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼等曼!你這毒婦竟也來了里烦?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,153評論 0 276
  • 序言:老撾萬榮一對情侶失蹤禁谦,失蹤者是張志新(化名)和其女友劉穎胁黑,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體州泊,經(jīng)...
    沈念sama閱讀 45,587評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡丧蘸,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,792評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了遥皂。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片力喷。...
    茶點故事閱讀 39,919評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖演训,靈堂內(nèi)的尸體忽然破棺而出弟孟,到底是詐尸還是另有隱情,我是刑警寧澤样悟,帶...
    沈念sama閱讀 35,635評論 5 345
  • 正文 年R本政府宣布披蕉,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏没讲。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,237評論 3 329
  • 文/蒙蒙 一礁苗、第九天 我趴在偏房一處隱蔽的房頂上張望爬凑。 院中可真熱鬧,春花似錦试伙、人聲如沸嘁信。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽潘靖。三九已至,卻和暖如春蚤蔓,著一層夾襖步出監(jiān)牢的瞬間卦溢,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評論 1 269
  • 我被黑心中介騙來泰國打工秀又, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留单寂,地道東北人。 一個月前我還...
    沈念sama閱讀 48,048評論 3 370
  • 正文 我出身青樓吐辙,卻偏偏與公主長得像宣决,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子昏苏,可洞房花燭夜當晚...
    茶點故事閱讀 44,864評論 2 354

推薦閱讀更多精彩內(nèi)容

  • 官網(wǎng) 中文版本 好的網(wǎng)站 Content-type: text/htmlBASH Section: User ...
    不排版閱讀 4,381評論 0 5
  • 22年12月更新:個人網(wǎng)站關停尊沸,如果仍舊對舊教程有興趣參考 Github 的markdown內(nèi)容[https://...
    tangyefei閱讀 35,182評論 22 257
  • feisky云計算、虛擬化與Linux技術筆記posts - 1014, comments - 298, trac...
    不排版閱讀 3,849評論 0 5
  • 關于Mongodb的全面總結(jié) MongoDB的內(nèi)部構(gòu)造《MongoDB The Definitive Guide》...
    中v中閱讀 31,931評論 2 89
  • 風兮兮的那個飄逸 太陽又一次普照 那是愛與水的交流 波光粼粼 眺望湖水贤惯,以觀魯湖洼专。 路以正,月不明救巷。 驚拍海浪壶熏,風雨行。
    米瀾盛若閱讀 230評論 0 3