How to Develop Web Services in WebASPart 2: Design your own Web services with ABAP HTTP Extensions By Axel Angeli, logosworld.com Editor's Note: To be honest, I didn't really understand the Web Application Server as well as I wanted to—until I read Axel's SAPtips white paper on the subject. Axel has a knack for making sense of SAP®'s solutions and helping others to understand their value. He believes that SAP's technological evolution is part of the overall trend towards open platforms and universal standards. What some SAP users may not realize is that the “future is now”—SAP has already reached the point where it can provide support for basic, integrated Web services initiatives. But stepping into SAP Web services does require mastery of new buzzwords like SOAP and WDSL. And, some key decisions about development environments must also be made. These choices may depend on which version of SAP is in use, which messaging systems are running, and many other factors. In this excellent how-to article, Axel digs right into all these issues. Building on his last piece, Axel starts with a basic introduction to Web services technologies, and then he takes a closer look at how basic Web services can be designed using WebAS, either with Business Server Pages or with HTTP extensions. Because this technology is still emerging, there are some judgment calls that must be made, such as whether to use traditional RFC/SAP HTTP Protocol, or WebAS's new ABAP Objects/HTTP classes. If this kind of techie talk peaks your interest, you're going to love Axel's opinionated, bird's eye view of SAP's Web services technologies. Chock full of actual coding examples, this article gives the real scoop on the technical capabilities SAP has to offer—capabilities that anyone who is looking to upgrade to the latest versions of SAP will want (and need) to know about. Technical Overview: The first part of this white paper1 uncovered the technical landscape of SAP’s WebAS and outlined how to develop classical server pages through the Business Server Pages (BSP). Web services are the recognized technology that provides automated services via the Internet. Given that fact, and given that a majority of international companies have SAP as their ERP system, it is a natural approach to make use of SAP itself to provide Web services. In this article, we’ll start by guiding you through an introduction to Web services and emerging protocols like SOAP and WDSL. Then, we'll discuss how Web services can be implemented using WebAS, either by means of Business Server Pages, or through SAP’s adaptation of the Java Servlet technology by means of the HTTP extensions super class. A note on public XML services: The examples for Web services in this document make use of the public services provided by Amazon.com. The developer key in the examples has been invalidated. The examples will still work, but we kindly ask you to register for your own developer token at http://amazon.com/xml, in order to comply with their code of conduct and as a gesture to proper “netiquette.” 1 Part one of this series is available for SAPtips subscribers in the SAPtips document library. The article is titled "How to Develop Web Services in WebAS – Part 1," by Axel Angeli. Copyright © 2003 by Klee Associates, Inc. www.SAPtips.com Page 1 How to Develop Web Services in WebASPart 2: Design your own Web services with ABAP HTTP Extensions Consulting Web Services from SAP and Anywhere Accessing SAP from Any Web Server Nowadays, the SAP ERP suite is the omnipresent software solution for enterprise computing. Many companies rely on SAP to manage their important finance and asset management issues, as well as their sales and distribution process, just to name a couple of the functional areas that SAP encompasses. A common—and definitely not very new—desire of users of information technology is to access the data stored in a centralized ERP system from anywhere in the world; especially now, since we have a feature-rich Internet browser client stored on every computer, including small pervasive devices like the palm-top computers. Under this premise, it appears as a natural choice to access your centralized SAP system via HTTP, the protocol your browser uses. Once you start talking about managing business processes remotely via the Internet, you're talking about the emerging technology that we call “Web services.” Accessing SAP ERP via HTTP HTTP Client Application (can be another R/3 system, too) HTTP Somewhere in the Internet/Intranet SAP WebAS ICM Internet Communication Manager COM Any HTTP Server HTTP Communication Interface Understands both HTTP and RFC RFC RFC RFC Function Modules BAPI SAP R/3 Figure 1: Accessing an ERP System HTTP Web services are designed to be accessed from another program, although they can generally be consulted from a Web browser as well. The calling program can be any program that understands HTTP, including SAP R/3 starting with release 3.0E. Before we go into details, let’s first learn more about Web services by example. Copyright © 2003 by Klee Associates, Inc. www.SAPtips.com Page 2 How to Develop Web Services in WebASPart 2: Design your own Web services with ABAP HTTP Extensions Example of a Web Service Let's look at what a typical Web service might look like. The principle of our example is very simple: • You send an HTTP request to the Web service provider. • You receive an XML document with the result. To visualize this, we shall have a look at Amazon.com, which allows XML-based inquiries to their bookstore through automated Web services. You can test this easily by entering the HTTP request shown in Figure 2 in your Web browser: http://xml.amazon.com/onca/xml2?t=webservices-20&tag=logosworldcom&devt=D2H30000000000&AsinSearch=3528057297&type=lite&f=xml. Figure 2: Calling the Amazon.com Web Service To make the request string a little better readable, we insert some line breaks after each part of the URL (Figure 3). However, the URL above must be entered as one string without any spaces as shown in Figure 2. http://xml.amazon.com/onca/xml2 ?t=webservices-20 &tag=logosworldcom &dev-t=D2H30000000000 &AsinSearch=3528057297 &type=lite&f=xml. Figure 3: The Amazon.com Web Service Request URL Formatted for Better Readability This request (which asks Amazon.com to list the books authored by someone in my company, logosworld.com), returns a plain XML document with the requested information included. See Figure 4 below. Copyright © 2003 by Klee Associates, Inc. www.SAPtips.com Page 3 How to Develop Web Services in WebASPart 2: Design your own Web services with ABAP HTTP Extensions <?xml version="1.0" encoding="UTF-8"?> <ProductInfo xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xsi:noNamespaceSchemaLocation ="http://xml.amazon.com/schemas2/dev-lite.xsd"> <Details> <Asin>3528057297</Asin> <ProductName>The SAP R/3 Guide to EDI and Interfaces</ProductName> <Authors> <Author>Axel Angeli</Author> <Author>Ulrich Streit</Author> <Author>Robi Gonfalonieri</Author> </Authors> <Manufacturer>Friedrick Vieweg & Son</Manufacturer> <OurPrice>$50.95</OurPrice> </Details> </ProductInfo> Tree representation of above XML ProductInfo └─ Details ├─ Asin │ └─ 3528057297 ├─ ProductName │ └─ The SAP R/3 Guide to EDI and Interfaces ├─ Authors │ └─ Author │ ├─ Axel Angeli │ ├─ Ulrich Streit │ └─ Robi Gonfalonieri └─ OurPrice └─ $50.95 Figure 4: XML-Response from Amazon.com About URLs, URIs and Points of Content In the theory of electronic communication, the partners at either end of a communication line are called end points. End points are also known as terminals, but this is a very ambiguous expression, so we better avoid it. Typically, a communication consists of two partners. At one end is a client, or requester, and at the other end is a point of content located on a server. In simple cases, the point of content is a file. In order to locate a point of content, the requester needs to specify sufficient information about the requested content, so that the Internet framework can route the request to a listener that runs on a server and is able to retrieve the content from the point of content. Typically, the requester specifies three items: Copyright © 2003 by Klee Associates, Inc. www.SAPtips.com Page 4 How to Develop Web Services in WebASPart 2: Design your own Web services with ABAP HTTP Extensions • The public name of the server and the domain; alternately, it can specify the server’s unique IP address. • The name of the resource in a format that it is understood by the listening port on the server • Optionally, parameters to pass further details about the request are provided. The assembly of these three information items is called a URI – Uniform Resource Indicator. In cases of Web pages, they are also known as URL – Uniform Resource Locator, where a URL is generally recognized as a subset or special variant of a URI. So we can say that a reference to a general point of content within the Internet is called a URI, a Uniform Resource Identifier, while URL is reserved to address a Web page. Figure 5 shows how a URI is constructed. Traditionally, a URL references a file on a specific server. Nowadays a URL may point to any kind of electronic resource that can be reached via HTTP. In these cases, the Web server captures the URL, and instead of returning a simple file, it calls a program to return a computed result. Parts of a URI Resource type Resource address Resource parameters r ete me me a m a n ol ara in rN file toc erve I-P ma th& o G o r a C p D P S http: //www. logosworld.de /asp/testdrive.htm ?user=micky&pass=mausi Resource address This is an identifying name of the requested ressource. Usually, this is simply the filename of the requested document, but it can be any string that is understood by the server. Usually the server tells from the suffix (e.g., .htm, .txt, .asp, .php, .cgi). Ressource type Tells the server which protocol to use. There are a wide variety of protocols. The most important protocols are the following ones: http: HyperText Transfer Protocol Tells the server that the requester (i.e., the browser) wants to receive general Unicode-coded documents (e.g., HTML). ftp: File Transfer Protocol Protocol specially for file transfers. smtp: Simple Mail Transfer Protocol Most important protocol for eMail distribution. Figure 5: Elements of a URI Copyright © 2003 by Klee Associates, Inc. www.SAPtips.com Page 5 How to Develop Web Services in WebASPart 2: Design your own Web services with ABAP HTTP Extensions Sending Parameters via HTTP In the previous example (Figure 2), we sent all the information that is needed by the server to build the proper result in the browser line. We did this by adding the parameters behind the actual URL. We could also have sent the parameters as an attachment to the HTTP request within the HTTP document body. The request for a search at Amazon.com is a relatively simply one. That is why we could pass all the search parameters as part of the requesting URI string. Issuing an HTTP request without sending any additional data is known as an “HTTP Get request”, and that is what we did. The form we chose to pass the parameters, i.e., by separating parameters with ampersands (&), is called a canonical URL. The history of this parameter-passing convention goes back to the long established CGI protocol2. A Detailed View on Web Services There is no precise, or even an official definition of “Web service.” Roughly speaking, Web services are programs that can be accessed via an Internet connection. Web services are typically comprised of self-service applications and automated workflows. Consider this typical self-service application: picture an order tracking service where a company provides an interface through the Internet that lets a client query the actual status of an order. A typical process flow may involve the following steps: 1. order receipt 2. production start and end 3. packing 4. shipping Such tracking systems are already established by many shipping companies. In this case, imagine that deliveries are transported from Sweden down to the Frankfurt airport, then flown “over the pond” to Chicago, and transported down to Kansas on a train. This obviously takes time, and in the course of order fulfillment, the commodities are passed through several hands. Given that there are so many uncertainties during the order flow, both the customer and vendor have a vested interest in regularly inspecting the status and location of each shipment. Many shipping companies offer these kinds of services already through the Internet, where the authorized parties can check the status and location of an order in process. As a natural extension, this “online tracking” can be formalized as a Web service by presenting the data in a computer-readable format that can be easily interpreted by a client program. Furthermore, the individual “legs”, or processing points, can report their status to the same Web service interface, so that the data no longer needs to be passed via paper notes, faxes, and manual re-entry. Via a basic Web service, this crucial information is now available in “quasi real-time”. Of course, you cannot simply load a program on your Web server and wait for anyone to call it up from anywhere within the reach of your network. Because Web services are designed to smoothly cooperate with other programs, they must abide by some guidelines: 1. Web services need to be easily accessible without any restrictive documentation. 2 If readers are looking for more explanation of the technical terms involved in Web services, we recommend taking a look at http://whatis.com, delivered by Techtarget.com Copyright © 2003 by Klee Associates, Inc. www.SAPtips.com Page 6 How to Develop Web Services in WebASPart 2: Design your own Web services with ABAP HTTP Extensions One great feature of the “human readable XML format” is that it usually allows an easy discovery of its contents and the document structure without the need for external documentation. As a point of comparison, many EDI projects failed primarily because the chosen formats were proprietary and had been disclosed only to a pre-selected, exclusive audience (E.G. EDIFACT documentation is only accessible by paying dues to the organization). 2. Web services should be easily adaptable to a range of clients and operating systems. The “Alpha and Omega” of Web services is “compatibility through convention”. No matter the content, Web services look largely the same. With the use of XML, it is possible to parse documents for necessary information, instead of mapping to a strict, inflexible format. Given this flexibility, a handler program can react smoothly on changes and additions in the sent documents. Characteristics of a Web Service From what is offered as Web services today, we can generally characterize Web services as having the following attributes: • Web services are invoked via an HTTP request. HTTP and the sister protocols—like the secure HTTPS option—are the undisputed standard as Internet protocol, and the only Internet protocol that is understood by all modern computers. • Web services deliver their results as an XML data stream. XML has become the de facto standard for Internet data exchange. XML documents have become so ubiquitous that it is an easy bet to say that XML will be the exclusive data exchange format for any kind of online, automated document-distribution system. Many document processing applications are transitioning from proprietary formats to storing data as XML data, or adding XML interfaces for external programs, e.g., the next version of Microsoft Office (Word, PowerPoint, etc.) will be XML-enabled, as will Adobe Framemaker. It is already obvious that the EDI world will soon be dominated by XML. Sooner or later all those acknowledged EDI standards like EDIFACT/UN or ANSI X.12 will go the way of the dinosaurs. • Web services results are structured data—data that can be easily interpreted by another program. This is an important characteristic that defines the essential difference between a classic Web page and a Web service. Web services are designed to be consulted primarily by other programs. Due to the text-based nature of XML documents, the results are naturally readable as well— another helpful XML feature. However, the response data must provide sufficient information so that a program can formally derive the requested information with as little effort as possible. • Web service results are either called by: • passing the requested data to an agent as an XML document, or • passing parameters as part of the URI, using the canonical URL as introduced by the CGI. (We'll elaborate on canonical URLs on the next page.) Web services via the SOAP-XML Standard As the request itself becomes more complicated, the URI(URL) used to issue the request would become lengthy. Therefore, the request can also be handed over to HTTP as a data block; this is Copyright © 2003 by Klee Associates, Inc. www.SAPtips.com Page 7 How to Develop Web Services in WebASPart 2: Design your own Web services with ABAP HTTP Extensions then called an “HTTP Post request”. There are many uses of HTTP Post requests, e.g., an HTTP Post request is sent to a server if you fill out an online HTML form in your browser and submit the form data. Amazon.com accepts requests from an HTTP Post as well and, in this case, it uses the SOAP protocol standard. SOAP is the acronym for the Simple Object Access Protocol and is itself an XML document. In addition to having the same features as a plain XML document, SOAP defines restrictions on how the document must be structured and how the XML tags have to be named. SOAP was designed out of the simple need to provide a standard format for the multiple ways you could structure a response with respect to naming your tags and laying out your response tree. SOAP has been designed to be used out of programs; therefore it is not that easy to test this variant in your browser, but in Figure 6, we show what a SOAP request might look like. <SOAP-ENV:Envelope> <SOAP-ENV:Body> <AsinSearchRequest> <AsinSearchRequest> <asin>3528057297</asin> <tag>logosworldcom</tag> <type>lite</type> <dev-tag>12345678901234</dev-tag> </AsinSearchRequest> </typens:AsinSearchRequest> </SOAP-ENV:Body> </SOAP-ENV:Envelope> Tree representation of above XML AsinSearchRequest ├─ asin │ └─ 3528057297 ├─ tag │ └─ logosworldcom ├─ type │ └─ lite └─ dev-tag └─ 12345678901234 Figure 6: SOAP Request for Amazon.com SAP as Web Client So far, we have seen how a Web service works in principle. The typical client of a Web service, however, is not an individual user, but another program, e.g., a program within SAP R/3. Let's take a closer look at how Web services function within various SAP releases. While the WebAS (SAP 4.7 and higher) can act generically as an HTTP client, the older releases make use of an SAP-provided utility called SAPHTTP, which is found both in the “/bin/exe” directory of the SAP application server (“/usr/sap/SID/SYS/bin/exe”) and as “SAPHTTP.EXE” as part of the SAPGUI installation package. Before you can use SAPHTTP, a valid RFC destination Copyright © 2003 by Klee Associates, Inc. www.SAPtips.com Page 8 How to Develop Web Services in WebASPart 2: Design your own Web services with ABAP HTTP Extensions must be defined with transaction SM59 in SAP (Figure 8), pointing to SAPHTTP either on the server or on the PC that has SAPGUI on. In the latter case, SAPHTTP will be called via the SAPGUI on the workstation. Using SAPHTTP, you call the following function modules: • function HTTP_GET, and • function HTTP_POST with the destination of SAPHTTP. See Figure 7 for an example of accessing Web services in SAP, using our Amazon.com book query example. DATA: ABSOLUTE_URI(128) type c. data: response_headers(80) occurs 0 with header line. data: RESPONSE_ENTITY_BODY(120) occurs 0 with header line. ABSOLUTE_URI = 'http://xml.amazon.com/onca/xml2?t=webservices-20' & '&tag=logosworldcom&dev-t=D2H30000000000' & '&AsinSearch=3528057297&type=lite&f=xml'. CALL FUNCTION 'HTTP_GET' EXPORTING ABSOLUTE_URI = ABSOLUTE_URI RFC_DESTINATION = 'SAPHTTPA' PROXY = '192.168.69.64:8080' TABLES * REQUEST_ENTITY_BODY = RESPONSE_ENTITY_BODY = RESPONSE_ENTITY_BODY RESPONSE_HEADERS = RESPONSE_HEADERS * REQUEST_HEADERS = EXCEPTIONS OTHERS = 8. LOOP AT response_entity_body. WRITE: / response_entity_body. ENDLOOP. Figure 7: SAP as Web Service Client with ABAP via SAPHTTP Utility Copyright © 2003 by Klee Associates, Inc. www.SAPtips.com Page 9 How to Develop Web Services in WebASPart 2: Design your own Web services with ABAP HTTP Extensions Figure 8: Definition of RFC Destination SAPHTTP in Transaction SM59 Calling a Web Services with the SAP WebAS HTTP Extension Class WebAS, with its generic HTTP interface, proposes to use the IF_HTTP_CLIENT interface class instead. Standard SAP WebAS distribution includes the report SXSLT_TEST, whose form LOAD_HTTP gives an example of how to request an HTTP page. In Figure 9 we constructed another example to demonstrate the essential. Intermezzo (and key SAP RFC tip): I recommend continuing to use the traditional method via the RFC destination to SAPHTTP whenever possible. Not only will it keep your development backward-compatible with older SAP releases, but the new access method, via the ABAP Object syntax, is still in a state of evolution, and cannot currently satisfy the needs of a modern developer. Unfortunately, ABAP Workbench, Copyright © 2003 by Klee Associates, Inc. www.SAPtips.com Page 10 How to Develop Web Services in WebASPart 2: Design your own Web services with ABAP HTTP Extensions the traditional SAP development environment, only has very basic support for ABAP/Objects. The core tool of every modern development workbench, the debugger, does not allow the display of essential information about ABAP/Objects and the current setting of attributes. The ABAP editor does also not support ABAP/Objects in a convenient way. Editing aids, like Intellisense, which displays methods and attributes for an object while you type, are either completely missing or awkward to use. With respect to the HTTP classes that ship with WebAS, it must be said that a large part of the coding is realized on the kernel level, which makes it nearly impossible to debug there. I am aware that a large community of developers, who dedicate their time, ambition, and professional obsession to object oriented development will heavily object, but from an experienced software architect’s and software auditor’s point of view, this way in which HTTP services are currently implemented in WebAS cannot be endorsed at this time. The only advantage of the HTTP classes over the traditional SAPHTTP is the direct implementation of all HTTP features, as opposed to SAPHTTP, which basically does HTTP forwarding to your proxy. But when you take into account that real life implementations of Web clients from SAP will forcibly access the Internet via a proxy anyway, this is not much of an advantage. Therefore, I decidedly state that, as of this writing, the best practice is to ignore the HTTP classes of WebAS, while continuing to use SAPHTTP for outbound Internet access and BSP for inbound HTTP calls. I will keep an eye on the evolving ABAP/Objects and HTTP classes of WebAS, and at the point where these new technologies surpass the traditional SAP HTTP protocols, I will author an update to SAPtips readers. For a detailed look at the WebAS HTTP client classes, see Figure 9 below, which submits a query to Amazon.com. Copyright © 2003 by Klee Associates, Inc. www.SAPtips.com Page 11 How to Develop Web Services in WebASPart 2: Design your own Web services with ABAP HTTP Extensions REPORT ZAXXTEST_CLHTTP. . CLASS cl_ixml DEFINITION LOAD. DATA: response TYPE string. DATA: g_ixml TYPE REF TO if_ixml. DATA: g_stream_factory TYPE REF TO if_ixml_stream_factory. DATA: headfields TYPE tihttpnvp. DATA: client TYPE REF TO if_http_client, host TYPE string, port TYPE string, proxy_host TYPE string, proxy_port TYPE string, path TYPE string, scheme TYPE i. During program load we create factory (helper) classes for XML handling LOAD-OF-PROGRAM. g_ixml = cl_ixml=>create( ). g_stream_factory = g_ixml->create_stream_factory( ). START-OF-SELECTION. Setting the parameters needed by the object host = 'http://xml.amazon.com'. port = '80'. path = '/onca/xml2?t=webservices-20' & '&tag=logosworldcom&dev-t=D2H30000000000' & '&AsinSearch=3528057297&type=lite&f=xml'. proxy_host = '192.168.69.64'. proxy_port = '8080'. scheme = 1. "1=HTTP 2=HTTPS * Create HTTP client object CALL METHOD cl_http_client=>create EXPORTING host = host service = port proxy_host = proxy_host proxy_service = proxy_port scheme = scheme IMPORTING client = client. * Create HTTP client object, send & receive client->request->set_header_field( name = value = client->request->set_header_field( name = value = '~request_uri' path ). '~request_method' 'GET' ). * send & receive client->send( ). client->receive( ). * Capture the result data response = client->response->get_cdata( ). Copyright © 2003 by Klee Associates, Inc. www.SAPtips.com Page 12 How to Develop Web Services in WebASPart 2: Design your own Web services with ABAP HTTP Extensions * Capture the header fields from the result CALL METHOD client->response->get_header_fields CHANGING fields = headfields. WRITE: / response COLOR COL_NEGATIVE. Figure 9: WebAS as HTTP Client Discovering a Web Service with WSDL and UDDI While the previous examples are certainly clear enough to understand the idea behind sending Web service requests and interpreting the responses, it is not clear how to find out how the SOAP requests need to be formatted. To do this, we need some sort of documentation. The required documentation for the form of a Web service can in turn be easily represented as a formal XML document. These formal descriptions of SOAP requests are done in a language called WSDL, the Web Services Description Language. The WSDL tells you how the tags of the request and response have to be named and what tree layout the XML documents will have. The WSDL format for Amazon.com is illustrated in Figure 10. If your Web service is to be accessed by many foreign sources, the next step is to publish the WSDL in a public directory, just as you publish a telephone number in the yellow pages. One of the popular Web service directories is the UDDI (Universal Description, Discovery and Integration), which is upheld by a consortium mainly driven by IBM. However, like the yellow pages, these directories are of interest only for a certain niche group of clients, as the directories do not indicate anything about the quality of a service. In practice, the use of a Web service is not typically established on an ad hoc basis. Rather, in advance, you would know exactly what kind of service you wanted to use, and you would already know the information you needed to access it, including the WSDL, without having to consult the UDDI. This key point should not go unmentioned: if you search for WSDL in SAP’s Interface Repository (http://ifr.sap.com), you may not find what you expect. SAP has not yet committed itself to any standards like WSDL. WSDL is mainly driven by IBM and Microsoft and it already has the status of a recommendation by the W3C (World Wide Web Consortium). Instead of WDSL, SAP has affiliated itself with a competing standard called the Web Service Choreography Interface (WSCI), an initiative mainly driven by SUN Microsystems and BEA. There appear to be some political issues in play here, because while WSCI may not be worse than WSDL, it isn't better either. Needless to say, competing Web services standards only slow down the corporate acceptance of Web services, so we can only hope that the political issues will be set aside in the interests of universal interoperability. Copyright © 2003 by Klee Associates, Inc. www.SAPtips.com Page 13 How to Develop Web Services in WebASPart 2: Design your own Web services with ABAP HTTP Extensions <definitions targetNamespace= "urn:PI/DevCentral/SoapService" name="AmazonSearch"> <types> <xsd:schema> <xsd:complexType name="AsinRequest"> <xsd:all> <xsd:element name="asin" /> <xsd:element name="tag" /> <xsd:element name="type" /> <xsd:element name="devtag" /> <xsd:element name="offer" /> <xsd:element name="offerpage" minOccurs="0"/> </xsd:all> </xsd:complexType> </xsd:schema> </types> <message name="AsinSearchRequest"> <part name="AsinSearchRequest" type="typens:AsinRequest"/> </message> <message name="AsinSearchResponse"> <part name="return" type="typens:ProductInfo"/> </message> </definitions> Figure 10: WSDL-Definition of an Amazon Search by Article Number (ASIN) Implementing Your Own Web Services Now that we have seen how we can make use of other people’s Web services, what we really want to see is how we can implement our own services. Let us explore this by showing how it is done in Java, WebAS, and Microsoft.NET. There are basically two different approaches to outline here. In both cases, our goal will be to create an XML result page. One option is to create the page by defining a template page that outlines the structure of the response document and by generating some code that evaluates the response data. The alternative is to set up a program that is called directly by the URL through an interface shim and returns the resulting data stream. Such a program is known as a servlet. The way that servlets are called and parameters are passed to them is derived from the old CGI standard, which allowed for the calling of executable programs from a Web server. While the concept of server pages, with its predefined templates, is nearly identical for all Web servers, the servlet concept differs in some essential ways, which we'll explore shortly. Web Services Through a BSP Let us start by taking the example of a Business Server Page (BSP) from the previous article I wrote on WebAS, and manipulate it to return an XML document instead of an HTML page. In the previous article, we defined a BSP that calls the BAPI to return the actual currency exchange rates as they are stored in the SAP system. The result was inserted within HTML tags to display an HTML table. Copyright © 2003 by Klee Associates, Inc. www.SAPtips.com Page 14 How to Develop Web Services in WebASPart 2: Design your own Web services with ABAP HTTP Extensions We’ll now vary this example by inserting some useful XML tags to represent a proper request response (see Figure 11). The format of the resulting XML document is taken from the template defined in the interface repository http://ifr.sap.com. As another variation, we could also enhance the template from the IFR and easily construct a SOAP document, which differs only in some named tags. We'll do this later in this paper. <%@page language="abap"%> <% DATA: exch_rate_list type bapi1093_0. DATA: DATA: DATA: DATA: tfrom_curr_range TYPE STANDARD TABLE OF bapi1093_3. tto_currncy_range TYPE STANDARD TABLE OF bapi1093_4. texch_rate_list TYPE STANDARD TABLE OF bapi1093_0. treturn TYPE STANDARD TABLE OF bapiret1. CALL FUNCTION 'BAPI_EXCHRATE_GETCURRENTRATES' DESTINATION 'NONE' EXPORTING date = sy-datum TABLES from_curr_range = tfrom_curr_range to_currncy_range = tto_currncy_range exch_rate_list = texch_rate_list return = treturn. %> <doc:ExchangeRate.GetCurrentRates.Response xmlns:doc="urn:sapcom:document:sap:business"> <!--List of Exchange Rates per Exch.Rate Type and Date--> <ExchRateList> <!--Export: List of exchange rates--> <% LOOP AT texch_rate_list into exch_rate_list. %> <item> <!--BAPI exchange rate table--> <FROM_CURR><!--From currency--><!--CUKY--> <%= exch_rate_list-from_curr %> </FROM_CURR> <TO_CURRNCY><!--To-currency--><!--CUKY--> <%= exch_rate_list-to_currncy %> </TO_CURRNCY> <VALID_FROM><!--Date from Which Entry Is Valid--><!--DATS--> <%= exch_rate_list-valid_from %> </VALID_FROM> <EXCH_RATE><!--Direct Quoted Exchange Rate--><!--DEC 9.5--> <%= exch_rate_list-exch_rate %> </EXCH_RATE> </item> <% ENDLOOP. %> </ExchRateList> </doc:ExchangeRate.GetCurrentRates.Response> Figure 11: XML Service Defined Through a BSP Copyright © 2003 by Klee Associates, Inc. www.SAPtips.com Page 15 How to Develop Web Services in WebASPart 2: Design your own Web services with ABAP HTTP Extensions Passing Parameters to the Web Service The previous example shown in Figure 11 is missing an important feature, the passing of parameters to the Web service. While ASP.NET or Java servlets resolve the parameters immediately into the request object, they are accessed through header variables in WebAS. Because this feature is poorly documented in the current WebAS release, we demonstrate their use in Figure 12. Copyright © 2003 by Klee Associates, Inc. www.SAPtips.com Page 16 How to Develop Web Services in WebASPart 2: Design your own Web services with ABAP HTTP Extensions <%@page language="abap"%> <html> <head> <link rel="stylesheet" href="../../sap/public/bc/bsp/styles/sapbsp.css"> <title>Simulation of AMAZON Web Services through BSP</title> <% DATA: BEGIN OF parm, name TYPE string, value TYPE string, rc TYPE i, END OF parm. DATA: querystring TYPE string. DATA: request_uri TYPE string. DATA: query TYPE REF TO cl_swlwp_uri. DATA: xml TYPE string. DATA: tfields TYPE tihttpnvp, field TYPE LINE OF tihttpnvp. **** Here we read all information pairs of the HTTP request ******** CALL METHOD request->get_header_fields CHANGING fields = tfields. **** This one reads the query_string explicitely ******** CALL METHOD request->get_header_field EXPORTING name = '~query_string' RECEIVING value = querystring. *********** URI Helper Class ************************************** * Initialize the helper class to better deal with query strings URI * need a dummy prefix to make the class work properly CONCATENATE 'dummy?' querystring INTO querystring. CALL METHOD cl_swlwp_uri=>create_from_string EXPORTING im_string = querystring IMPORTING ex_uri = query. *********** parm-name = CALL METHOD EXPORTING IMPORTING Extract a single parameter **************** 'ASIN'. query->get_query_parameter im_name = parm-name ex_value = parm-value. **** Here we better call a function module to do our service. * CALL FUNCTION 'Z_AXX_XML_BOOKSTORE' * EXPORTING querystring = querystring * IMPORTING XML = XML. ******************************************************* %> </head> <body class="bspBody1"> <H1>Simulation of AMAZON Web Services through BSP</H1> <HR>QueryString: <% = querystring %> <br>PARAM: Name=<% = parm-name %> Value=<% = parm-value %> RC= <% = parm-rc %> <HR><table> <% LOOP AT tfields INTO field. %> Copyright © 2003 by Klee Associates, Inc. www.SAPtips.com Page 17 How to Develop Web Services in WebASPart 2: Design your own Web services with ABAP HTTP Extensions <tr><td><% = field-name %></td><td><% = field-value %></td></tr> <% ENDLOOP. %> </table> </body></html> Figure 12: Catching the Query String Parameters to Simulate the Amazon Service In Figure 13 we show the way to simulate the Amazon.com article number search. The example returns an XML data stream in the way it is done by Amazon.com. Since there is no bookstore available in the WebAS basic version, we simply echo the received parameters in the result string, assuming that this is sufficient guidance to add the necessary code to return the desired result data in the resulting XML stream. <%@page language="abap"%> <% ... Same as in previous example %> <?xml version="1.0" encoding="UTF-8"?> <ProductInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <QueryString> <% = querystring %> </QueryString> <PARAM><NAME><% = parm-name %> </NAME><VALUE><% = parm-value %></VALUE></PARAM> <return> <% LOOP AT tfields INTO field. %> <Details> <Name><% = field-name %></Name> <Value><% = field-value %></Value> </Details> <% ENDLOOP. %> </return> </ProductInfo> Figure 13: Returning the Query String Data as XML Stream in the Amazon Fashion WebAS Servlets Through HTTP Extensions The previous WebAS examples returned the both HTML and XML result through a Business Server Page. Another way to produce the result string from the WebAS is through the use of the HTTP extensions, which we will call WebAS servlets, as they use an approach similar to the Java servlets. While Java servlets extend the base class javax.servlet.*, the WebAS extends3 the ABAP class IF_HTTP_EXTENSION (the prefix IF stands for interface). Extending the class is also known as inheriting the class. In the case of Web services, the newly developed class inherits the IF_HTTP_EXTENSION and overwrites one distinct method: HANDLE_REQUEST (). The request handler itself can access the HTTP objects through a 3 Extending a class is also known as inheriting a class, depending on which terminology of object oriented programming is used Copyright © 2003 by Klee Associates, Inc. www.SAPtips.com Page 18 How to Develop Web Services in WebASPart 2: Design your own Web services with ABAP HTTP Extensions series of helper classes, e.g., IF_HTTP_RESPONSE and IF_HTTP_REQUEST, which are inherited via the parent class IF_HTTP_EXTENSION. As a simple first example, for an HTTP service we shall inspect the predefined class CL_HTTP_EXT_PING, which can be reviewed with the class builder (SE24). The class has been mapped with transaction SICF to the service name pingservice. Hence, with an up and running WebAS, you could call the service by entering a URL like the one below in your browser, where ”linux:8080” is the HTTP address of the WebAS. http://linux:8080/pingservice Figure 14: Sample URL to Call a Web Service of the WebAS Request Handling with Method IF_HTTP_EXTENSION~HANDLE_REQUEST When the HTTP service request is received by the WebAS, it calls the method HANDLE_REQUEST() of the named class. In our example, pingservice is the public name that has been assigned to the implementing class in transaction SICF. The implementing class should be an extension of the default handler class IF_HTTP_EXTENSION, and it should implement a method with the fixed name HANDLE_REQUEST(). The IF_HTTP_EXTENSION class implements all important methods and attributes that are needed for handling the response and request parts of an HTTP communication. See Figure 15. method IF_HTTP_EXTENSION~HANDLE_REQUEST. data: result type string. server->response->set_header_field( name = 'Content-Type' value = 'text/html' ). result = '<html><body>'(001) & 'Connection to server successful'(101) & 'SystemID: &SYSID&'(102) & '</body></html'(999). replace '&SYSID&' with sy-sysid into result. server->response->set_cdata( data = result ). endmethod. Figure 15: Sample Implementation of a Pingservice Class Within the HANDLE_REQUEST method, an arbitrary ABAP Object code can be executed. Finally, the response object must be furnished with the response data, according to the requirements of the requesting HTTP client. In the pingservice example, we assume that the request expects a simple standard HTML response. So the response header is set with the method Copyright © 2003 by Klee Associates, Inc. www.SAPtips.com Page 19 How to Develop Web Services in WebASPart 2: Design your own Web services with ABAP HTTP Extensions server->response->set_header_field accordingly to text/html and the result data block is set to the response data with method server->response->set_cdata( data = ) . In addition to returning the data, we need to set the HTTP header information, which is sometimes mandatory and sometimes only useful. Typically, the header would at least provide information about the content of the document data that is sent in the document body. In our case, we tell the receiver of the document that the body contains HTML data. The valid content descriptors are defined by the W3C MIME recommendation. server->response->set_header_field( name = 'Content-Type' value = 'text/html' ). As a next step, we build the result string, which actually can be an arbitrary text. As a best practice rule, you would insert a call to a function module that returns the final result data string. This is “best practice” because it reduces the amount of code within an interface handler to a minimum. Doing so, the request handler is used as a wrapper for the application and as a jumping board to call the actual processing only: result = '<html><body>'(001) & 'Connection to server successful'(101) & 'SystemID: &SYSID&'(102) & '</body></html'(999). replace '&SYSID&' with sy-sysid into result. Finally, the result is assigned to the HTTP body with the set_cdata method. server->response->set_cdata( data = result ). Web Services Through Java Servlets With the upcoming hype for Java J2EE support as part of the WebAS starting with release 6.2, you might be interested to see how the same code looks when it is written in Java. In Java, a program that can be called via HTTP is called a servlet. When a servlet is written, it is deployed in a formal structure called the servlet container. Basically, the program in Java looks the same as in ABAP. Again, there is a formal base class that carries the HTTP extensions. This class is inherited by any servlet class that you develop and deploy. Other than in Java, the servlet does not work on top of a general request handler, but the servlet container explicitly calls some methods that match the name of the HTTP request. For every HTTP command, such as GET or POST, there has to be a method implemented whose name is built by prefixing the HTTP command with “do” as follows: • doXxx(), where Xxx is to be replaced by the name of the handled HTTP command, e.g., doGet for HTTP Get and doPost for HTTP Post. A calling Web client may expect that a servlet handles at least the basic HTTP commands Get and Post, so consequently a servlet must support and implement the standard methods: • doGet() • doPost() Copyright © 2003 by Klee Associates, Inc. www.SAPtips.com Page 20 How to Develop Web Services in WebASPart 2: Design your own Web services with ABAP HTTP Extensions Every method will be called exclusively from the matching context, and the response of each method is a string that is returned in the body of HTTP response. Before we can use the servlet, the servlet class must be deployed in the Web server’s servlet container. When this is successfully done, it can be called via an HTTP Get or HTTP Post request by specifying nothing more than the class name in the URL. If the class requires parameter information, it can be appended to the URL separated by a question mark (?) to build a canonical URI, which we are already familiar with. See Figure 16. public class HelloJSP { public static void doGet(String[] args) { System.out.println("<html><body>Hello World from JSP</body></html>"); } public static void main(String[] args) { System.out.println("<html><body>Welcome to Hello World for JSP</body></html>"); } } Figure 16: Implementation of Servlet Class HelloWorldExample in Java SAP XML and SOAP Utilities SAP also provides for a number of helper classes to allow for easier (I don't dare say easy) creation of the resulting XML documents, e.g., creating a proper SOAP response document. In Figure 17, there is an example that is also found in a similar fashion in the demo section of the WebAS, and is called the “info service.” The example may look cryptic at the first glance. The key thing to understand is that the method soapdoc->add_parameter converts the given ABAP data structure into a SOAP-compliant XML sub tree. Copyright © 2003 by Klee Associates, Inc. www.SAPtips.com Page 21 How to Develop Web Services in WebASPart 2: Design your own Web services with ABAP HTTP Extensions method if_http_extension~handle_request. * parameters: * [in] if_http_server& server * Call through browser: http://linux:8080/sap/public/info data: data: data: data: data: data: data: data: data: l_rfcsi type rfcsi. soapdoc type ref to CSoapDocument. isoapdoc type ref to ISoapSerialize. exUsage type ref to CSoapExceptionUsage. exResrc type ref to CSoapExceptionResource. exIntrn type ref to CSoapExceptionInternal. dref type ref to data. xdata type xstring. data type string. call function 'RFC_SYSTEM_INFO' importing rfcsi_export = l_rfcsi. clear xdata. create object soapdoc. if not soapdoc is initial. try. call method soapdoc->set_method exporting name = 'RFC_SYSTEM_INFO.Response' nsprefix = 'rfc' nsvalue = CSoapConstants=>sc_rfc_function_ns. get reference of l_rfcsi into dref. call method soapdoc->add_parameter exporting name = 'RFCSI' value = dref direction = CSoapConstants=>ic_param_in. isoapdoc = soapdoc. call method isoapdoc->serialize changing document = xdata. * -- set header field call method server->response->set_header_field( name = 'Content-Type' "#EC NOTEXT value = 'text/xml' ). catch CSoapExceptionUsage into exUsage. "-- don't care clear xdata. catch CSoapExceptionResource into exResrc. clear xdata. catch CSoapExceptionInternal into exIntrn. clear xdata. endtry. endif. if xdata is initial. call method server->response->set_header_field( Copyright © 2003 by Klee Associates, Inc. www.SAPtips.com Page 22 How to Develop Web Services in WebASPart 2: Design your own Web services with ABAP HTTP Extensions name = 'Content-Type' "#EC NOTEXT value = 'text/html' ). * Bild an HTML framework to properly display it in a browser concatenate '<html>' '<body>' l_rfcsi '</body>' '</html>' into data. call method server->response->set_cdata( data = data ). else. call method server->response->set_data( data = xdata ). endif. endmethod. Figure 17: Producing a SOAP Document Out of a Function Call Result In my system, the resulting SOAP document looks as follows in Figure 18. If you look closer, you will find that the SOAP document is nearly identical with the template provided by the SAP interface repository, but with one small enhancement: the template is embraced by the SOAPENV envelope tags. Copyright © 2003 by Klee Associates, Inc. www.SAPtips.com Page 23 How to Develop Web Services in WebASPart 2: Design your own Web services with ABAP HTTP Extensions Figure 18: SOAP Document Produced with Aid of the SoapdocÆadd_parameter Method Do You Need WebAS or SAP Enterprise for Web Services? Calling SAP via RFC or via HTTP From what we have seen so far, it is certainly clear that there is no need to upgrade to WebAS or SAP Enterprise (4.7) for the sole purpose of integrating your SAP system with the Web. If you want to give your HTTP-based SAP clients real-time access to all the wealth of data inside of SAP, you can use any modern Web server, and access your SAP ERP system via RFC calls from Java or Windows DCOM calls. Realistically, if you designed a solution that delivered information from your ERP system to an Internet requester, you would not even think of plugging in your Internet connection directly to your SAP box, for the simple reason of security. Exposing your ERP system directly to the Internet would be like depositing the safe with the Queen’s crown jewels in the garden of Buckingham palace. Copyright © 2003 by Klee Associates, Inc. www.SAPtips.com Page 24 How to Develop Web Services in WebASPart 2: Design your own Web services with ABAP HTTP Extensions However, there are other arguments for upgrading your SAP ERP system to SAP Enterprise 4.7: • SAP Enterprise will allow you to easily design browser access to SAP for Intranet solutions. These solutions are becoming more and more popular, because they don't involve deploying SAPGUI on every workstation. • Secondly, having SAP function like any HTTP server, as it does in SAP Enterprise, allows a smoother communication with other internal TCP/IP applications, including your own Internet Web server. Smooth HTTP interaction can provoke a nominal return of investment when you have a complex heterogeneous server landscape. Whereas having RFC access means deploying the necessary drivers on the client computer, calling dedicated libraries, and being dependent on SAP-provided utilities and documentation during development, the use of WebAS allows you to access your SAP ERP system in the same manner and use the same utilities as you would to access any other online location or Web server. Although programming RFC access is relatively easy, and it's available for most common operating platforms (including Windows, Java on Windows, Linux, and UNIX), deploying an RFC application requires that the client computer has the necessary RFC drivers installed. Installing drivers on a productive machine is always critical. You have to consider: • deployment and registering of the drivers • rebooting the box after installation • allowing for the proper security mechanisms • hat testing your application may interfere with existing applications and even bring them down. When you decide to activate HTTP communication with SAP, you will benefit from the alreadyinstalled TCP/IP tools that are universally installed on every modern computer from mainframes down to pervasive palm-top clients. This allows access to SAP from every computer within reach of your network, without any special preparation of the client. Another benefit of SAP HTTP: your development and deployment team will also avoid endless discussions with the Basis and security administration team. Every proprietary standard used in your server landscape will likely explode your training and planning costs. What may look like an easy five-minute task to your development team suddenly turns out to become an elaborate ceremony requiring weeks of planning. Once your SAP talks HTTP, it is only up to whoever is handling the firewall to open or deny the access to your SAP ERP system. This takes the discussion away from technical complexities and allows for a more strategic focus. So, based on the strengths of the WebAS and Enterprise 4.7, what is my final assessment in terms of the best approach to Web services? My current recommendation, as of this writing, is that WebAS and Enterprise 4.7 is the ideal platform for SAP Web services, for all the reasons I've outlined in this paper. But, keep in mind, that specifically when submitting a SOAP request to the SAP system, I recommend continuing to use SAP HTTP and RFC, not the HTTP classes of WebAS, until the HTTP classes and ABAP/Objects technologies mature. Even if you're running on WebAS, you can still continue to use SAP HTTP and traditional RFC methods. And, best of all, you do not need to be running WebAS or 4.7 to start using Web services in your application environment. Copyright © 2003 by Klee Associates, Inc. www.SAPtips.com Page 25 How to Develop Web Services in WebASPart 2: Design your own Web services with ABAP HTTP Extensions SAP As the Universal Development Platform It is already pretty obvious that SAP, with the addition of HTTP service to its kernel, has matured into one of the leading competitors in the enterprise application server market. From now on, we will have to clearly distinguish between the SAP ERP suite—which is a class of its own anyway— and the SAP kernel technology, currently marketed as the NetWeaver WebAS. Thanks to the strong transaction management, the database integration, the fully integrated development workbench, and sophisticated change and deployment management, SAP WebAS has already become a serious contender to the established virtual machine frameworks for enterprise application servers. In the next white paper, I shall assess the strengths and weaknesses of the three major development and runtime environments, namely WebSphere J2EE, Microsoft.NET, and SAP WebAS, and explain why the “Clash of the Frameworks” will end in favor of the newcomer SAP WebAS and ABAP—at least for SAP users. Copyright © 2003 by Klee Associates, Inc. www.SAPtips.com Page 26 How to Develop Web Services in WebASPart 2: Design your own Web services with ABAP HTTP Extensions Axel Angeli is a senior SAP and EAI advisor and principal of logosworld.com, a Germanbased enterprise specializing in coaching SAP and EAI project teams and advising IT management on implementation issues. Axel has been in the IT business since 1984, and throughout his career, he has always worked with cutting edge technologies. Axel's SAP experience stems back from the good old R/2 days and he is an expert on SAP’s NetWeaver technology and any kind of ABAP development. A speaker of several languages, Axel specializes in coaching and leading large multi-national teams on complex projects with heterogeneous platforms and international rollouts. Known for his intensive and successful trouble-shooting experience, Axel has been nicknamed by his colleagues as the “Red Adair” of SAP projects. He is the author of the best-selling tutorial “The SAP R/3 Guide to EDI, IDocs, ALE and Interfaces.” The information in our publications and on our Website is the copyrighted work of Klee Associates, Inc. and is owned by Klee Associates, Inc. NO WARRANTY: This documentation is delivered as is, and Klee Associates, Inc. makes no warranty as to its accuracy or use. Any use of this documentation is at the risk of the user. Although we make every good faith effort to ensure accuracy, this document may include technical or other inaccuracies or typographical errors. Klee Associates, Inc. reserves the right to make changes without prior notice. NO AFFILIATION: Klee Associates, Inc. and this publication are not affiliated with or endorsed by SAP AG. SAP AG software referenced on this site is furnished under license agreements between SAP AG and its customers and can be used only within the terms of such agreements. SAP AG and mySAP are registered trademarks of SAP AG. All other company and product names used herein may be trademarks or registered trademarks of their respective owners. Copyright © 2003 by Klee Associates, Inc. www.SAPtips.com Page 27
© Copyright 2024