首先在我们自己的 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
下面这个对象中的方法, 用来连接 SAP
- package 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{
- Map<String, String> params = new HashMap<String, String>();
- 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<String, String> params = new HashMap<String, String>();
- params.put(paramName, paramValue);
- return callRFC(funcName, params, returnTab, client);
- }
- public static JCO.Table callRFC(String funcName, Map<String, String> params, String returnTab) throws Exception{
- return callRFC(funcName, params).getTableParameterList().getTable(returnTab);
- }
- public static JCO.Table callRFC(String funcName, Map<String, String> params, String returnTab, JCO.Client client) throws Exception{
- return callRFC(funcName, params, client).getTableParameterList().getTable(returnTab);
- }
- public static JCO.Function callRFC(String funcName, Map<String, String> 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<String, String> 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() - lastCheckModified <checkModifiedInteval) return;
- lastCheckModified = System.currentTimeMillis();
- InputStream is = null;
- try {
- URL url = getConfigFileUrl();
- long modified = getFileLastModified(url);
- //logger.debug("**** new modified:" + modified);
- if (modified> lastModified) {
- // 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 <String,
- String> getSimilarProperties(String keyPrex) {
- confirmLatest();
- Map <String,
- String> result = new HashMap <String,
- String> ();
- 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;
- }
- }
这就是全部
运行结果
来源: https://yq.aliyun.com/articles/658793