TUTORIAL SAP JAVA Connector en Windows.
Archivos:Archivos:Archivos:Archivos:
Manual Java Connector: docs\jco\JCo Tutorial.pdf
Archivo Instalación Java Connector: instalar\sapjco-ntintel-2.1.1.zip
Java JDK 1.2.2: instalar\jdk-1_2_2_011-win.exe
InstalaciónInstalaciónInstalaciónInstalación Instalar Java JDKInstalar Java JDKInstalar Java JDKInstalar Java JDK En este ejemplo se usa la versión 1.2.2 (recomendado versión mayor o igual a 1.2), se
pueden bajar de http://java.sun.com/
Tip: Es recomendable modificar la variable de entorno PATH, en W2K
En avanzado
Variables de entorno
Editamos la variable de sistema Path, agregando al final c:\jdk1.2.2\bin, o el directorio
correspondiente al JDK instalado.
De la misma forma agregamos la variable de sistema CLASSPATH, (ver final del
documento)
Instalar JAVA ConnectorInstalar JAVA ConnectorInstalar JAVA ConnectorInstalar JAVA Connector
Antes que nada leer el Manual Java Conector(docs\jco\JCo Tutorial.pdf).
En este ejemplo se usa Java Connector 2.0, del manual se desprende que necesita una
versión Java JDK mayor o igual a ala 1.2.
El proceso de instalación de Java Connector esta descrito en el capítulo 3.2.2 del manual
docs\jco\JCo Tutorial.pdf).
Programación en JAVAProgramación en JAVAProgramación en JAVAProgramación en JAVA Mi primer programaMi primer programaMi primer programaMi primer programa Supondremos que el Java Connector se instaló en el directorio C:\Jco
Primero vamos al Shell,
1) En pantalla principal Windows, Inicio�Ejecutar
ejecutamos cmd,
posteriormente nos vamos al directorio c:\Jco\demo
En el directorio C:\Jco\demo existen varios ejemplos, veamos el
Example1.java
/** * Example1.java * Property of SAP AG, Walldorf * (c) Copyright SAP AG, Walldorf, 2000. * All rights reserved. */ import com.sap.mw.jco.*; /** * @version 1.0 * @author SAP AG, Walldorf */ public class Example1 { public static void main(String[] argv) { JCO.Client client = null; try { // Print the version of the underlying JCO library System.out.println("\n\nVersion of the JCO-library:\n" + "---------------------------\n" + JCO.getMiddlewareVersion()); // Create a client connection to a dedicated R/3 system client = JCO.createClient("000", // SAP client "johndoe", // userid "*****", // password "EN", // language "appserver",// host name "00"); // system number // Open the connection client.connect(); // Get the attributes of the connection and print them JCO.Attributes attributes = client.getAttributes(); System.out.println("Connection attributes:\n" + "----------------------\n" + attributes); // Create the input parameter list JCO.ParameterList input = JCO.createParameterList(); // Set the first (and only) import parameter input.appendValue("REQUTEXT", JCO.TYPE_CHAR, 255, "This is my first Jayco example."); // Create the out parameter list JCO.ParameterList output = JCO.createParameterList(); // Specify the parameters types the function will be returning output.addInfo("ECHOTEXT", JCO.TYPE_CHAR, 255); output.addInfo("RESPTEXT", JCO.TYPE_CHAR, 255); // Call the function client.execute("STFC_CONNECTION", input, output); // Print the result
System.out.println("The function 'STFC_CONNECTION' returned the following parameters:\n" + "-----------------------------------------------------------------"); for (int i = 0; i < output.getFieldCount(); i++) { System.out.println("Name: " + output.getName(i) + " Value: " + output.getString(i)); }//for // Close the connection client.disconnect(); // All done System.out.println("\n\nCongratulations! It worked."); } catch (Exception ex) { System.out.println("Caught an exception: \n" + ex); if (client != null) client.disconnect(); } } }
Este ejemplo es una prueba de conexión a SAP, si observamos la sentencia
client = JCO.createClient( "000", // SAP client "johndoe", // userid "*****", // password "EN", // language "appserver",// host name "00"); // system number
Acá le damos los parámetros de entrada para el Logon a SAP, es claro que debemos
modificar esta línea con los datos Logon respectivos a la máquina SAP a la cual queremos
conectarnos.
Modificada esta línea debemos proceder de la siguiente manera
(la opción classpath esta explicada al final de este documento)
Si observamos se creó el archivo Example1.class.
Entonces, procedemos
Posteriormente aparece el siguiente mensaje en la pantalla indicándonos si la conexión fue
exitosa:
Uso de BAPIsUso de BAPIsUso de BAPIsUso de BAPIs
En el directorio demo existe el programa TutorialBapi1.java que ejemplifica el uso de
BAPI, en particular de la BAPI BAPI_COMPANYCODE_GETLIST import com.sap.mw.jco.*; /** * @author Thomas G. Schuessler, ARAsoft GmbH * http://www.arasoft.de */ public class TutorialBapi1 extends Object { JCO.Client mConnection; JCO.Repository mRepository; public TutorialBapi1() { try { // Change the logon information to your own system/user mConnection = JCO.createClient("200", // SAP client "carjb9", // userid "brasil01", // password null, // language "bau214s0.bhp.com.au", // application server host name "00"); // system number mConnection.connect(); mRepository = new JCO.Repository("ARAsoft", mConnection); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } JCO.Function function = null; JCO.Table codes = null; try { function = this.createFunction("BAPI_COMPANYCODE_GETLIST"); if (function == null) { System.out.println("BAPI_COMPANYCODE_GETLIST" + " not found in SAP."); System.exit(1); } mConnection.execute(function); JCO.Structure returnStructure = function.getExportParameterList().getStructure("RETURN"); if (! (returnStructure.getString("TYPE").equals("") || returnStructure.getString("TYPE").equals("S")) ) { System.out.println(returnStructure.getString("MESSAGE")); System.exit(1); } codes = function.getTableParameterList().getTable("COMPANYCODE_LIST"); for (int i = 0; i < codes.getNumRows(); i++) { codes.setRow(i); System.out.println(codes.getString("COMP_CODE") + '\t' + codes.getString("COMP_NAME")); } } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } try { codes.firstRow(); for (int i = 0; i < codes.getNumRows(); i++, codes.nextRow()) { function = this.createFunction("BAPI_COMPANYCODE_GETDETAIL"); if (function == null) { System.out.println("BAPI_COMPANYCODE_GETDETAIL" + " not found in SAP."); System.exit(1); } function.getImportParameterList(). setValue(codes.getString("COMP_CODE"), "COMPANYCODEID"); function.getExportParameterList().setActive(false, "COMPANYCODE_ADDRESS");
mConnection.execute(function); JCO.Structure returnStructure = function.getExportParameterList().getStructure("RETURN"); if (! (returnStructure.getString("TYPE").equals("") || returnStructure.getString("TYPE").equals("S") || returnStructure.getString("TYPE").equals("W")) ) { System.out.println(returnStructure.getString("MESSAGE")); } JCO.Structure detail = function.getExportParameterList(). getStructure("COMPANYCODE_DETAIL"); System.out.println(detail.getString("COMP_CODE") + '\t' + detail.getString("COUNTRY") + '\t' + detail.getString("CITY")); } } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } mConnection.disconnect(); } public JCO.Function createFunction(String name) throws Exception { try { IFunctionTemplate ft = mRepository.getFunctionTemplate(name.toUpperCase()); if (ft == null) return null; return ft.getFunction(); } catch (Exception ex) { throw new Exception("Problem retrieving JCO.Function object."); } } public static void main (String args[]) { TutorialBapi1 app = new TutorialBapi1(); } }
en este ejemplo la salida va al archivo list1.txt. Si observamos el archivo posteriormente es
del estilo 0001 SAP A.G. 1000 BHP Billiton Limited 1001 Baniettor Mining (Pty) Lt 1002 Old BHPB Aust Fin Pt USD 1003 Billiton Australia Fin Pt 1005 BHP Billiton Ltd (Min AU) 1010 BHP Intnl Fin Corporation 1011 Consolidated Nominees 1020 BHP Marine & Genrl Ins 1021 Donkerpoort Iron Ltd 1030 BHP Intrntl Holdings LTD 1031 Uniholdings Ltd 1040 BHP Finance Ltd 1043 BHP Finance Ltd (PET) 1045 BHP Finance Ltd MIN AUS 1046 BHP Finance Ltd MIN AMER 1050 BHP Holdings (USA) Inc. 1051 Gengro Ltd
1060 BHP Finance (USA) Inc 1061 African Metals Ltd 1070 Beswick Pty Ltd 1071 Tarrus (Pty) Ltd 1080 BHP Investment Hold Ltd 1081 Unilux SA 1083 BHP Inves Hold Ltd (Pet) 1090 BHP Finance Inv l PTY LTD
Setting the class path
SynopsisSynopsisSynopsisSynopsis The class path is the path that the Java runtime environment searches for
classes and other resource files. The class search path (more commonly
known by the shorter name, "class path") can be set using either the -classpath option when calling an SDK tool (the preferred method) or by
setting the CLASSPATH environment variable. The -classpath option is preferred because you can set it individually for each application without
affecting other applications and without other applications modifying its
value. C:> sdkTool ----classpath classpath classpath classpath classpath1;;;;classpath2... -or- C:> set CLASSPATH=set CLASSPATH=set CLASSPATH=set CLASSPATH=classpath1;;;;classpath2... where: sdkTool
A command-line tool, such as java, javac, or javadoc. For a listing, see SDK
Tools.
classpath1;;;;classpath2 Class paths to the .jar, .zip or .class files. Each classpath should end with a
filename or directory depending on what you are setting the class path to:
• For a .jar or .zip file that contains .class files, the class path ends with
the name of the .zip or .jar file.
• For .class files in an unnamed package, the class path ends with the
directory that contains the .class files.
• For .class files in a named package, the class path ends with the
directory that contains the "root" package (the first package in the
full package name). Multiple path entries are separated by semi-colons. With the set command, it's important to omit spaces from around the equals sign (=).
The default class path is the current directory. Setting the CLASSPATH variable or using the -classpath command-line option overrides that default, so if you want to include the current directory in the search path, you must include "...." in the new settings. Classpath entries that are neither directories nor archives (.zip or .jar files) are ignored. DescriptionDescriptionDescriptionDescription The class path tells SDK tools and applications where to find third-party and user-defined classes -- that is, classes that are not Java extensions or part of the Java platform. The class path needs to find any classes you've compiled with the javac compiler -- its default is the current directory to conveniently enable those classes to be found. Java 2 SDK, the JVM and other SDK tools find classes by searching the Java platform (bootstrap) classes, any extension classes, and the class path, in that order. (For details on the search strategy, see How Classes Are Found.) Class libraries for most applications will want to take advantage of the extensions mechanism. You only need to set the class path when you want to load a class that's (a) not in the current directory or in any of its subdirectories, and (b) not in a location specified by the extensions mechanism. If you are upgrading from an older version of the SDK, your startup settings may include CLASSPATH settings that are no longer needed. You should remove any settings that are not application-specific, such as classes.zip. Some third-party applications that use the Java Virtual Machine may modify your CLASSPATH environment variable to include the libaries they use. Such settings can remain.
You can change the class path by using the Java tools' -classpath option when you invoke the JVM or other SDK tools or by using the CLASSPATH environment variable. Using the -classpath option is preferred over setting CLASSPATH environment variable because you can set it individually for each application without affecting other applications and without other applications modifying its value. Classes can be stored either in directories (folders) or in archive files. The Java platform classes are stored in rt.jar. For more details on archives and information on how the class path works, see Understanding the class path and package names near the end of this document. Important Note: Some older versions of the JDK sofware included a <jdk-dir>/classes entry in the default class path. That directory exists for use by the JDK software, and should not be used for application classes.
Application classes should be placed in a directory outside of the JDK
directory hierarcy. That way, installing a new JDK does not force you to
reinstall application classes. For compatibility with older versions,
applications that use the <jdk-dir>/classes directory as a class library will run
in the current version, but there is no guarantee that they will run in future
versions.
Using the SDK tools' Using the SDK tools' Using the SDK tools' Using the SDK tools' ----classpath optionclasspath optionclasspath optionclasspath option The SDK tools java, jdb, javac, and javah have a ----classpathclasspathclasspathclasspath option which replaces the path or paths specified by the CLASSPATH environment variable while the tool runs. This is the recommended option for changing class path settings, because each application can have the class path it needs without interfering with any other application. The runtime tool java has a ----cpcpcpcp option, as well. This option is an abbreviation for ----classpathclasspathclasspathclasspath.
For very special cases, both java and javac have options that let you change the path they use to find their own class libraries. The vast majority of users will never to need to use those options, however. Using the CLASSPATH environment variableUsing the CLASSPATH environment variableUsing the CLASSPATH environment variableUsing the CLASSPATH environment variable In general, you will want to use the -classpath command-line option, as explained in the previous section. This section shows you how to set the CLASSPATH environment variable if you want to do that, or clear settings left over from a previous installation.
Setting CLASSPATHSetting CLASSPATHSetting CLASSPATHSetting CLASSPATH The CLASSPATH environment variable is modified with the setsetsetset command. The format is: set CLASSPATH=set CLASSPATH=set CLASSPATH=set CLASSPATH=path1;;;;path2 ... The paths should begin with the letter specifying the drive, for example, C:\. That way, the classes will still be found if you happen to switch to a different drive. (If the path entries start with backslash (\) and you are on drive D:, for example, then the classes will be expected on D:, rather thanC:.) Clearing CLASSPATHClearing CLASSPATHClearing CLASSPATHClearing CLASSPATH If your CLASSPATH environment variable has been set to a value that is not correct, or if your startup file or script is setting an incorrect path, you can unset CLASSPATH by using: C:> set CLAset CLAset CLAset CLASSPATH=SSPATH=SSPATH=SSPATH=
This command unsets CLASSPATH for the current command prompt window only. You should also delete or modify your startup settings to ensure that you have the right CLASSPATH settings in future sessions. Changing Startup SettingsChanging Startup SettingsChanging Startup SettingsChanging Startup Settings
If the CLASSPATH variable is set at system startup, the place to look for it
depends on your operating system:
Operating
System Method Windows 95 and
98 Examine autoexec.bat for the set command. Other (Windows
NT, Windows
2000, ...) The CLASSPATH environment variable can be set using the
System utility in the Control Panel. Understanding the class path and package namesUnderstanding the class path and package namesUnderstanding the class path and package namesUnderstanding the class path and package names Java classes are organized into packages which are mapped to directories in the file system. But, unlike the file system, whenever you specify a package name, you specify the whole package name -- never part of it. For example, the package name for java.awt.Button is always specified as java.awt. For example, suppose you want the Java runtime to find a class named Cool.class in the package utility.myapp. If the path to that directory isC:\java\MyClasses\utility\myapp, you would set the class path so that it contains C:\java\MyClasses. To run that app, you could use the following JVM command: C:> java java java java ----classpath C:classpath C:classpath C:classpath C:\\\\javajavajavajava\\\\MyClasses utility.myapp.CoolMyClasses utility.myapp.CoolMyClasses utility.myapp.CoolMyClasses utility.myapp.Cool
When the app runs, the JVM uses the class path settings to find any other classes defined in the utility.myapp package that are used by the Cool class. Note that the entire package name is specified in the command. It is not possible, for example, to set the class path so it contains C:\java\MyClasses\utility and use the command java myapp.Cool. The class would not be found. (You may be wondering what defines the package name for a class. The answer is that the package name is part of the class and cannot be modified, except by recompiling the class.) Note: Note: Note: Note: An interesting consequence of the package specification mechanism is that files which are part of the same package may actually exist in different directories. The package name will be the same for each class, but the path to each file may start from a different directory in the class path. Folders and archive filesFolders and archive filesFolders and archive filesFolders and archive files When classes are stored in a directory (folder), like c:\java\MyClasses\utility\myapp, then the class path entry points to the directory that contains the first element of the package name. (in this case, C:\java\MyClasses, since the package name is utility.myapp.) But when classes are stored in an archive file (a .zip or .jar file) the class path entry is the path to and including the .zip or .jar file. For example, to use a class library that is in a .jar file, the command would look something like this: C:> java java java java ----classpath C:classpath C:classpath C:classpath C:\\\\javajavajavajava\\\\MyClassesMyClassesMyClassesMyClasses\\\\myclasses.jar utility.myapp.Coolmyclasses.jar utility.myapp.Coolmyclasses.jar utility.myapp.Coolmyclasses.jar utility.myapp.Cool
Multiple specificationsMultiple specificationsMultiple specificationsMultiple specifications To find class files in the directory C:\java\MyClasses as well as classes in C:\java\OtherClasses, you would set the class path to: C:> java java java java ----classpath C:classpath C:classpath C:classpath C:\\\\javajavajavajava\\\\MyClasses;C:MyClasses;C:MyClasses;C:MyClasses;C:\\\\javajavajavajava\\\\OtherClassesOtherClassesOtherClassesOtherClasses ... Note that the two paths are separated by a semicolon. Specification orderSpecification orderSpecification orderSpecification order The order in which you specify multiple class path entries is important. The Java interpreter will look for classes in the directories in the order they appear in the class path variable. In the example above, the Java interpreter will first look for a needed class in the directory C:\java\MyClasses. Only if it doesn't find a class with the proper name in that directory will the interpreter look in the C:\java\OtherClasses directory.