Kettle與Java整合——Java程式碼調取執行資源庫的Transformation
阿新 • • 發佈:2019-02-01
下面程式碼是Java程式碼呼叫Kettle4.0版本的Transformation
1、Java讀取資源庫執行Transformation
(1)目錄型別資源庫Java程式碼
import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.repository.filerep.KettleFileRepository;
import org.pentaho.di.repository.filerep.KettleFileRepositoryMeta;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
public classReaderTransFromRep{
private static String tranName = "IM_KSDM"; // 傳輸名稱
public static void main(String[] args) throws KettleException {
Trans trans=null;
try {
// 初始化
KettleEnvironment.init();這個是4.0 版本的初始化,和3.x版本的不同
// 資源庫元物件
KettleFileRepositoryMeta repinfo = new KettleFileRepositoryMeta("","","資料採集","file:///E:/Workspaces/Kettle");
// 檔案形式的資源庫
KettleFileRepository rep = new KettleFileRepository();
rep.init(repinfo);
// 轉換元物件
if(tranName!=null){
TransMeta transMetadel = rep.loadTransformation(rep.getTransformationID(tranName, null ), null);
// 轉換
trans = new Trans(transMetadel);
// 執行轉換
trans.execute(null);
// 等待轉換執行結束
trans.waitUntilFinished();
//丟擲異常
if(trans.getErrors()>0){
throw new Exception("There are errors during transformation exception!(傳輸過程中發生異常)");
}
}else{
throw new KettleException("傳輸名為空!");
}
} catch (Exception e) {
if(trans!=null){
trans.stopAll();
}
e.printStackTrace();
throw new KettleException(e);
}
}
}
(2)資料庫型別資源庫
import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.repository.RepositoryDirectory;
import org.pentaho.di.repository.RepositoryDirectoryInterface;
import org.pentaho.di.repository.kdr.KettleDatabaseRepository;
import org.pentaho.di.repository.kdr.KettleDatabaseRepositoryMeta;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
public classReaderTransFromDBRep{
private static String transName="t1";
public static void main(String[] args) {
try {
KettleEnvironment.init();
DatabaseMeta dataMeta = new DatabaseMeta("KettleDBRep","MSSQL","Native","127.0.0.1","etl","1433","sa","bsoft");
KettleDatabaseRepositoryMeta repInfo = new KettleDatabaseRepositoryMeta();
repInfo.setConnection(dataMeta);
KettleDatabaseRepository rep = new KettleDatabaseRepository();
rep.init(repInfo);
rep.connect("admin", "admin");
RepositoryDirectoryInterface dir = new RepositoryDirectory();
dir.setObjectId(rep.getRootDirectoryID());
TransMeta tranMeta = rep.loadTransformation(rep.getTransformationID(transName, dir), null);
Trans trans = new Trans(tranMeta);
trans.execute(null);
trans.waitUntilFinished();
} catch (KettleException e) {
e.printStackTrace();
}
}
}