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());
 }
}