This example shows how to make a sales order using the SAP java Connector and BAPI_SALESORDER_CREATEFROMDAT2. First the ABAP code for using the BAPI is shown, and next the Java implementation is shown.
| ABAP Example |
| Java Example |
REPORT z_bapi_create_sales_order_test .
* Order header:
* - Order type: OR Important you must use the german code TA
* - Sales org: 1000
* - Distrb. chan.: 10
* - Division: 00
*
* - Sold to party: 1032
* - Ship to party: 1032
* - Purch order: DG-19970626-3
*
* Order item:
* - Material: P-100
* - Qty: 1
DATA:
* Order partners
li_order_partners TYPE STANDARD TABLE OF bapiparnr,
l_order_partners LIKE bapiparnr,
* Structures for order header
l_order_header_in LIKE bapisdhd1,
l_order_header_inx LIKE bapisdhd1x,
* Tables for order items
li_order_items_in TYPE STANDARD TABLE OF bapisditm,
l_order_items_in LIKE bapisditm,
li_order_items_inx TYPE STANDARD TABLE OF bapisditmx,
l_order_items_inx LIKE bapisditmx,
* Return table from bapi call
li_return TYPE STANDARD TABLE OF bapiret2,
l_return TYPE bapiret2,
* Sales document number
l_vbeln LIKE bapivbeln-vbeln,
* Error flag
l_errflag(1) TYPE c.
START-OF-SELECTION.
*------------------------------------------------------------------
* Build partner information
*------------------------------------------------------------------
CLEAR l_order_partners.
l_order_partners-partn_role = 'AG'. "Remember German codes !
l_order_partners-partn_numb = '0000001032'.
APPEND l_order_partners TO li_order_partners.
*------------------------------------------------------------------
* Build order header
*------------------------------------------------------------------
* Update flag
l_order_header_inx-updateflag = 'I'.
* Sales document type
l_order_header_in-doc_type = 'TA'. "Remember German codes !
l_order_header_inx-doc_type = 'X'.
* Sales organization
l_order_header_in-sales_org = '1000'.
l_order_header_inx-sales_org = 'X'.
* Distribution channel
l_order_header_in-distr_chan = '10'.
l_order_header_inx-distr_chan = 'X'.
* Division
l_order_header_in-division = '00'.
l_order_header_inx-division = 'X'.
* Purchase order
l_order_header_in-purch_no_c = 'DG-19970626-300'.
l_order_header_inx-purch_no_c = 'X'.
*------------------------------------------------------------------
* Build order item(s) - Only 1 is used in this example
*------------------------------------------------------------------
l_order_items_in-itm_number = '10'.
l_order_items_inx-itm_number = '10'.
l_order_items_in-material = 'P-100'.
l_order_items_inx-material = 'X'.
l_order_items_in-comp_quant = '1.000'.
l_order_items_inx-comp_quant = 'X'.
APPEND l_order_items_in TO li_order_items_in.
l_order_items_inx-updateflag = 'I'.
APPEND l_order_items_inx TO li_order_items_inx.
*------------------------------------------------------------------
* CALL Bapi
*------------------------------------------------------------------
CALL FUNCTION 'BAPI_SALESORDER_CREATEFROMDAT2'
EXPORTING
order_header_in = l_order_header_in
order_header_inx = l_order_header_inx
testrun = 'X'
IMPORTING
salesdocument = l_vbeln
TABLES
return = li_return
order_items_in = li_order_items_in
order_items_inx = li_order_items_inx
order_partners = li_order_partners.
END-OF-SELECTION.
*------------------------------------------------------------------
* Check and write Return table
*------------------------------------------------------------------
CLEAR l_errflag.
WRITE: / 'Sales dcoument: ', l_vbeln.
LOOP AT li_return INTO l_return.
WRITE: / l_return-type, l_return-message(50).
IF l_return-type = 'E'.
l_errflag = 'X'.
ENDIF.
ENDLOOP.
*------------------------------------------------------------------
* No errors - Commit
*------------------------------------------------------------------
IF l_errflag IS INITIAL.
CALL FUNCTION 'BAPI_TRANSACTION_COMMIT'.
ENDIF.
This example e3monstartes how to create a salesorder using BAPI_SALESORDER_CREATEFROMDAT2 and how to read the status inmformation of an existing sales order using BAPI_SALESORDER_GETSTATUS.
The example conists of the following classes:
| Run | Main method |
| MainScreen | The main screen for the application, containing the menus for exiting the applikation, loggin on- and off to SAP, create salesorder and view salesorder status |
| LogonScreen | Logon pad for logon to SAP. Also has a method to handle logoff. The actual logon i carried out using the Connect method of the SapConnection class |
| SapConnection | Contains code for loggin on to SAP. The class has no user interface. The user interface is provided by the LogonScreen class. The class creates a public static connection object mConnection. As the connection object is static, the same connection will be used for all instances of the class. That means that if a connection has / been made onece, all other classes that uases an instance of SapConnection, will have access to the same connection. |
| CreateOrder | User interface for creating a new sales order. Orders are created using class JcoCreateSalesorderFromDat2. |
| JcoCreateSalesorderFromDat2 | Code for creating a new sales order. The class has no userinterface. The user interface is provided by class CreateOrder. The class calls BAPI_SALESORDER_CREATEFROMDAT2 and BAPI_TRANSACTION_COMMIT. |
| ViewOrder | User interface for viewing the status information of a sales order. |
| JcoBapiSalesorderGetStatus | Code for viewing the status information of a sales order. The class has no user interface. The user interface is procied by class ViewOrder. The cklass calls BAPI_SALESORDER_GETSTATUS |
//**************************************************************************
// Contains the Main method
//**************************************************************************
public class Run
{
public static void main(String[] args)
{ MainScreen mainscreen1 = new MainScreen();
mainscreen1.show();
}
}
The main screen for the application, containing the menus for exiting the applikation, loggin on- and off to SAP, create salesorder and view salesorder status.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
public class MainScreen extends JFrame
{
//---------------------------------------------------------------
//Class level variables
//---------------------------------------------------------------
//Menus
private JMenu FileMenu;
private JMenu SalesOrderMenu;
private Border loweredbevel;
private JLabel statusLabel;
private SapConnection sapConnection;
private LogonScreen logonscreen1;
//------------------------------------------------------------------
// Constructor class
//------------------------------------------------------------------
public MainScreen()
{ //---------------------------------------------------------------
//Set frame properties
//---------------------------------------------------------------
setSize(700,600);
setTitle("Sales orders");
// Exit applikation when using the Close button
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//---------------------------------------------------------------
// Center screen
//---------------------------------------------------------------
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = this.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
this.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
Container myPane = getContentPane();
//---------------------------------------------------------------
// Add menus
//---------------------------------------------------------------
//Actions
Action LogOn = new MenuActions("Logon","LOGON");
Action LogOff = new MenuActions("Logoff","LOGOFF");
Action exitApp = new MenuActions("Exit","EXIT_APP");
Action CreateOrder = new MenuActions("Create salesorder","CREATE_ORDER");
Action ViewOrder = new MenuActions("View order status","VIEW_ORDER");
// File menu
FileMenu = new JMenu("File");
FileMenu.add(LogOn);
FileMenu.add(LogOff);
FileMenu.add(exitApp);
// Sales order menu
SalesOrderMenu = new JMenu("Sales order");
SalesOrderMenu.add(CreateOrder);
SalesOrderMenu.add(ViewOrder);
//Implement menu bar
JMenuBar MenuBar = new JMenuBar();
MenuBar.add(FileMenu);
MenuBar.add(SalesOrderMenu);
setJMenuBar(MenuBar);
//Create status label with lowered border
loweredbevel = BorderFactory.createLoweredBevelBorder();
statusLabel = new JLabel("Status: Logged off");
statusLabel.setBorder(loweredbevel);
myPane.add(statusLabel,"South");
//Initialize Logoon screen class
logonscreen1 = new LogonScreen(this);
sapConnection = new SapConnection();
} // public MainScreen()
//---------------------------------------------------------------
// CLASS MenuActions - Private class to handle menu actions
//---------------------------------------------------------------
class MenuActions extends AbstractAction
{
public MenuActions(String p_name,String p_Action)
{ putValue(Action.NAME, p_name);
putValue("myAction", p_Action);
}
public void actionPerformed(ActionEvent evt)
{ String actionType = (String)getValue("myAction");
if ( actionType == "EXIT_APP" )
System.exit(0);
else if ( actionType == "LOGON" )
SapLogon();
else if ( actionType == "LOGOFF" )
SapLogoff();
else if ( actionType == "CREATE_ORDER" )
CreateOrder();
else if ( actionType == "VIEW_ORDER" )
ViewOrder();
}
}
//---------------------------------------------------------------
// Private method SapLogon - Logon to SAP, shows the LogonScreen
//---------------------------------------------------------------
private void SapLogon()
{ logonscreen1.show();
if ( sapConnection.mConnection == null )
{ statusLabel.setText("Status: Logged off"); }
else
{ statusLabel.setText("Status: Logged on"); }
}
//---------------------------------------------------------------
// Private method SapLogoff - Calls the SapLogoff method of the
// LogonScreen class
//---------------------------------------------------------------
private void SapLogoff()
{ logonscreen1.SapLogoff();
if ( sapConnection.mConnection == null )
{ statusLabel.setText("Status: Logged off"); }
else
{ statusLabel.setText("Status: Logged on"); }
}
//---------------------------------------------------------------
// Private method CreateOrder - Calls the CreateOrder screen
//---------------------------------------------------------------
private void CreateOrder()
{ CreateOrder createOrder = new CreateOrder(this);
createOrder.show();
}
//---------------------------------------------------------------
// Private method ViewOrder - Calls the ViewOrder screen
//---------------------------------------------------------------
private void ViewOrder()
{ ViewOrder viewOrder = new ViewOrder(this);
viewOrder.show();
}
} //END public class MainScreen extends JFrame
Logon pad for logon to SAP. Also has a method to handle logoff. The actual logon i carried out using the Connect method of the SapConnection class.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import com.sap.mw.jco.*; //The JCO
public class LogonScreen extends JDialog
{
private JTextField textClient;
private JTextField textUser;
private JTextField textPw;
private JTextField textLangu;
private JTextField textHost;
private JTextField textSystem;
private SapConnection sapConnection;
public LogonScreen(JFrame parent)
{
super(parent, "Logon to SAP",true);
//---------------------------------------------------------------
//Set frame properties
//---------------------------------------------------------------
setSize(400,400);
setTitle("Logon to SAP");
setLocation(225,155);
//---------------------------------------------------------------
// Center screen
//---------------------------------------------------------------
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = this.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
this.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
Container myContentPane = getContentPane();
//---------------------------------------------------------------
// Create buttons
//---------------------------------------------------------------
JPanel buttonPanel = new JPanel();
JButton cancel = new JButton("Cancel");
JButton logOn = new JButton("Logon");
buttonPanel.add(logOn);
buttonPanel.add(cancel);
myContentPane.add(buttonPanel, "South");
//---------------------------------------------------------------
// Create labels and text fields
//---------------------------------------------------------------
Box vBox = Box.createVerticalBox();
JLabel labelClient = new JLabel("Client: ");
textClient = new JTextField("800",3);
JLabel labelUser = new JLabel("User: ");
textUser = new JTextField("WMHEFRN");
JLabel labelPw = new JLabel("Password: ");
textPw = new JTextField("sluppert3");
JLabel labelLangu = new JLabel("Language: ");
textLangu = new JTextField("EN");
JLabel labelHost = new JLabel("Host: ");
textHost = new JTextField("172.29.80.207");
JLabel labelSystem = new JLabel("System: ");
textSystem = new JTextField("00");
vBox.add(Box.createVerticalStrut(40));
vBox.add(labelClient);
vBox.add(textClient);
vBox.add(labelUser);
vBox.add(textUser);
vBox.add(labelPw);
vBox.add(textPw);
vBox.add(labelLangu);
vBox.add(textLangu);
vBox.add(labelHost);
vBox.add(textHost);
vBox.add(labelSystem);
vBox.add(textSystem);
vBox.add(Box.createVerticalStrut(40));
myContentPane.add(vBox, "Center");
//---------------------------------------------------------------
// Action listeners
//---------------------------------------------------------------
cancel.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent evt)
{ setVisible(false);
}
} );
logOn.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent evt)
{ sapLogon(textClient.getText(),
textUser.getText(),
textPw.getText(),
textLangu.getText(),
textHost.getText(),
textSystem.getText()
);
}
} );
} //END public LogonScreen()
//---------------------------------------------------------------
// Private Method sapLogon - Logs on to SAP
//---------------------------------------------------------------
private void sapLogon(String client,
String User,
String Pw,
String Langu,
String Host,
String System)
{ Exception sapException = null;
sapConnection = new SapConnection();
sapException = sapConnection.Connect(client, //SAP client
User, //User ID
Pw, //Password
Langu, //Language
Host, //Host
System); //System
if ( sapException == null )
{ JOptionPane.showMessageDialog(this, "Logon ok");
this.hide();
}
else
{ JOptionPane.showMessageDialog(this,sapException);
}
} //END method
//---------------------------------------------------------------
// Public Method sapLogoff - Logs off from SAP
//---------------------------------------------------------------
public void SapLogoff()
{ if (sapConnection.mConnection == null)
{ JOptionPane.showMessageDialog(this, "You was not logged on"); }
else
{ try
{ sapConnection.mConnection.disconnect();
sapConnection.mConnection = null;
JOptionPane.showMessageDialog(this, "Logged off");
}
catch (Exception ex)
{JOptionPane.showMessageDialog(this,ex);}
} // END try
} //END method
} //END public LogonScreen(JFrame parent)
Contains code for loggin on to SAP. The class has no user interface. The user interface is provided by the LogonScreen class. The class creates a public static connection object mConnection. As the connection object is static, the same connection will be used for all instances of the class. That means that if a connection has / been made onece, all other classes that uases an instance of SapConnection, will have access to the same connection.
import com.sap.mw.jco.*; //The JCO
public class SapConnection
{ public static JCO.Client mConnection = null;
public SapConnection()
{
}
public Exception Connect(String client,
String User,
String Pw,
String Langu,
String Host,
String System)
{ try
{ mConnection = JCO.createClient(client, //SAP client
User, //User ID
Pw, //Password
Langu, //Language
Host, //Host
System); //System
mConnection.connect();
return null;
}
catch (Exception ex)
{mConnection = null;
return ex;
}
}
}
User interface for creating a new sales order. Orders are created using class JcoCreateSalesorderFromDat2.
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.event.*;
import java.util.*;
public class CreateOrder extends JDialog
{ //Screen fields
private JTextField txtDocType;
private JTextField txtPartnerNumber;
private JTextField txtSalesOrg;
private JTextField txtDistrChn;
private JTextField txtDiv;
private JTextField txtPurchOrd;
private JTextArea txtStatusField;
private JList bapiReturnList;
// Object for table data
private Object[][] itemData;
//Vector to hold return vaklues from the BAPI
private Vector bapiReturn = new Vector(0);
public CreateOrder(JFrame parent)
{ super(parent, "Create sales Order",true);
//---------------------------------------------------------------
//Set frame properties
//---------------------------------------------------------------
setSize(700,600);
setTitle("Create Sales Order");
//---------------------------------------------------------------
// Center screen
//---------------------------------------------------------------
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = this.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
this.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
Container myContentPane = getContentPane();
//---------------------------------------------------------------
// Create buttons
//---------------------------------------------------------------
JPanel buttonPanel = new JPanel();
JButton createButton = new JButton("Create");
JButton cancelButton = new JButton("Cancel");
buttonPanel.add(createButton);
buttonPanel.add(cancelButton);
myContentPane.add(buttonPanel, "South");
//---------------------------------------------------------------
// Screen fields - Textfields and labels
//---------------------------------------------------------------
JLabel lblDocType = new JLabel("Order type: ");
lblDocType.setAlignmentX(0);
txtDocType = new JTextField("TA");
txtDocType.setMaximumSize(new Dimension(50,Short.MAX_VALUE));
txtDocType.setAlignmentX(0);
JLabel lblPartnerNumber = new JLabel("Sold to party:");
lblPartnerNumber.setAlignmentX(0);
txtPartnerNumber = new JTextField("0000001032");
txtPartnerNumber.setMaximumSize(new Dimension(160,Short.MAX_VALUE));
txtPartnerNumber.setAlignmentX(0);
JLabel lblSalesOrg = new JLabel("Sales org.:");
lblSalesOrg.setAlignmentX(0);
txtSalesOrg = new JTextField("1000");
txtSalesOrg.setMaximumSize(new Dimension(75,Short.MAX_VALUE));
txtSalesOrg.setAlignmentX(0);
JLabel lblDistrChn = new JLabel("Distribution channel:");
lblDistrChn.setAlignmentX(0);
txtDistrChn = new JTextField("10");
txtDistrChn.setMaximumSize(new Dimension(40,Short.MAX_VALUE));
txtDistrChn.setAlignmentX(0);
JLabel lblDiv = new JLabel("Division: ");
lblDiv.setAlignmentX(0);
txtDiv = new JTextField("00");
txtDiv.setMaximumSize(new Dimension(40,Short.MAX_VALUE));
txtDiv.setAlignmentX(0);
JLabel lblPurchOrd = new JLabel("Purchase order:");
lblPurchOrd.setAlignmentX(0);
txtPurchOrd = new JTextField("DG-19970626-300");
txtPurchOrd.setMaximumSize(new Dimension(400,Short.MAX_VALUE));
txtPurchOrd.setAlignmentX(0);
//---------------------------------------------------------------
// Screen layout
//---------------------------------------------------------------
JPanel centerPanel = new JPanel();
Box vBox = Box.createVerticalBox();
vBox.add(lblDocType);
vBox.add(txtDocType);
vBox.add(Box.createRigidArea(new Dimension(0,10)));
vBox.add(lblPartnerNumber);
vBox.add(txtPartnerNumber);
vBox.add(Box.createRigidArea(new Dimension(0,10)));
vBox.add(lblSalesOrg);
vBox.add(txtSalesOrg);
vBox.add(Box.createRigidArea(new Dimension(0,10)));
vBox.add(lblDistrChn);
vBox.add(txtDistrChn);
vBox.add(Box.createRigidArea(new Dimension(0,10)));
vBox.add(lblDiv);
vBox.add(txtDiv);
vBox.add(Box.createRigidArea(new Dimension(0,10)));
vBox.add(lblPurchOrd);
vBox.add(txtPurchOrd);
//Filler box
Dimension minSize = new Dimension(5, 30);
Dimension prefSize = new Dimension(5, 30);
Dimension maxSize = new Dimension(Short.MAX_VALUE, 30);
vBox.add(new Box.Filler(minSize, prefSize, maxSize));
//---------------------------------------------------------------
// Create table
//---------------------------------------------------------------
TableModel myModel = new itemTableModel();
JTable itemTable = new JTable(myModel);
//Create scroll pane and add table
JScrollPane myScrollPane = new JScrollPane(itemTable);
//Setting initial column width of the first column
TableColumn column = null;
column = itemTable.getColumnModel().getColumn(0);
column.setMaxWidth(30);
//Setting the table size
itemTable.setPreferredScrollableViewportSize(new Dimension(500,100));
vBox.add(myScrollPane);
//---------------------------------------------------------------
// Create List box to hold Bapi return valkues
//---------------------------------------------------------------
bapiReturnList = new JList();
JScrollPane bapireturnScrollPane = new JScrollPane(bapiReturnList);
vBox.add(Box.createRigidArea(new Dimension(0,5)));
vBox.add(bapireturnScrollPane);
//---------------------------------------------------------------
// Putting it all together
//---------------------------------------------------------------
centerPanel.add(vBox);
myContentPane.add(centerPanel,"Center");
//---------------------------------------------------------------
// Create a default item in the table
//---------------------------------------------------------------
itemData = new Object[3][10];
itemData[0][0] = "10";
itemData[1][0] = "P-100";
itemData[2][0] = "1.000";
//---------------------------------------------------------------
// Action listeners for buttons
//---------------------------------------------------------------
cancelButton.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent evt)
{ setVisible(false);
}
} );
createButton.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent evt)
{createSalesOrder();
}
} );
} //END - public CreateOrder(JFrame parent)
//---------------------------------------------------------------
// CLASS ItemTable - TABLE MODEL
//---------------------------------------------------------------
class itemTableModel extends AbstractTableModel
{
// Column headers
String[] columnNames = {"Item", "Material", "Quantity"};
// Set number of columns in the table = 3
public int getColumnCount() {
return 3;
}
// Set number of rows in the table
public int getRowCount() {
return 5;
}
public String getColumnName(int col) {
return columnNames[col];
}
// Set value of a cell
public Object getValueAt(int row, int col) {
return itemData[col][row];
}
// Which cells are editable.
// It is only necessary to implement this method
// if the table is editable
public boolean isCellEditable(int row, int col)
{ return true; //All cells are editable
}
// Update cell after it has been edited.
public void setValueAt(Object value, int row, int col)
{ itemData[col][row] = value;
fireTableCellUpdated(row, col);
}
}
//---------------------------------------------------------------
// METHOD CreateSalesOrder - Create the salesorder using
// class JcoCreateSalesorderFromDat2
//---------------------------------------------------------------
private void createSalesOrder()
{ String SalesDocument;
try
{ JcoCreateSalesorderFromDat2 jcoCreateSalesorder = new JcoCreateSalesorderFromDat2();
SalesDocument = jcoCreateSalesorder.jcoCreate( txtPartnerNumber.getText(),
txtDocType.getText(),
txtSalesOrg.getText(),
txtDistrChn.getText(),
txtDiv.getText(),
txtPurchOrd.getText(),
itemData,
bapiReturn );
bapiReturnList.setListData(bapiReturn);
JOptionPane.showMessageDialog(this, "Sales document " + SalesDocument + " created");
}
catch (Exception mException)
{ JOptionPane.showMessageDialog(this, mException);
}
} // END - private void createSalesOrder()
} //END - public class CreateOrder extends JDialog
Code for creating a new sales order. The class has no userinterface. The user interface is provided by class CreateOrder. The class calls BAPI_SALESORDER_CREATEFROMDAT2 and BAPI_TRANSACTION_COMMIT.
import com.sap.mw.jco.*; //The JCO
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class JcoCreateSalesorderFromDat2
{
private SapConnection sapConnection1;
private IRepository mRepository;
private JCO.Function jcoFunction;
private JCO.Function jcoCommit;
//*******************************************************************
// CONSTRUCTOR
//*******************************************************************
public JcoCreateSalesorderFromDat2()
{
sapConnection1 = new SapConnection();
}
//*******************************************************************
// CLASS jcoCreate - Creates sales order
//*******************************************************************
public String jcoCreate( String PartnerNumber,
String DocType,
String SalesOrg,
String DistrChan,
String Division,
String PurchOrder,
Object [][] itemData,
Vector bapiReturn)
throws RepositoryNotCreatedException,
FunctionNotCreatedException,
InvalidParameterException,
ExecuteException,
FunctionCommitNotCreatedException,
ExecuteCommitException
{
//---------------------------------------------------------
// Create metadata with JCO Repository
//---------------------------------------------------------
try
{ mRepository = new JCO.Repository("hFrank",sapConnection1.mConnection); }
catch (Exception mException)
{ throw new RepositoryNotCreatedException(); }
//---------------------------------------------------------
// Get a function template for BAPI_SALESORDER_CREATEFROMDAT2
// from the repository and create a function
//---------------------------------------------------------
try
{ // Get a function template from the repository
IFunctionTemplate ftemplate = mRepository.getFunctionTemplate("BAPI_SALESORDER_CREATEFROMDAT2");
// Create a function from the template
jcoFunction = new JCO.Function(ftemplate);
if ( jcoFunction == null )
throw new FunctionNotCreatedException();
}
catch (Exception mException)
{ throw new FunctionNotCreatedException(); }
//---------------------------------------------------------
// Set import parameters
//---------------------------------------------------------
try
{
//Partner information - Note that this is a table parameter
JCO.Table ORDER_PARTNERS = jcoFunction.getTableParameterList().getTable("ORDER_PARTNERS");
ORDER_PARTNERS.appendRow();
ORDER_PARTNERS.setValue("AG","PARTN_ROLE");
ORDER_PARTNERS.setValue(PartnerNumber,"PARTN_NUMB");
// ORDER_HEADER_INX - Structure parameter
JCO.Structure order_header_inx =
jcoFunction.getImportParameterList().getStructure("ORDER_HEADER_INX");
order_header_inx.setValue("I","UPDATEFLAG");
order_header_inx.setValue("X","DOC_TYPE");
order_header_inx.setValue("X","SALES_ORG");
order_header_inx.setValue("X","DISTR_CHAN");
order_header_inx.setValue("X","DIVISION");
order_header_inx.setValue("X","PURCH_NO_C");
//ORDER_HEADER_IN - Structure parameter
JCO.Structure order_header_in =
jcoFunction.getImportParameterList().getStructure("ORDER_HEADER_IN");
order_header_in.setValue(DocType,"DOC_TYPE");
order_header_in.setValue(SalesOrg,"SALES_ORG");
order_header_in.setValue(DistrChan,"DISTR_CHAN");
order_header_in.setValue(Division,"DIVISION");
order_header_in.setValue(PurchOrder,"PURCH_NO_C");
// Item data - Table parameter.
JCO.Table ORDER_ITEMS_INX = jcoFunction.getTableParameterList().getTable("ORDER_ITEMS_INX");
JCO.Table ORDER_ITEMS_IN = jcoFunction.getTableParameterList().getTable("ORDER_ITEMS_IN");
for ( int i = 0; i <= itemData.length; i++)
{ if (itemData[0][i] != null)
{ ORDER_ITEMS_INX.appendRow();
ORDER_ITEMS_IN.appendRow();
ORDER_ITEMS_INX.setValue(itemData[0][i],"ITM_NUMBER");
ORDER_ITEMS_IN.setValue(itemData[0][i],"ITM_NUMBER");
ORDER_ITEMS_INX.setValue("X","MATERIAL");
ORDER_ITEMS_IN.setValue(itemData[1][i],"MATERIAL");
ORDER_ITEMS_INX.setValue("X","COMP_QUANT");
ORDER_ITEMS_IN.setValue(itemData[2][i],"COMP_QUANT");
ORDER_ITEMS_INX.setValue("X","UPDATEFLAG");
}
}
}
catch (Exception mException)
{ mException.printStackTrace();
throw new InvalidParameterException();
}
//---------------------------------------------------------
// Execute function
//---------------------------------------------------------
try
{ sapConnection1.mConnection.execute(jcoFunction);
}
catch (Exception mException)
{ mException.printStackTrace();
throw new ExecuteException();
}
//---------------------------------------------------------
// Commit
//---------------------------------------------------------
try
{ // Get a function template from the repository
IFunctionTemplate ftemplate = mRepository.getFunctionTemplate("BAPI_TRANSACTION_COMMIT");
// Create a function from the template
jcoCommit = new JCO.Function(ftemplate);
if ( jcoCommit == null )
throw new FunctionNotCreatedException();
}
catch (Exception mException)
{ throw new FunctionCommitNotCreatedException(); }
// Execute COMMIT
try
{ sapConnection1.mConnection.execute(jcoCommit);
}
catch (Exception mException)
{ mException.printStackTrace();
throw new ExecuteCommitException();
}
//---------------------------------------------------------
// Handle return data
//---------------------------------------------------------
// Return
JCO.Table jcoReturn = jcoFunction.getTableParameterList().getTable("RETURN");
for (int i = 0; i < jcoReturn.getNumRows(); i++)
{ jcoReturn.setRow(i);
String Message = jcoReturn.getField("TYPE").getValue() + " " +
jcoReturn.getField("MESSAGE").getValue();
bapiReturn.setSize(i + 1);
bapiReturn.setElementAt(new String(Message),i );
}
// Sales document number
JCO.Field SalesDocumentField = jcoFunction.getExportParameterList().getField("SALESDOCUMENT");
String SalesDocumentString = SalesDocumentField.getValue().toString();
return SalesDocumentString;
} // END - public void jcoCreate()
//*******************************************************************
// Exception classes
//*******************************************************************
class RepositoryNotCreatedException extends Exception
{ public RepositoryNotCreatedException()
{ super("Repository object could not be created"); }
}
class FunctionNotCreatedException extends Exception
{ public FunctionNotCreatedException()
{ super("Function could not be created"); }
}
class FunctionCommitNotCreatedException extends Exception
{ public FunctionCommitNotCreatedException()
{ super("Function COMMIT could not be created"); }
}
class InvalidParameterException extends Exception
{ public InvalidParameterException()
{ super("Invalid parameter"); }
}
class ExecuteException extends Exception
{ public ExecuteException()
{ super("Execution failed"); }
}
class ExecuteCommitException extends Exception
{ public ExecuteCommitException()
{ super("Execution of commit failed"); }
}
}
User interface for viewing the status information of a sales order.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.table.*;
import java.util.*;
public class ViewOrder extends JDialog
{ private JTextField txtFindDoc; // sales document number
private JLabel txtDocDate; // Document date
private JLabel txtPurchNo; // Purchase order number
private JLabel txtReqdateH; // Requested delivery date
private JLabel txtDlvStatH; // Delivery block (document header)
private JLabel txtBapiReturn; // Bapi return infor field
private JTable itemTable;
private Object[][] itemData;
public ViewOrder(JFrame parent)
{ super(parent, "View sales order",true);
//---------------------------------------------------------------
// Size and Center screen
//---------------------------------------------------------------
setSize(700,600);
setTitle("View Sales Order");
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = this.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
this.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
Container myContentPane = getContentPane();
//---------------------------------------------------------------
// Add View and Exit buttons at the buttom of the screen
//---------------------------------------------------------------
JPanel buttonPanel = new JPanel();
JButton exitButton = new JButton("Exit");
buttonPanel.add(exitButton);
myContentPane.add(buttonPanel,"South");
//---------------------------------------------------------------
// Add search order field + button
//---------------------------------------------------------------
JLabel lblFindDoc = new JLabel("Order number: ");
txtFindDoc = new JTextField("0000006973");
txtFindDoc.setMaximumSize(new Dimension(90,Short.MAX_VALUE));
JButton viewButton = new JButton("View");
viewButton.setMaximumSize(new Dimension(80,Short.MAX_VALUE));
Box hBox1 = Box.createHorizontalBox();
hBox1.add(Box.createRigidArea(new Dimension(200,0)));
hBox1.add(lblFindDoc);
hBox1.add(Box.createRigidArea(new Dimension(10,0)));
hBox1.add(txtFindDoc);
hBox1.add(Box.createRigidArea(new Dimension(10,0)));
hBox1.add(viewButton);
hBox1.add(Box.createRigidArea(new Dimension(200,0)));
myContentPane.add(hBox1,"North");
//---------------------------------------------------------------
// Add Order header fields
//---------------------------------------------------------------
//---- Document date
Box hBox2 = Box.createHorizontalBox();
JLabel lblDocDate = new JLabel("Document date: ");
lblDocDate.setMaximumSize(new Dimension(150,Short.MAX_VALUE));
lblDocDate.setAlignmentX(0);
hBox2.add(lblDocDate);
txtDocDate = new JLabel();
txtDocDate.setMaximumSize(new Dimension(150,Short.MAX_VALUE));
txtDocDate.setAlignmentX(0);
txtDocDate.setBorder(BorderFactory.createLoweredBevelBorder());
hBox2.add(txtDocDate);
//--- Purchase order number
Box hBox3 = Box.createHorizontalBox();
JLabel lblPurchNo = new JLabel("Purchase order number: ");
lblPurchNo.setMaximumSize(new Dimension(150,Short.MAX_VALUE));
lblPurchNo.setAlignmentX(0);
hBox3.add(lblPurchNo);
txtPurchNo = new JLabel();
txtPurchNo.setMaximumSize(new Dimension(150,Short.MAX_VALUE));
txtPurchNo.setAlignmentX(100);
txtPurchNo.setBorder(BorderFactory.createLoweredBevelBorder());
hBox3.add(txtPurchNo);
//--- Requested delivery date
Box hBox4 = Box.createHorizontalBox();
JLabel lblReqdateH = new JLabel("Requested delivery date:");
lblReqdateH.setMaximumSize(new Dimension(150,Short.MAX_VALUE));
lblReqdateH.setAlignmentX(0);
hBox4.add(lblReqdateH);
txtReqdateH = new JLabel();
txtReqdateH.setMaximumSize(new Dimension(150,Short.MAX_VALUE));
txtReqdateH.setAlignmentX(0);
txtReqdateH.setBorder(BorderFactory.createLoweredBevelBorder());
hBox4.add(txtReqdateH);
//--- Delivery block (document header)
Box hBox5 = Box.createHorizontalBox();
JLabel lblDlvStatH = new JLabel("Delivery block: ");
lblDlvStatH.setMaximumSize(new Dimension(280,Short.MAX_VALUE));
lblDlvStatH.setAlignmentX(0);
hBox5.add(lblDlvStatH);
txtDlvStatH = new JLabel();
txtDlvStatH.setMaximumSize(new Dimension(20,Short.MAX_VALUE));
txtDlvStatH.setAlignmentX(0);
txtDlvStatH.setBorder(BorderFactory.createLoweredBevelBorder());
hBox5.add(txtDlvStatH);
Box vBox1 = Box.createVerticalBox();
//Filler box
Dimension minSize = new Dimension(5, 30);
Dimension prefSize = new Dimension(5, 30);
Dimension maxSize = new Dimension(Short.MAX_VALUE, 30);
vBox1.add(new Box.Filler(minSize, prefSize, maxSize));
vBox1.add(hBox2);
vBox1.add(Box.createRigidArea(new Dimension(0,10)));
vBox1.add(hBox3);
vBox1.add(Box.createRigidArea(new Dimension(0,10)));
vBox1.add(hBox4);
vBox1.add(Box.createRigidArea(new Dimension(0,10)));
vBox1.add(hBox5);
vBox1.add(Box.createRigidArea(new Dimension(0,10)));
vBox1.add(new Box.Filler(minSize, prefSize, maxSize));
JLabel lblItems = new JLabel("Order items: ");
lblItems.setMaximumSize(new Dimension(200,Short.MAX_VALUE));
lblItems.setAlignmentX(0);
vBox1.add(lblItems);
//---------------------------------------------------------------
// Create table
//---------------------------------------------------------------
itemData = new Object[6][50];
itemData[0][0] = "";
TableModel myModel = new itemTableModel();
itemTable = new JTable(myModel);
//Create scroll pane and add table
JScrollPane myScrollPane = new JScrollPane(itemTable);
//Setting initial column width
TableColumn column = null;
column = itemTable.getColumnModel().getColumn(0);
column.setPreferredWidth(50);
column = itemTable.getColumnModel().getColumn(1);
column.setPreferredWidth(110);
column = itemTable.getColumnModel().getColumn(2);
column.setPreferredWidth(250);
column = itemTable.getColumnModel().getColumn(3);
column.setPreferredWidth(75);
column = itemTable.getColumnModel().getColumn(4);
column.setPreferredWidth(75);
column = itemTable.getColumnModel().getColumn(5);
column.setPreferredWidth(30);
//Setting the table size
itemTable.setPreferredScrollableViewportSize(new Dimension(650,100));
vBox1.add(myScrollPane);
//---------------------------------------------------------------
// BAPI return info field
//---------------------------------------------------------------
vBox1.add(new Box.Filler(minSize, prefSize, maxSize));
JLabel lblBapiReturn = new JLabel("Return info from BAPI: ");
vBox1.add(lblBapiReturn);
Box vBox2 = Box.createHorizontalBox();
txtBapiReturn = new JLabel(" ");
txtBapiReturn.setMaximumSize(new Dimension(800,Short.MAX_VALUE));
txtBapiReturn.setAlignmentX(0);
txtBapiReturn.setBorder(BorderFactory.createLoweredBevelBorder());
vBox2.add(txtBapiReturn);
vBox1.add(vBox2);
//---------------------------------------------------------------
// Build it all together
//---------------------------------------------------------------
JPanel centerPanel = new JPanel();
centerPanel.add(vBox1);
myContentPane.add(centerPanel,"Center");
//---------------------------------------------------------------
// Action listeners for buttons
//---------------------------------------------------------------
exitButton.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent evt)
{ setVisible(false);
}
} );
viewButton.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent evt)
{ viewSalesOrder();
}
} );
}
//---------------------------------------------------------------
// METHOD - viewSalesOrder
//---------------------------------------------------------------
private void viewSalesOrder()
{ String DocDate = null;
String BapiReturn = null;
JcoBapiSalesorderGetStatus getOrderStatus = new JcoBapiSalesorderGetStatus();
try
{ // Find order
getOrderStatus.GetStatus(txtFindDoc.getText());
// Get header info
txtDocDate.setText(getOrderStatus.getDocDate());
txtPurchNo.setText(getOrderStatus.getPurchNo());
txtReqdateH.setText(getOrderStatus.getReqDateH());
txtDlvStatH.setText(getOrderStatus.getDlvBlock());
// Get item data
int numItems = getOrderStatus.getNumItems(); //Number of items
String [][] itemArray = getOrderStatus.getItems();
for (int row = 0; row < itemArray.length; row++)
{ for (int col = 0; col < 6; col++)
itemData[col][row] = itemArray[row][col];
}
// Get BapiReturn
txtBapiReturn.setText(getOrderStatus.getBapiReturn());
}
catch (Exception mException)
{ JOptionPane.showMessageDialog(this, mException);
}
}
//---------------------------------------------------------------
// CLASS ItemTable - TABLE MODEL
//---------------------------------------------------------------
class itemTableModel extends AbstractTableModel
{
String[] columnNames = {"Item", "Material", "Description",
"Quantity","Net value","Curr"};
// Set number of columns in the table
// = Number of column names
public int getColumnCount() {
//return columnNames.length;
return 6;
}
// Set number of rows in the table
public int getRowCount() {
return 50;
}
public String getColumnName(int col) {
return columnNames[col];
}
// Set value of a cell
public Object getValueAt(int row, int col) {
return itemData[col][row];
}
// No editable cells
public boolean isCellEditable(int row, int col)
{ return false;
}
// Update cell after it has been edited.
public void setValueAt(Object value, int row, int col)
{ itemData[row][col] = value;
}
}
}
Code for viewing the status information of a sales order. The class has no user interface. The user interface is procied by class ViewOrder. The cklass calls BAPI_SALESORDER_GETSTATUS
import com.sap.mw.jco.*; //The JCO
import java.util.*;
import java.text.*;
public class JcoBapiSalesorderGetStatus
{ private SapConnection sapConnection1;
private IRepository mRepository;
private JCO.Function jcoFunction;
// Return parameters
private String oDocDate;
private String oPurchNo;
private String oReqDateH;
private String oDlvBlock;
private String oBapiReturn;
private String[][] itemData;
public JcoBapiSalesorderGetStatus()
{ sapConnection1 = new SapConnection();
}
public void GetStatus ( String iSalesDocument )
throws SalesDocumentEmptyException,
RepositoryNotCreatedException,
FunctionNotCreatedException,
InvalidInputParameterException,
ExecuteException,
GetStatusException,
BapiReturnException
{ // Date format used for date fields
DateFormat dateFormatter;
Locale dkLocale = new Locale("dk","DK");
dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT,dkLocale);
// Salesdocument number is empty
if (iSalesDocument.length() == 0)
throw new SalesDocumentEmptyException();
//---------------------------------------------------------
// Create metadata with JCO Repository
//---------------------------------------------------------
try
{ mRepository = new JCO.Repository("hFrank",sapConnection1.mConnection); }
catch (Exception mException)
{ //mException.printStackTrace();
throw new RepositoryNotCreatedException();
}
//---------------------------------------------------------
// Get a function template for BAPI_SALESORDER_GETSTATUS
// from the repository and create a function
//---------------------------------------------------------
try
{ // Get a function template from the repository
IFunctionTemplate ftemplate = mRepository.getFunctionTemplate("BAPI_SALESORDER_GETSTATUS");
// Create a function from the template
jcoFunction = new JCO.Function(ftemplate);
if ( jcoFunction == null )
throw new FunctionNotCreatedException();
}
catch (Exception mException)
{ //mException.printStackTrace();
throw new FunctionNotCreatedException();
}
//---------------------------------------------------------
// Set the SALESDOCUMENT import parameter
//---------------------------------------------------------
try
{ JCO.Field SalesDocumentField = jcoFunction.getImportParameterList().getField("SALESDOCUMENT");
SalesDocumentField.setValue(iSalesDocument);
}
catch (Exception mException)
{ throw new InvalidInputParameterException();
}
//---------------------------------------------------------
// Execute function
//---------------------------------------------------------
try
{ sapConnection1.mConnection.execute(jcoFunction);
}
catch (Exception mException)
{ //mException.printStackTrace();
throw new ExecuteException();
}
//---------------------------------------------------------
// Get sales order status. Item info is saved in the
// array itemData.
//---------------------------------------------------------
try
{ JCO.Table jcoStatusInfo = jcoFunction.getTableParameterList().getTable("STATUSINFO");
int NumRows = jcoStatusInfo.getNumRows();
// Array dimension 2 (Columns):
// 0 : ITM_NUMBER Item number
// 1 : MATERIAL Material number
// 2 : SHORT_TEXT Short text for sales order item
// 3 : REQ_QTY Cumulative order quantity in sales units
// 4 : NET_VALUE Net value of the order item in document currency
// 5 : CURRENCY SD document currency
itemData = new String[NumRows][6];
for (int i=0; i < NumRows; i++)
{ jcoStatusInfo.setRow(i);
// These fields are header fields and it is only necessary to
// read info for the first item
if ( i == 0 )
{ oDocDate = dateFormatter.format(jcoStatusInfo.getField("DOC_DATE").getDate());
oPurchNo = jcoStatusInfo.getField("PURCH_NO").getValue().toString();
oReqDateH = dateFormatter.format(jcoStatusInfo.getField("REQ_DATE_H").getDate());
oDlvBlock = jcoStatusInfo.getField("DLV_BLOCK").getValue().toString();
}
// Item data
itemData[i][0] = jcoStatusInfo.getField("ITM_NUMBER").getValue().toString();
itemData[i][1] = jcoStatusInfo.getField("MATERIAL").getValue().toString();
itemData[i][2] = jcoStatusInfo.getField("SHORT_TEXT").getValue().toString();
itemData[i][3] = jcoStatusInfo.getField("REQ_QTY").getValue().toString();
itemData[i][4] = jcoStatusInfo.getField("NET_VALUE").getValue().toString();
itemData[i][5] = jcoStatusInfo.getField("CURRENCY").getValue().toString();
}
}
catch (Exception mException)
{ throw new GetStatusException();
}
//---------------------------------------------------------
// Get BAPIRETURN
//---------------------------------------------------------
try
{ JCO.Structure jcoBapiReturn = jcoFunction.getExportParameterList().getStructure("RETURN");
oBapiReturn = jcoBapiReturn.getField("TYPE").getValue() + " " +
jcoBapiReturn.getField("MESSAGE").getValue();
}
catch (Exception mException)
{ throw new BapiReturnException();
}
}
//*******************************************************************
// Classes that returns status information
//*******************************************************************
public String getDocDate()
{ return oDocDate; }
public String getPurchNo()
{ return oPurchNo; }
public String getReqDateH()
{ return oReqDateH; }
public String getDlvBlock()
{ return oDlvBlock; }
public String getBapiReturn()
{ return oBapiReturn; }
public String[][] getItems()
{ return itemData;
}
public int getNumItems()
{ return itemData.length;
}
//*******************************************************************
// Exception classes
//*******************************************************************
class SalesDocumentEmptyException extends Exception
{ public SalesDocumentEmptyException()
{ super("You must enter a sales document"); }
}
class RepositoryNotCreatedException extends Exception
{ public RepositoryNotCreatedException()
{ super("Repository object could not be created"); }
}
class FunctionNotCreatedException extends Exception
{ public FunctionNotCreatedException()
{ super("Function could not be created"); }
}
class InvalidInputParameterException extends Exception
{ public InvalidInputParameterException()
{ super("Invalid parameter"); }
}
class ExecuteException extends Exception
{ public ExecuteException()
{ super("Execution failed"); }
}
class GetStatusException extends Exception
{ public GetStatusException()
{ super("Error when reading status information"); }
}
class BapiReturnException extends Exception
{ public BapiReturnException()
{ super("Error whern reading BAPI return information"); }
}
}
| Converted from CHM to HTML with chm2web Standard 2.7 (unicode) |