java取出SAP接口的数据/javaでsap interfaceからデータを取得する/obtain data from sap by java

import test.ConnectionPool;
import com.sap.mw.jco.*;
import com.sap.mw.jco.JCO.Client;
import com.sap.mw.jco.JCO.ParameterList;
import com.sap.mw.jco.JCO.Table;
public class MyMain {

    public static void main(String[] args) {
   
       Client mConnection = null;
       //创建连接池
       ConnectionPool cp = new ConnectionPool();
       try{
       JCO.Table ret = null;
       JCO.Function function = null;
       JCO.ParameterList inParm = null;
     
       //RFC函数名      
       String strRfcName = "zrfc_ddstutas";//rfc函数名
       //使用连接池
       cp.PoolConnection("mySAPPools",50, "700", "00593987", "shit","192.168.100.4", "03");
       //从连接池中取出Connection
       mConnection = JCO.getClient("mySAPPools");
       //             (
  //                            "700", //端口号
  //                            "00593987", //用户名
  //                            "shit", //密码
  //                            "EN", //语言
  //                            "192.168.100.4", //sap服务器ip
  //                            "03"); //系统编号
                              //sysConfig.getSapGroupName()); //SAP组名

        //mConnection.connect();
        if(mConnection!=null&& mConnection.isAlive()){
           System.out.println("SAP连接成功");
        // 从连接获得一个逻辑意义上的“仓库”对象(Repository)
           JCO.Repository myRepository = new JCO.Repository("hui",mConnection); // 只是一个名字
         //为输入参数赋值
           IFunctionTemplate ft = myRepository.getFunctionTemplate(strRfcName.toUpperCase());
             // 从这个函数模板获得该SAP函数的对象
           function = ft.getFunction();
          //  function = this.createFunction(strRfcName);
   inParm = function.getImportParameterList();
   //inParm.clear();
   inParm.setValue("8515466119", "BSTNK"); //AUFNR_B 订单号                          
   //inParm.setValue("1997-10-11", "ERDAT_B"); //AUFNR_E 订单号 
   //inParm.setValue("2011-10-11", "ERDAT_E"); //AUFNR_E 订单号   
   //inParm.setValue("", "KUNNR"); //AUFNR_E 订单号   
  
   //赋值传入参数
   function.setImportParameterList(inParm);          
   mConnection.execute(function);
  
   //执行完毕读取返回信息
   ParameterList pList=function.getTableParameterList();
   //pList.getTable("OUTPUT");
  
   System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+pList.toXML());
   ret = function.getTableParameterList().getTable("OUTPUT");
   if (ret.getNumRows() > 0) {
    System.out.println("查询结果>0");
    for (int i = 0; i < ret.getNumRows(); i++) {
        ret.setRow(i);//指定行
        String strVBELN = ret.getString("VBELN");
        System.out.println("strVBELN查询结果为"+strVBELN);
        String strKUNNR = ret.getString("KUNNR");
        System.out.println("strKUNNR查询结果为"+strKUNNR);
        String strERDAT = ret.getString("ERDAT");
        System.out.println("strERDAT查询结果为"+strERDAT);
        String strMS = ret.getString("MS");
        System.out.println("strMS查询结果为"+strMS);
        String strSTUTSA1= ret.getString("STUTSA1");
        System.out.println("strSTUTSA1查询结果为"+strSTUTSA1);
        String strSTUTSA2= ret.getString("STUTSA2");
        System.out.println("strSTUTSA2查询结果为"+strSTUTSA2);
        String strSTUTSA3= ret.getString("STUTSA3");
        System.out.println("strSTUTSA3查询结果为"+strSTUTSA3);
        String strSTUTSA4= ret.getString("STUTSA4");
        System.out.println("strSTUTSA4查询结果为"+strSTUTSA4);
        String strSTUTSA5= ret.getString("STUTSA5");
        System.out.println("strSTUTSA5查询结果为"+strSTUTSA5);
        String strSTUTSA6= ret.getString("STUTSA6");
        System.out.println("strSTUTSA6查询结果为"+strSTUTSA6);
        String strSTUTSA7= ret.getString("STUTSA7");
        System.out.println("strSTUTSA7查询结果为"+strSTUTSA7);
    }
   }
   System.out.println("查询结果为"+ret.getNumRows());    
          
      


          
        }
      }catch(Exception ex) {
      
           System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
           ex.printStackTrace();
          System.out.println("Caught an exception: \n" + ex);
        }finally{
            // do not forget to close the client connection
         cp.RemoveClientPool("Sample_Pool");
        }
    }

}

javaでsapへ接続(日本語)java连接SAP(中国語)Connected to sap by java(english)

JAVAでSAPに構築してあるRFCモジュールもしくは、BAPIをコールします。ここで実現できるのは、JAVAでSAPを起動し制御する事が可能になります。(SAPからの起動ではありません)当機能を実行する前提として、SAPが提供しているJcoをダウンロードして、取得しておく必要があります。 
 ①実行環境の制御 
  ダウンロードしたJcoを実行環境へロードします。(CLASSPATHへロード) 
 ②Jcoをインポート 
  import com.sap.mw.jco.*; 
 ③接続環境の構築 
  JCO.Client mConnection; 
  mConnection = JCO.createClient(クライアント,ユーザID,パスワード,言語,ホスト名,システム番号); 
  mConnection.connect(); 
 ④BAPIの実行準備  
  JCO.Repository mRepository; 
  JCO.Function function = null; 
  mRepository = new JCO.Repository(リポジトリ名, mConnection); ※リポジトリ名はとりあえず好きな文字列で 
  IFunctionTemplate ftemplate = = mRepository.getFunctionTemplate(BAPIのID); ※大文字で指定する事 ・・・ toUpperCaseを利用 
 ⑤BAPIのパラメータセット 
  function = ftemplate.getFunction(); 
 ⑤BAPIの実行 
  mConnection.execute(function); 
 ⑥実行結果の取得 
  JCO.Structure returnStructure = null; 
  returnStructure = function.getExportParameterList().getStructure(エクスポートパラメータID); 構造を持つエクスポートパラメータ 
  returnStructure.getString(構造の項目ID).equals(値); で値の判別可能 
   
 ⑧切断 
  mConnection.disconnect(); 
  JCO.removeClientPool(SID); 


http://help.sap.com/saphelp_nw70/helpdata/JA/fa/f752423f3ab330e10000000a155106/frameset.htm



http://www.baidu.com/p/%E5%BC%B5%E5%B0%8F%E5%A9%89?from=zhidao

1:Sap 域模型 
package abc;
public class SapSystem implements java.lang.Cloneable {
 private final String name;
 private final String host;
 private final String client;
 private final String systemNumber; 
 private final String user;
 private final String password;
 private final String language ="en"; // English will be used as login language 

/**
  * Constructor, Login language is assumed to be English
  * @param name
  * @param client
  * @param user
  * @param password
  * @param host
  * @param systemNumber
  */
 public SapSystem(String name, String host, String client
    , String systemNumber, String user, String password) {
    this.name = name;
    this.client = client;
    this.user = user;
    this.password = password;
    this.host = host;
    this.systemNumber = systemNumber;
 }

public String getName() {
  return name;
 }

 public String getClient() {
  return client;
 }

 public String getUser() {
  return user;
 }

 public String getPassword() {
  return password;
 }

 public String getLanguage() {
  return language;
 }

 public String getHost() {
  return host;
 }

 public String getSystemNumber() {
  return systemNumber;
 }

 @Override
 public String toString() {
  return "Client " + client + " User " + user + " PW " + password
    + " Language " + language + " Host " + host + " SysID "
    + systemNumber;
 }

 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + ((client == null) ? 0 : client.hashCode());
  result = prime * result + ((host == null) ? 0 : host.hashCode());
  result = prime * result
    + ((language == null) ? 0 : language.hashCode());
  result = prime * result + ((name == null) ? 0 : name.hashCode());
  result = prime * result
    + ((password == null) ? 0 : password.hashCode());
  result = prime * result
    + ((systemNumber == null) ? 0 : systemNumber.hashCode());
  result = prime * result + ((user == null) ? 0 : user.hashCode());
  return result;
 }

 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  SapSystem other = (SapSystem) obj;
  if (client == null) {
   if (other.client != null)
    return false;
  } else if (!client.equals(other.client))
   return false;
  if (host == null) {
   if (other.host != null)
    return false;
  } else if (!host.equals(other.host))
   return false;
  if (language == null) {
   if (other.language != null)
    return false;
  } else if (!language.equals(other.language))
   return false;
  if (name == null) {
   if (other.name != null)
    return false;
  } else if (!name.equals(other.name))
   return false;
  if (password == null) {
   if (other.password != null)
    return false;
  } else if (!password.equals(other.password))
   return false;
  if (systemNumber == null) {
   if (other.systemNumber != null)
    return false;
  } else if (!systemNumber.equals(other.systemNumber))
   return false;
  if (user == null) {
   if (other.user != null)
    return false;
  } else if (!user.equals(other.user))
   return false;
  return true;
 }

 @Override
 public Object clone() {
  try {
   return super.clone();
  } catch (CloneNotSupportedException e) {
   e.printStackTrace();
  }
  return null;
 }

}
=====================================
2:建立连接
import java.util.Properties;

import com.sap.conn.jco.ext.DestinationDataEventListener;
import com.sap.conn.jco.ext.DestinationDataProvider;

import de.vogella.sap.system.model.SapSystem;

/**
 * Represents the destination to a specific SAP system. 
 * The destination is maintained via a property file
 * 
 */
public class MyDestinationDataProvider implements DestinationDataProvider {
 static String SAP_SERVER = "SAP_SERVER";
 private final Properties ABAP_AS_properties;

 public MyDestinationDataProvider(SapSystem system) {
  Properties properties = new Properties();
  properties.setProperty(DestinationDataProvider.JCO_ASHOST, system
    .getHost());
  properties.setProperty(DestinationDataProvider.JCO_SYSNR, system
    .getSystemNumber());
  properties.setProperty(DestinationDataProvider.JCO_CLIENT, system
    .getClient());
  
  properties.setProperty(DestinationDataProvider.JCO_USER, system
    .getUser());
  properties.setProperty(DestinationDataProvider.JCO_PASSWD, system
    .getPassword());
 
  ABAP_AS_properties = properties;
 }
 
 @Override
 public Properties getDestinationProperties(String system) {
  return ABAP_AS_properties;
 }

 @Override
 public void setDestinationDataEventListener(
   DestinationDataEventListener eventListener) {
 }

 @Override
 public boolean supportsEvents() {
  return false;
 }

}
==================
import com.sap.conn.jco.JCoContext;
import com.sap.conn.jco.JCoDestination;
import com.sap.conn.jco.JCoDestinationManager;
import com.sap.conn.jco.JCoException;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoRepository;

import de.vogella.sap.system.model.SapSystem;

/**
 * Connection allows to get and execute SAP functions. The constructor expect a
 * SapSystem and will save the connection data to a file. The connection will
 * also be automatically be established.
 */

public class Connection {
 static String SAP_SERVER = "SAP_SERVER";
 private JCoRepository repos;
 private JCoDestination dest;

 public Connection(SapSystem system) {
  MyDestinationDataProvider myProvider = new MyDestinationDataProvider(system);
  com.sap.conn.jco.ext.Environment
    .registerDestinationDataProvider(myProvider);
  try {
   dest = JCoDestinationManager.getDestination(SAP_SERVER);
   System.out.println("Attributes:");
   System.out.println(dest.getAttributes());
   repos = dest.getRepository();
  } catch (JCoException e) {
   throw new RuntimeException(e);
  }

 }

 /**
  * Method getFunction read a SAP Function and return it to the caller. The
  * caller can then set parameters (import, export, tables) on this function
  * and call later the method execute.
  * 
  * getFunction translates the JCo checked exceptions into a non-checked
  * exceptions
  */
 public JCoFunction getFunction(String functionStr) {
  JCoFunction function = null;
  try {
   function = repos.getFunction(functionStr);
  } catch (Exception e) {
   e.printStackTrace();
   throw new RuntimeException(
     "Problem retrieving JCO.Function object.");
  }
  if (function == null) {
   throw new RuntimeException("Not possible to receive function. ");
  }

  return function;
 }

 /**
  * Method execute will call a function. The Caller of this function has
  * already set all required parameters of the function
  * 
  */
 public void execute(JCoFunction function) {
  try {
   JCoContext.begin(dest);
   function.execute(dest);

  } catch (JCoException e) {
   e.printStackTrace();
  } finally {
   try {
    JCoContext.end(dest);
   } catch (JCoException e) {
    e.printStackTrace();
   }
  }
 }

}
======================
3:测试连接
import static org.junit.Assert.assertTrue;

import org.junit.Test;

import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoTable;

import de.vogella.sap.rfc.core.connection.Connection;
import de.vogella.sap.system.model.SapSystem;

public class ConnectionTester {
 static String SAP = "SAP_SERVER";

 @Test
 public void checkConnection() {
  // SAP System
  SapSystem system = new SapSystem("PFT", "pwdf6394.wdf.sap.corp", "600", "76", "mytester", "welcome");
  
  Connection connect = new Connection(system);

  JCoFunction function = connect.getFunction("BAPI_USER_GETLIST");
  function.getImportParameterList().setValue("MAX_ROWS", 10);
  connect.execute(function);
  JCoTable table = function.getTableParameterList().getTable("USERLIST");
  assertTrue("User Tabelle should not be empty", !table.isEmpty());
 }
}
======================
4:简化JCo存取
import com.sap.conn.jco.JCoTable;

/**
 * TableAdapter is used to simplify the reading of the values of the Jco tables
 */

public class TableAdapterReader {
 protected JCoTable table;

 public TableAdapterReader(JCoTable table) {
  this.table = table;
 }

 public String get(String s) {
  return table.getValue(s).toString();
 }

 public Boolean getBoolean(String s) {
  String value = table.getValue(s).toString();
  return value.equals("X");
 }

 public String getMessage() {
  return table.getString("MESSAGE");
 }

 public int size() {
  return table.getNumRows();
 }

 public void next() {
  table.nextRow();
 }
}
5:最后测试
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoTable;

import de.vogella.sap.rfc.core.connection.Connection;
import de.vogella.sap.rfc.helper.TableAdapterReader;
import de.vogella.sap.system.model.SapSystem;

public class TableAdapterTester {
 @Test
 public void checkConnection() {
  // SAP System
  SapSystem system = new SapSystem("PFT", "pwdf6394.wdf.sap.corp", "600",
    "76", "mytester", "welcome");

  Connection connect = new Connection(system);

  JCoFunction function = connect.getFunction("BAPI_USER_GETLIST");
  function.getImportParameterList().setValue("MAX_ROWS", 10);
  connect.execute(function);
  JCoTable table = function.getTableParameterList().getTable("USERLIST");
  TableAdapterReader adapter = new TableAdapterReader(table);

  System.out.println("Number of Users: " + adapter.size());
  for (int i = 0; i < adapter.size(); i++) {
   // USERNAME is a column in the table "USERLIST"
   String s = adapter.get("USERNAME");
   assertNotNull(s);
   assertTrue(s.length() > 0);
   System.out.println(s);
   adapter.next();
  }

  assertTrue("User Tabelle should not be empty", !table.isEmpty());
 }
}