kettle api 執行轉換


import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.LogWriter;
import be.ibridge.kettle.core.NotePadMeta;
import be.ibridge.kettle.core.database.Database;
import be.ibridge.kettle.core.database.DatabaseMeta;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.trans.StepLoader;
import be.ibridge.kettle.trans.Trans;
import be.ibridge.kettle.trans.TransHopMeta;
import be.ibridge.kettle.trans.TransMeta;
import be.ibridge.kettle.trans.step.StepMeta;
import be.ibridge.kettle.trans.step.StepMetaInterface;
import be.ibridge.kettle.trans.step.selectvalues.SelectValuesMeta;
import be.ibridge.kettle.trans.step.tableinput.TableInputMeta;
import be.ibridge.kettle.trans.step.tableoutput.TableOutputMeta;

/**
 *
 * <p>Title:
 * 本文描述了以下操作:

1)           建立一個新的轉換(transformation)

2)           把轉換(transformation)存儲爲XML文件

3)           生成需要在目標表運行的SQL語句

4)           執行轉換(transformation)

5)           刪除目標表,可以使測試程序可以反覆執行(這一點可根據需要修改)。
</p>
 * <p>Description: TODO 類的功能描述</p>
 * <p>Copyright: Copyright (c) 2003</p>

 * @author <a href="mailto: [email protected]">洪亮</a>
 * @version 1.0
 * <p>------------------------------------------------------------</p>
 * <p> 修改歷史 </p>
 * <p>  序號    日期       時間        修 改 人    修 改 原 因</p>
 * <p>   1    2006-9-20   下午05:59:06     洪亮       創建  </p>
 *
 */

public class TransBuilderME
{
    public static final String[] databasesXML = {
        "<?xml version=/"1.0/" encoding=/"UTF-8/"?>" +
        "<connection>" +
            "<name>target</name>" +
            "<server>192.168.169.220</server>" +
            "<type>ORACLE</type>" +
            "<access>Native</access>" +
            "<database>NMSDB</database>" +
            "<port>1521</port>" +
            "<username>UCP</username>" +
            "<password>UCP</password>" +
          "</connection>",
         
          "<?xml version=/"1.0/" encoding=/"UTF-8/"?>" +
          "<connection>" +
              "<name>source</name>" +
              "<server>192.168.169.220</server>" +
              "<type>ORACLE</type>" +
              "<access>Native</access>" +
              "<database>NMSDB</database>" +
              "<port>1521</port>" +
              "<username>UCP</username>" +
              "<password>UCP</password>" +
            "</connection>" 
    };

    /**
     * Creates a new Transformation using input parameters such as the tablename to read from.
     * @param transformationName The name of the transformation
     * @param sourceDatabaseName The name of the database to read from
     * @param sourceTableName The name of the table to read from
     * @param sourceFields The field names we want to read from the source table
     * @param targetDatabaseName The name of the target database
     * @param targetTableName The name of the target table we want to write to
     * @param targetFields The names of the fields in the target table (same number of fields as sourceFields)
     * @return A new transformation
     * @throws KettleException In the rare case something goes wrong
     */
    public static final TransMeta buildCopyTable(String transformationName, String sourceDatabaseName, String sourceTableName, String[] sourceFields, String targetDatabaseName, String targetTableName, String[] targetFields) throws KettleException
    {
        LogWriter log = LogWriter.getInstance();
       
        try
        {
            //
            // Create a new transformation...
            //傳輸元信息
            TransMeta transMeta = new TransMeta();
            transMeta.setName(transformationName);//傳輸名稱
           
            // Add the database connections
            for (int i=0;i<databasesXML.length;i++)//數據庫配置信息數組
            {
                DatabaseMeta databaseMeta = new DatabaseMeta(databasesXML[i]);//數據庫元信息
                transMeta.addDatabase(databaseMeta);//傳輸元  中加入數據庫元信息
            }
           
            DatabaseMeta sourceDBInfo = transMeta.findDatabase(sourceDatabaseName);//查找源數據庫元信息
            DatabaseMeta targetDBInfo = transMeta.findDatabase(targetDatabaseName);//查找目標數據庫元信息

           
            //
            // Add a note
            //
            String note = "Reads information from table [" + sourceTableName+ "] on database [" + sourceDBInfo + "]" + Const.CR;
            note += "After that, it writes the information to table [" + targetTableName + "] on database [" + targetDBInfo + "]";
            NotePadMeta ni = new NotePadMeta(note, 150, 10, -1, -1);//註釋信息
            transMeta.addNote(ni);

            //
            // create the source step...
            //
            String fromstepname = "read from [" + sourceTableName + "]";//from步驟名稱
            TableInputMeta tii = new TableInputMeta();//表輸入元數據信息
            tii.setDatabaseMeta(sourceDBInfo);//爲表輸入 指定 數據庫
            String selectSQL = "SELECT "+Const.CR;//拼接查詢sql語句
            for (int i=0;i<sourceFields.length;i++)
            {
                if (i>0) selectSQL+=", "; else selectSQL+="  ";
                selectSQL+=sourceFields[i]+Const.CR;
            }
            selectSQL+="FROM "+sourceTableName;
            tii.setSQL(selectSQL);//設置查詢sql語句

            StepLoader steploader = StepLoader.getInstance();//???

            String fromstepid = steploader.getStepPluginID(tii);
            //步驟元數據信息
            StepMeta fromstep = new StepMeta(log, fromstepid, fromstepname, (StepMetaInterface) tii);
            fromstep.setLocation(150, 100);
            fromstep.setDraw(true);
            fromstep.setDescription("Reads information from table [" + sourceTableName + "] on database [" + sourceDBInfo + "]");
            //傳輸中 添加步驟
            transMeta.addStep(fromstep);
            //
            // add logic to rename fields
            // Use metadata logic in SelectValues, use SelectValueInfo...
            //選擇字段(重命名)
            SelectValuesMeta svi = new SelectValuesMeta();
            svi.allocate(0, 0, sourceFields.length);
            for (int i = 0; i < sourceFields.length; i++)
            {
             //設置源字段和目標字段
                svi.getMetaName()[i] = sourceFields[i];
                svi.getMetaRename()[i] = targetFields[i];
            }

            String selstepname = "Rename field names";
            //獲取步驟插件ID
            String selstepid = steploader.getStepPluginID(svi);
            //創建步驟元數據信息
            StepMeta selstep = new StepMeta(log, selstepid, selstepname, (StepMetaInterface) svi);
            selstep.setLocation(350, 100);
            selstep.setDraw(true);
            selstep.setDescription("Rename field names");
            //添加步驟
            transMeta.addStep(selstep);

            //傳輸連接元數據信息(連接from和select)
            TransHopMeta shi = new TransHopMeta(fromstep, selstep);
            transMeta.addTransHop(shi);//添加到傳輸元對象
            fromstep = selstep;//然後設置from步驟爲select步驟

            //
            // Create the target step...
            //
            //
            // Add the TableOutputMeta step...
            //設置目標步驟名稱
            String tostepname = "write to [" + targetTableName + "]";
            //表輸出元對象
            TableOutputMeta toi = new TableOutputMeta();
            toi.setDatabase(targetDBInfo);//設置數據庫
            toi.setTablename(targetTableName);//設置表名
            toi.setCommitSize(3000);//設置批量提交數
            toi.setTruncateTable(true);//是否清除原有數據

            //獲取步驟ID
            String tostepid = steploader.getStepPluginID(toi);
            //創建to步驟
            StepMeta tostep = new StepMeta(log, tostepid, tostepname, (StepMetaInterface) toi);
            tostep.setLocation(550, 100);
            tostep.setDraw(true);
            tostep.setDescription("Write information to table [" + targetTableName + "] on database [" + targetDBInfo + "]");
            transMeta.addStep(tostep);//添加步驟

            //
            // Add a hop between the two steps...
            //
            //創建連接 from--to
            TransHopMeta hi = new TransHopMeta(fromstep, tostep);
            transMeta.addTransHop(hi);

            // OK, if we're still here: overwrite the current transformation...
            return transMeta;
        }
        catch (Exception e)
        {
            throw new KettleException("An unexpected error occurred creating the new transformation", e);
        }
    }

    /**
     * 1) create a new transformation
     * 2) save the transformation as XML file
     * 3) generate the SQL for the target table
     * 4) Execute the transformation
     * 5) drop the target table to make this program repeatable
     *
     * @param args
     */
    public static void main(String[] args) throws Exception
    {
        long start = new Date().getTime();
        // Init the logging...
        LogWriter log = LogWriter.getInstance("TransBuilder.log", true, LogWriter.LOG_LEVEL_DETAILED);
       
        // Load the Kettle steps & plugins
        StepLoader stloader = StepLoader.getInstance();
        if (!stloader.read())
        {
            log.logError("TransBuilder",  "Error loading Kettle steps & plugins... stopping now!");
            return;
        }
       
        // The parameters we want, optionally this can be
        String fileName = "./NewTrans.xml";
        String transformationName = "Test Transformation";
        String sourceDatabaseName = "source";
        String sourceTableName = "emp_collect";
        String sourceFields[] = {
          "empno",      
          "ename",      
          "job",        
          "mgr",        
          "comm",       
          "sal",        
          "deptno",     
          "birthday"   
 
            };

        String targetDatabaseName = "target";
        String targetTableName = "emp_kettle01";
        String targetFields[] = {
          "empno01",      
          "ename01",      
          "job01",        
          "mgr01",        
          "comm",       
          "sal",        
          "deptno",     
          "birthday"
            };

       
        // Generate the transformation.
        //創建轉換元對象
        TransMeta transMeta = TransBuilderME.buildCopyTable(
                transformationName,
                sourceDatabaseName,
                sourceTableName,
                sourceFields,
                targetDatabaseName,
                targetTableName,
                targetFields
                );
//        transMeta = new  TransMeta();
        // Save it as a file:
        //傳輸元對象 中獲得XML,並輸出
        String xml = transMeta.getXML();
        DataOutputStream dos = new DataOutputStream(new FileOutputStream(new File(fileName)));
        dos.write(xml.getBytes("UTF-8"));
        dos.close();
        System.out.println("Saved transformation to file: "+fileName);

        // OK, What's the SQL we need to execute to generate the target table?
        //獲得sql語句,創建表語句
        String sql = transMeta.getSQLStatementsString();

        // Execute the SQL on the target table:
        //創建表
        Database targetDatabase = new Database(transMeta.findDatabase(targetDatabaseName));
        targetDatabase.connect();//連接數據庫
        targetDatabase.execStatements(sql);//執行sql
       
        // Now execute the transformation...
        //執行傳輸任務
        Trans trans = new Trans(log, transMeta);
        trans.execute(null);
        trans.waitUntilFinished();//等待執行完畢
       
        // For testing/repeatability, we drop the target table again
//        targetDatabase.execStatement("drop table "+targetTableName);
        targetDatabase.disconnect();//斷開數據庫連接
       
        long end = new Date().getTime();
        System.out.println("運行時間:" + (end - start) / 1000 + "秒");
        long min = (end - start) / 1000 / 60;
        long second = (end - start) / 1000 % 60;
        System.out.println("運行時間:" + min + "分鐘" + second + "秒");
    }


}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章