使用java code 在kettle 4.x创建transformation
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import org.pentaho.di.core.KettleEnvironment; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransHopMeta; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.steps.tableinput.TableInputMeta; import org.pentaho.di.trans.steps.tableoutput.TableOutputMeta; public class TransDemo { public static void main(String[] args) throws Exception { //初始化 KettleEnvironment.init(); File file = new File("C:\\Users\\Administrator\\Desktop\\123.ktr"); //创建一个转换 TransMeta transMeta = createTransformation(); //写到文件中 writeTransformationToFile(transMeta, file); //执行转换 execute(transMeta); } static TransMeta createTransformation(){ DatabaseMeta in = new DatabaseMeta(); in.setName("in"); in.setHostname("127.0.0.1"); in.setDBName("xe"); in.setDBPort("1521"); in.setUsername("abc"); in.setPassword("abc"); //表输出连接信息 DatabaseMeta out = new DatabaseMeta(); out.setName("out"); out.setHostname("127.0.0.1"); out.setDBName("xe"); out.setDBPort("1521"); out.setUsername("abc"); out.setPassword("abc"); //创建一个元数据 TransMeta transMeta = new TransMeta(); transMeta.setName("我的转换"); transMeta.addDatabase(out); transMeta.addDatabase(in); //表输入 TableInputMeta tin = new TableInputMeta(); tin.setDatabaseMeta(in); String insql = "select * from source_table"; tin.setSQL(insql); //创建step StepMeta inputStep = new StepMeta("从源数据表读取数据", tin); inputStep.setLocation(50, 50); inputStep.setDraw(true); transMeta.addStep(inputStep); //表输出 TableOutputMeta tout = new TableOutputMeta(); tout.setDatabaseMeta(out); tout.setSchemaName("abc"); tout.setTableName("dest_table"); StepMeta outputStep = new StepMeta("获取数据", tout); outputStep.setLocation(400, 400); outputStep.setDraw(true); transMeta.addStep(outputStep); //设置连线 TransHopMeta hop = new TransHopMeta(inputStep, outputStep); transMeta.addTransHop(hop); return transMeta; } static void writeTransformationToFile(TransMeta transMeta ,File file) throws Exception{ String xml = XMLHandler.getXMLHeader() + transMeta.getXML(); OutputStream opt = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(opt); bos.write(xml.getBytes("utf-8")); bos.close(); } static void execute(TransMeta transMeta) throws Exception{ Trans trans = new Trans(transMeta); trans.execute(null); trans.waitUntilFinished(); if(trans.getErrors() > 0) System.out.println("执行转换出错"); else System.out.println("成功执行这个转换"); } }