本文共 15390 字,大约阅读时间需要 51 分钟。
首先在我们自己的maven项目中,提供一个属性配置文件
如下图所示,提供SAP足够权限用户的用户名密码等信息然后测试java代码TestNG代码如下package com.tsmi.hibernate.utils;import org.testng.annotations.Test;import com.sap.mw.jco.JCO;public class ConfigUtilTest { @Test public void f() { String clientV = ConfigUtil.getProperty("SAP_CLIENT"); String user = ConfigUtil.getProperty("SAP_USRE"); String pwd = ConfigUtil.getProperty("SAP_PASSWORD"); String lang = ConfigUtil.getProperty("SAP_LANG"); String ipAddress = ConfigUtil.getProperty("SAP_IPADDRESS"); String sync = ConfigUtil.getProperty("SAP_SYSNR"); System.out.println("ConfigUtilTest测试类信息:--clientV is: " + clientV + " ;user is: " + user + " ;pwd is: " + pwd + " ;lang is: " + lang + " ;ipAddress is: " + ipAddress + "--"); //测试java端从SAP获取待检单的数据 //测试输入参数建议: 172.16.10.80上生产机PRD 采购组:911;供应商编号:20108007;日期:当天; try { /* JCO.Table output = SAPfunction.getDJDinfo("911", "20108007", "20180408", "1000"); System.out.println("----getCapacity():返回值的容量,预定返回值内表一条记录包含23个元素-----" + output.getCapacity()); System.out.println("----getFieldCount():" + output.getFieldCount()); System.out.println("----getName():SAP中Function的返回值的参数名称----" + output.getName()); System.out.println("----getFieldCount():返回值中的记录数" + output.getNumRows()); if (output.getNumRows() > 0) { do { String sEBELN = (String) output.getValue("EBELN"); String sEBELP = (String) output.getValue("EBELP"); String sMATNR = (String) output.getValue("MATNR"); String sTXZ01 = (String) output.getValue("TXZ01"); String sKGY = (String) output.getValue("KGY"); String sLGORT = (String) output.getValue("LGORT"); System.out.println( sEBELN + "--" + sEBELP + "--" + sMATNR + "--" + sTXZ01 + "--" + sKGY + "--" + sLGORT); } while (output.nextRow()); } else { System.out.println("!!请检查java端输入参数,因为从SAP返回的记录数为0!!"); } */ //上面的代码都没有什么用 //测试向SAP传递一颗物料(慎重使用) //本次测试的核心代码 SAPfunction.sendMToSAP(); } catch (Exception e) { e.printStackTrace(); } }}
上述代码执行后,SAP端会创建一个物料
下面展示一下创建物料的java代码内容package com.tsmi.hibernate.utils;import java.util.Vector;import com.sap.mw.jco.IFunctionTemplate;import com.sap.mw.jco.JCO;/** * @author Administrator * 涉及到LIFNR MATNR PERNR等SAP中的编号字段,请确保java端或者abap端进行了前导零的补齐或者删除 * */public class SAPfunction { /** * 从SAP获取待检单数据 * 输入参数: 采购组+供应商编号+过账日期+工厂 * 返回值:JCO.Table的实例 * @throws Exception */ public static JCO.Table getDJDinfo(String sEKGRP,String sLIFNR,String sBUDAT,String sWERKS) throws Exception { JCO.Client mConnection = SAPClientUtil.getConnectedClient(); JCO.Function function = SAPClientUtil.createFunction("Z_PLM_DJD", mConnection); JCO.Table input = function.getTableParameterList().getTable("ITAB_INPUT"); input.appendRow(); setDJDInput(input, sEKGRP, sLIFNR, sBUDAT, sWERKS); mConnection.execute(function); // 返回值 JCO.Table output = function.getTableParameterList().getTable("ITAB_MSEG_MKPF"); output.firstRow(); return output; } public static void setDJDInput(JCO.Table input,String sEKGRP,String sLIFNR,String sBUDAT,String sWERKS){ // 172.16.10.89上测试机DEV 采购组:902;供应商编号:20002012;日期:20120921; // 172.16.10.80上生产机PRD 采购组:911;供应商编号:20108007;日期:当天; input.setValue(sEKGRP, "EKGRP"); //采购组 input.setValue(sLIFNR, "LIFNR"); //供应商编号 input.setValue(sBUDAT, "BUDAT"); //过账日期 input.setValue(sWERKS, "WERKS"); //工厂 } /** * 核心方法:发送物料到ERP系统 * @param part * @param mark * @return * @throws Exception */ public static String sendMToSAP() throws Exception{ boolean mark = false; StringBuffer buf = new StringBuffer(); //获取SAP中Function Module的连接参数 JCO.Client mConnection = SAPClientUtil.getConnectedClient(); //使用参数和Fucntion name创建Function Module的实例 JCO.Function function = SAPClientUtil.createFunction("Z_PDM_MATERIAL", mConnection);//函数名 //获取SAP中Function Module的输入参数 JCO.Table input = function.getTableParameterList().getTable("IM_TAB"); input.appendRow(); //为输入参数提供数据,核心语句input.setValue(bianma, "MATNR"); //物料编码 setTableValue(input); mark = true; if(mark){ //执行SAP的Function Module mConnection.execute(function); JCO.Table output = function.getTableParameterList().getTable("IT_RETURN"); output.firstRow(); do{ String flag = (String)output.getValue("TYPE"); String number = (String)output.getValue("MATNR"); String message = (String)output.getValue("MESSAGE"); //log.debug("number:" + number + ";flag:" + flag + ";message:" + message); if(flag.equals("E")){ if(message.trim().length() > 0) buf.append("物料编号为:" + number + " 的物料,传送erp失败。message:" + message + "\n"); } }while(output.nextRow()); } if(buf.toString().length() == 0){ buf.append("success"); } return buf.toString(); } //所创建物料的具体参数 public static void setTableValue(JCO.Table input){ String factory = ""; double penqimianji = 0; double zhongliang = 0; String bianma = ""; String miaoshu = ""; String zhongyaodu = "01"; String chanpinxinghao = "产品型号"; //String type = TypeIdentifierUtility.getTypeIdentifier(part).getTypename(); factory = "1000"; penqimianji = 2.2; zhongliang = 3.3; // 物料编码 bianma = "BJBPJAVA2018122901"; // 物料描述 miaoshu = "由java代码创建的物料1"; String xinghao = "型号1"; String unit = "KG"; unit = toERPUnit(unit); input.setValue(bianma, "MATNR"); //物料编码 input.setValue(miaoshu, "MAKTX"); //物料描述 input.setValue(unit, "MEINS"); //单位 input.setValue("Z201", "MTART"); //物料类型 input.setValue(penqimianji, "VOLUM");//涂装面积 input.setValue(zhongliang, "NTGEW"); //重量 input.setValue(zhongyaodu, "TEMPB"); //重要度 input.setValue(chanpinxinghao, "WRKST"); //产品型号 input.setValue("1000", "PRCTR"); //利润中心 input.setValue(factory, "WERKS"); //工厂 } public static String toERPUnit(String unit){ if(unit.equals("EA")){ return "EA"; }else if(unit.equals("KG")){ return "KG"; }else if(unit.equals("M")){ return "M"; }else if(unit.equals("L")){ return "L"; }else if(unit.equals("SQ_M")){ return "M2"; }else if(unit.equals("MIN")){ return "MIN"; }else if(unit.equals("CU_M")){ return "M3"; }else if(unit.equals("KM")){ return "KM"; }else if(unit.equals("MM")){ return "MM"; }else if(unit.equals("CAN")){ return "CAN"; }else if(unit.equals("DEG")){ return "DEG"; }else if(unit.equals("BLANK")){ return "EA"; }else if(unit.equals("PC")){ return "PC"; }else{ return ""; } } public static void main(String[] args) { // TODO Auto-generated method stub }}
上述代码首先调用其它对象的方法,连接了SAP
下面这个对象中的方法,用来连接SAPpackage com.tsmi.hibernate.utils;import java.util.HashMap;import java.util.Map;import com.sap.mw.jco.IFunctionTemplate;import com.sap.mw.jco.JCO;import com.tsmi.hibernate.utils.ConfigUtil;public class SAPClientUtil { public static JCO.Client getConnectedClient(){ String clientV = ConfigUtil.getProperty("SAP_CLIENT"); String user = ConfigUtil.getProperty("SAP_USRE"); String pwd = ConfigUtil.getProperty("SAP_PASSWORD"); String lang = ConfigUtil.getProperty("SAP_LANG"); String ipAddress = ConfigUtil.getProperty("SAP_IPADDRESS"); String sync = ConfigUtil.getProperty("SAP_SYSNR"); JCO.Client client = JCO.createClient(clientV, user, pwd, lang, ipAddress, sync); client.connect(); return client; } public static JCO.Function createFunction(String name, JCO.Client client) throws Exception { JCO.Repository repository = new JCO.Repository("ARAsoft", client); try { IFunctionTemplate ft = repository.getFunctionTemplate(name.toUpperCase()); if (ft == null) return null; return ft.getFunction(); } catch (Exception ex) { throw new Exception("Problem retrieving JCO.Function object."); } } public static JCO.Table callRFC(String funcName, String paramName, String paramValue, String returnTab) throws Exception{ Mapparams = new HashMap (); params.put(paramName, paramValue); return callRFC(funcName, params, returnTab); } public static JCO.Table callRFC(String funcName, String paramName, String paramValue, String returnTab, JCO.Client client) throws Exception{ Map params = new HashMap (); params.put(paramName, paramValue); return callRFC(funcName, params, returnTab, client); } public static JCO.Table callRFC(String funcName, Map params, String returnTab) throws Exception{ return callRFC(funcName, params).getTableParameterList().getTable(returnTab); } public static JCO.Table callRFC(String funcName, Map params, String returnTab, JCO.Client client) throws Exception{ return callRFC(funcName, params, client).getTableParameterList().getTable(returnTab); } public static JCO.Function callRFC(String funcName, Map params) throws Exception{ JCO.Client client = null; try{ client = SAPClientUtil.getConnectedClient(); return callRFC(funcName, params, client); }catch(Exception e){ throw e; }finally{ if(client != null){ client.disconnect(); client = null; } } } public static JCO.Function callRFC(String funcName, Map params, JCO.Client client) throws Exception{ client = SAPClientUtil.getConnectedClient(); JCO.Function function = createFunction(funcName, client); JCO.ParameterList input = function.getImportParameterList(); if(params != null){ for(String key : params.keySet()) input.setValue(params.get(key), key); } client.execute(function); return function; }}
下面这个对象的方法,用来获取properties文件,用来得到创建RFC连接所需要的用户名密码
package com.tsmi.hibernate.utils;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.io.UnsupportedEncodingException;import java.net.URL;import java.net.URLDecoder;import java.util.Enumeration;import java.util.HashMap;import java.util.Map;import java.util.Properties;import org.apache.commons.io.IOUtils;import org.apache.log4j.Logger;//import wt.log4j.LogR;/** * 配置文件工具类 * @author Li Banggui * */public class ConfigUtil { //private static final Logger logger = LogR.getLogger(ConfigUtil.class.getName()); // 配置属性 private static final String CONFIGFILE = "/integration.properties"; //配置文件路径 private static Properties configs = new Properties(); private static long lastModified = 0; //文件更新时间 private static long lastCheckModified = 0; //最后一次检查文件更新时间 private static long checkModifiedInteval = 1000 * 60 * 5; //检查文件更新间隔 // 加载配置属性 static { confirmLatest(); } /** * 获取配置文件URL * @return */ public static URL getConfigFileUrl() { URL url = ConfigUtil.class.getResource(CONFIGFILE); return url; } public static InputStream getConfigAsStream() { URL url = getConfigFileUrl(); try { return url != null ? url.openStream() : null; } catch (IOException e) { return null; } } /** * 确认配置文件内容最新,若不是最新,则重新读取 * */ private static synchronized void confirmLatest(){ //logger.debug("******* check latest: " + System.currentTimeMillis() + ", " + lastCheckModified + ", " + lastModified + ", " + checkModifiedInteval); if(System.currentTimeMillis() - lastCheckModifiedlastModified){ // logger.debug("****** 系统配置文件更新,重新读取......"); lastModified = modified; is = url.openStream(); Properties tempps = new Properties(); tempps.load(is); configs.clear(); for (Enumeration item = tempps.keys(); item.hasMoreElements();) { try { String key = (String) item.nextElement(); String viewkey = new String(key.getBytes("ISO-8859-1"), "GB2312"); String value = new String(tempps.getProperty(key).getBytes("ISO-8859-1"), "GB2312"); configs.put(viewkey, value); } catch (UnsupportedEncodingException e) { // logger.error("读取系统默认配置文件内容错误", e); } } String strCheckModifiedInteval = configs.getProperty("checkModifiedInteval"); try{ if(strCheckModifiedInteval!=null) checkModifiedInteval = (long) (Float.parseFloat(strCheckModifiedInteval) * 60 * 1000); }catch(Exception e){ //logger.error("系统配置刷新频率错误", e); } } } catch (IOException e) { //logger.error("打开系统默认配置文件错误", e); } finally { if(is!=null) IOUtils.closeQuietly(is); } } /** * 获取文件修改时间 * @param url * @return * @throws UnsupportedEncodingException */ private static long getFileLastModified(URL url) throws UnsupportedEncodingException{ File file = new File(URLDecoder.decode(url.getFile(),"UTF-8")); return file.lastModified(); } /** * 获取配置属性值 * * @param key * @return */ public static String getProperty(String key) { confirmLatest(); if (key == null) { return null; } return configs.getProperty(key); } /** * 获取配置属性值 * * @param key * @return */ public static String getProperty(String key, String defaultValue) { confirmLatest(); if (key == null) { return defaultValue; } return configs.getProperty(key, defaultValue); } /** * 获取一组以相同前缀开头的key对应的值 * * @param keyPrex * @return */ public static Map getSimilarProperties(String keyPrex) { confirmLatest(); Map result = new HashMap (); for (Enumeration item = configs.keys(); item.hasMoreElements();) { String key = (String) item.nextElement(); if (key.toLowerCase().startsWith(keyPrex.toLowerCase())) { result.put(key, (String) configs.get(key)); } } return result; }}
这就是全部
运行结果转载地址:http://sehnx.baihongyu.com/