Android+ +How+to+Guide

Published on January 2017 | Categories: Documents | Downloads: 98 | Comments: 0 | Views: 599
of 31
Download PDF   Embed   Report

Comments

Content

Consuming SAP NetWeaver Gateway Services from Android Applications

Copyright
© Copyright 2011 SAP AG. All rights reserved. SAP Library document classification: PUBLIC No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP AG. The information contained herein may be changed without prior notice. Some software products marketed by SAP AG and its distributors contain proprietary software components of other software vendors. Microsoft, Windows, Excel, Outlook, and PowerPoint are registered trademarks of Microsoft Corporation. IBM, DB2, DB2 Universal Database, System i, System i5, System p, System p5, System x, System z, System z10, System z9, z10, z9, iSeries, pSeries, xSeries, zSeries, eServer, z/VM, z/OS, i5/OS, S/390, OS/390, OS/400, AS/400, S/390 Parallel Enterprise Server, PowerVM, Power Architecture, POWER6+, POWER6, POWER5+, POWER5, POWER, OpenPower, PowerPC, BatchPipes, BladeCenter, System Storage, GPFS, HACMP, RETAIN, DB2 Connect, RACF, Redbooks, OS/2, Parallel Sysplex, MVS/ESA, AIX, Intelligent Miner, WebSphere, Netfinity, Tivoli and Informix are trademarks or registered trademarks of IBM Corporation. Linux is the registered trademark of Linus Torvalds in the U.S. and other countries. Adobe, the Adobe logo, Acrobat, PostScript, and Reader are either trademarks or registered trademarks of Adobe Systems Incorporated in the United States and/or other countries. Oracle is a registered trademark of Oracle Corporation. UNIX, X/Open, OSF/1, and Motif are registered trademarks of the Open Group. Citrix, ICA, Program Neighborhood, MetaFrame, WinFrame, VideoFrame, and MultiWin are trademarks or registered trademarks of Citrix Systems, Inc. HTML, XML, XHTML and W3C are trademarks or registered trademarks of W3C®, World Wide Web Consortium, Massachusetts Institute of Technology. Java is a registered trademark of Sun Microsystems, Inc. JavaScript is a registered trademark of Sun Microsystems, Inc., used under license for technology invented and implemented by Netscape. SAP, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP BusinessObjects Explorer, StreamWork, and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of SAP AG in Germany and other countries. Business Objects and the Business Objects logo, BusinessObjects, Crystal Reports, Crystal Decisions, Web Intelligence, Xcelsius, and other Business Objects products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of Business Objects Software Ltd. Business Objects is an SAP company. Sybase and Adaptive Server, iAnywhere, Sybase 365, SQL Anywhere, and other Sybase products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of Sybase, Inc. Sybase is an SAP company. All other product and service names mentioned are the trademarks of their respective companies. Data contained in this document serves informational purposes only. National product specifications may vary. These materials are subject to change without notice. These materials are provided by SAP AG and its affiliated companies ("SAP Group") for informational purposes only, without representation or warranty of any kind, and SAP Group shall not be liable for errors or omissions with respect to the materials. The only warranties for SAP Group products and services are those that are set forth in the express warranty statements accompanying such products and services, if any. Nothing herein should be construed as constituting an additional warranty.

Copyright/Trademark

Table of Contents
Consuming SAP NetWeaver Gateway Services from Android Applications ............................. 4 Prerequisites ............................................................................................................................................. 5 Building an Android Application ............................................................................................................. 6 Function Import Example .................................................................................................................... 6 Read Example .................................................................................................................................... 10 Create Example .................................................................................................................................. 12 Creation of Request Body for Create Method ................................................................................ 14 Authentication Using X.509 Certificate ............................................................................................... 15 Prerequisites ....................................................................................................................................... 15 Android Project Configuration .......................................................................................................... 16 Read Example using X.509 .............................................................................................................. 16 Appendix 1 - RMTSAMPLEFLIGHT Service Metadata Description ............................................ 18 Appendix 2 – Code Snippets .......................................................................................................... 24 Read - Get Carrier by Carrier ID .......................................................................................................... 24 Function Import ....................................................................................................................................... 26 Create - Booking a Flight ...................................................................................................................... 28 Appendix 3 – Code Snippets using x.509 ..................................................................................... 30

Copyright/Trademark

CONSUMING SAP NETWEAVER GATEWAY SERVICES FROM ANDROID APPLICATIONS
SAP NetWeaver Gateway technology provides a simple way to interact with SAP applications through variety of devices, environments and platforms based on market standards. The framework enables development of innovative, people-centric solutions that bring the power of SAP business software into new experiences, such as: social networking and collaboration environments; mobile and tablet devices; and rich internet applications. The framework supports rapid innovation while ensuring security, integrity, management and optimized maintenance of the core SAP systems. Completely flexible, the software offers connectivity to SAP applications using any programming language or model without the need for SAP knowledge by taking advantage of REST services and OData/ATOM protocols. This guide provides information on how to consume SAP NetWeaver Gateway services from Android applications based on the following scenario:  The user wants to fly from New York to San Francisco.  He goes online and searches for the different flights available. He enters his search parameters: city of origin, destination city, departure date, and arrival date (Function Import).  From the SAP NetWeaver Gateway, he receives the information for the option(s) that meet(s) his search parameters (Get Function).  He can now select the one that suits him the most and book his flight (Create Function). The links to access the service document and metadata document are provided the in table below.
Service Document Metadata Document

http://<Gateway_host>:<Gateway_port>/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/ http://<Gateway_host>:< Gateway_port>/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/ $metadata?$format=xml

Each service URL should contain the following information:  Gateway host  Port  SAP Client – no need to specify client if connecting to the default client. Example:
http://<Gateway_Host>:<Gateway_Port>/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT?sap-client=100

To obtain information on the selected service (its properties, function imports, associations, etc.), refer to Appendix 1, were we show the Metadata description of the RMTSAMPLEFLIGHT service. To view the code snippets in a format that can be copied into new code, refer to Appendix 2 – Code Snippets.

Copyright/Trademark

The Flight service contains the following collections:
Collection URL

FlightCollection (list of flights) CarrierCollection (list of carriers BookingsCollection (list of Bookings)

http://<Gateway_host>:<Gateway_port >/sap/opu/sdata/ iwfnd/RMTSAMPLEFLIGHT/FlightCollection http://<Gateway_host>:<Gateway_port >/ sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/CarrierCollection http://<Gateway_host>:<Gateway_port>/sap/opu/sdata/ iwfnd/RMTSAMPLEFLIGHT/BookingCollection

The operation GetAvailableFlights on FlightCollection is used to get a list of flights. The following is the URL for the same: http://<Gateway_host>:<Gateway_port>/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/GetAvailableFlights? Each collection supports some or all of the operations listed below. The table below provides the list of operations supported and the methods that each of this operations map to respectively:
Operation Method

Create Read Update Delete

HTTP POST GET PUT DELETE

Prerequisites
The following tools are required for developing an Android application:
Software Version

SAP NetWeaver Gateway Eclipse OS

2.0 3.6 Android 2.1

Contact your system administrator for landscape details to connect to the SAP NetWeaver Gateway system.

Copyright/Trademark

Building an Android Application
Function Import Example To get a list of the available flights, based on filter criteria, triggerthe “GetAvailableFlights” function import with cityFrom, cityTo, fromDate and toDate parameters. The response will contain a list of flights that meet the criteria. Note: For more information on Function Import (also called Service Operation), refer to OData documentation at http://www.odata.org/developers/protocols/uri-conventions under the Addressing Service Operations section. Refer to the code snippet below for details on how to do it from an Android application: 1. Use the following method for executing a Function Import that returns a collection of flights.
/** * * @param cityFrom * @param cityTo * @param date * @return available flights * @throws URISyntaxException * @throws ClientProtocolException * @throws IOException */ public String getFlightList(String cityFrom, String cityTo, String fromDate, String toDate) throws URISyntaxException, ClientProtocolException, IOException {

2. Create the request URL that will be sent.
String requestUrl = http://<Gateway_Host>:<Gateway_Port>/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/GetAvailableFligh ts?cityfrom= + cityFrom + "&cityto=" + cityTo + "&fromdate=" + fromDate + "&todate=" + toDate;

3. Define HTTP client.
DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("<Gateway_User>", "<Gateway_Password>"));

4. Create a Get request.
HttpGet getRequest = new HttpGet(); // buffer reader to read the response BufferedReader bufferedReader = null; // placeholder for the service response HttpResponse response = null; getRequest.setURI(new URI(requestUrl)); getRequest.setHeader("Content-Type", "text/xml"); getRequest.setHeader("Host", getRequest.getURI().getHost());

5. Execute the request.
response = client.execute(getRequest);

Copyright/Trademark

bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer stringBuffer = new StringBuffer(""); String line = ""; try { while ((line = bufferedReader.readLine()) != null) { stringBuffer.append(line); } bufferedReader.close(); } catch (IOException e) { Log.e("IO exception", e.toString()); } // XML response, needs to be parsed as described below. return stringBuffer.toString(); }

To parse the properties for each entry from the feed follow the example below:
public void parsePropertiesFromFeed(String xml) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); String propertyValue = null; String propertyName = null; try { DocumentBuilder builder = factory.newDocumentBuilder(); Document dom = builder.parse(new ByteArrayInputStream(xml.getBytes())); Element root = dom.getDocumentElement(); NodeList entries = root.getElementsByTagName("atom:entry"); // iterate over entries for (int i = 0; i < entries.getLength(); i++) { Toast.makeText(getApplicationContext(), "entry number: " + i, Toast.LENGTH_SHORT).show(); Node atomContentNode = entries.item(i).getChildNodes().item(1); If (atomContentNode.getNodeName().equalsIgnoreCase("atom:content")) { Node mpropertiesNode = atomContentNode.getChildNodes().item(0); if (mpropertiesNode.getNodeName().equalsIgnoreCase("m:properties")) { NodeList mpropertiesList = mpropertiesNode.getChildNodes(); // iterate over entry properties for (int j = 0; j < mpropertiesList.getLength(); j++) { propertyName = mpropertiesList.item(j).getNodeName(); propertyValue = mpropertiesList.item(j).getFirstChild().getNodeValue( ); Toast.makeText(getApplicationContext(), propertyName + ": " + propertyValue, Toast.LENGTH_SHORT).show(); } }

Copyright/Trademark

} } } catch (Exception e) { throw new RuntimeException(e.getMessage()); } }

Response
<?xml version="1.0" encoding="utf-8" ?> - <atom:feed xml:base="<Gateway_Host>:<Gateway_Port>/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:sap="http://www.sap.com/Protocols/SAPData"> <atom:id>http://<host name>:<port>/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/FlightCollection</atom:id> <atom:link href="FlightCollection" rel="self" type="application/atom+xml;type=feed" title="FlightCollection" /> <atom:title>FlightCollection</atom:title> <atom:updated>2011-09-27T06:32:42Z</atom:updated> - <atom:entry> <atom:author /> - <atom:content type="application/xml"> - <m:properties> <d:carrid>AA</d:carrid> <d:connid>0017</d:connid> <d:fldate m:Type="Edm.DateTime">2011-01-05T00:00:00</d:fldate> <d:PRICE m:Type="Edm.Decimal">889.00</d:PRICE> <d:CURRENCY>USD</d:CURRENCY> <d:PLANETYPE>747-400</d:PLANETYPE> <d:SEATSMAX>385</d:SEATSMAX> <d:SEATSOCC>367</d:SEATSOCC> <d:PAYMENTSUM m:Type="Edm.Decimal">185742.73</d:PAYMENTSUM> <d:SEATSMAX_B>31</d:SEATSMAX_B> <d:SEATSOCC_B>22</d:SEATSOCC_B> <d:SEATSMAX_F>21</d:SEATSMAX_F> <d:SEATSOCC_F>21</d:SEATSOCC_F> - <d:flightDetails> <d:countryFrom>US</d:countryFrom> <d:cityFrom>new york</d:cityFrom> <d:airportFrom>JFK</d:airportFrom> <d:countryTo>US</d:countryTo> <d:cityTo>SAN FRANCISCO</d:cityTo> <d:airportTo>SFO</d:airportTo> <d:flightTime>361</d:flightTime> <d:departureTime m:Type="Edm.Time">PT11H00M00S</d:departureTime> <d:arrivalTime m:Type="Edm.Time">PT14H01M00S</d:arrivalTime> <d:distance m:Type="Edm.Decimal">2574.0000</d:distance> <d:distanceUnit>SMI</d:distanceUnit> <d:flightType /> <d:period m:Type="Edm.Byte">0</d:period> </d:flightDetails> </m:properties> </atom:content> <atom:id>http://<Gateway_Host>:<Gateway_Port>/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/FlightCollection(carrid='AA',conn id='0017',fldate='20110105')</atom:id> <atom:link href="FlightCollection(carrid='AA',connid='0017',fldate='20110105')" rel="edit" type="application/atom+xml;type=entry" /> <atom:link href="FlightCollection(carrid='AA',connid='0017',fldate='20110105')/flightbooking" rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/flightbooking" type="application/atom+xml;type=entry" title="RMTSAMPLEFLIGHT.BookingFlight" /> <atom:link href="FlightCollection(carrid='AA',connid='0017',fldate='20110105')/flightBookings" rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/flightBookings" type="application/atom+xml;type=feed" title="RMTSAMPLEFLIGHT.FlightBookings" /> <atom:link href="FlightCollection(carrid='AA',connid='0017',fldate='20110105')/FlightCarrier" rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/FlightCarrier" type="application/atom+xml;type=entry" title="RMTSAMPLEFLIGHT.CarrierToFlight" /> <atom:title>Flight</atom:title>

Copyright/Trademark

<atom:updated>2011-09-27T06:32:42Z</atom:updated> </atom:entry> - <atom:entry> <atom:author /> - <atom:content type="application/xml"> - <m:properties> <d:carrid>AA</d:carrid> <d:connid>0017</d:connid> <d:fldate m:Type="Edm.DateTime">2011-03-16T00:00:00</d:fldate> <d:PRICE m:Type="Edm.Decimal">422.94</d:PRICE> <d:CURRENCY>USD</d:CURRENCY> <d:PLANETYPE>747-400</d:PLANETYPE> <d:SEATSMAX>385</d:SEATSMAX> <d:SEATSOCC>371</d:SEATSOCC> <d:PAYMENTSUM m:Type="Edm.Decimal">192129.22</d:PAYMENTSUM> <d:SEATSMAX_B>31</d:SEATSMAX_B> <d:SEATSOCC_B>30</d:SEATSOCC_B> <d:SEATSMAX_F>21</d:SEATSMAX_F> <d:SEATSOCC_F>20</d:SEATSOCC_F> - <d:flightDetails> <d:countryFrom>US</d:countryFrom> <d:cityFrom>new york</d:cityFrom> <d:airportFrom>JFK</d:airportFrom> <d:countryTo>US</d:countryTo> <d:cityTo>SAN FRANCISCO</d:cityTo> <d:airportTo>SFO</d:airportTo> <d:flightTime>361</d:flightTime> <d:departureTime m:Type="Edm.Time">PT11H00M00S</d:departureTime> <d:arrivalTime m:Type="Edm.Time">PT14H01M00S</d:arrivalTime> <d:distance m:Type="Edm.Decimal">2574.0000</d:distance> <d:distanceUnit>SMI</d:distanceUnit> <d:flightType /> <d:period m:Type="Edm.Byte">0</d:period> </d:flightDetails> </m:properties> </atom:content> <atom:id>http://<Gateway_Host>:<Gateway_Port>/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/FlightCollection(carrid='AA',conn id='0017',fldate='20110316')</atom:id> <atom:link href="FlightCollection(carrid='AA',connid='0017',fldate='20110316')" rel="edit" type="application/atom+xml;type=entry" /> <atom:link href="FlightCollection(carrid='AA',connid='0017',fldate='20110316')/flightbooking" rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/flightbooking" type="application/atom+xml;type=entry" title="RMTSAMPLEFLIGHT.BookingFlight" /> <atom:link href="FlightCollection(carrid='AA',connid='0017',fldate='20110316')/flightBookings" rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/flightBookings" type="application/atom+xml;type=feed" title="RMTSAMPLEFLIGHT.FlightBookings" /> <atom:link href="FlightCollection(carrid='AA',connid='0017',fldate='20110316')/FlightCarrier" rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/FlightCarrier" type="application/atom+xml;type=entry" title="RMTSAMPLEFLIGHT.CarrierToFlight" /> <atom:title>Flight</atom:title> <atom:updated>2011-09-27T06:32:42Z</atom:updated> </atom:entry>

Copyright/Trademark

Read Example To read the carrier details, you must call the “CarrierCollection” using the Carrier ID parameter. Refer to the code snippet below for details on how to do it from an Android application: 1. Create a “Get Specific” carrier query using the method below, the result returned in the response is a Carrier XML entry.
/** * Method for getting Carrier information by its carrierId * @param carrid the carrier id to search for, e.g. LH * @return Carrier xml entry * @throws URISyntaxException * @throws ClientProtocolException * @throws IOException */ public String getCarrier(String carrid) throws URISyntaxException, ClientProtocolException, IOException {

2. Create the request URL that will be sent.
String requestUrl = http://<Gateway_Host>:<Gateway_Port>/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/CarrierCollection (carrid=' + carrid + "')";

3. Define HTTP client.
DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("<Gateway_User>", "<Gateway_Password>"));

4. Create a Get request.
HttpGet getRequest = new HttpGet(); // buffer reader to read the response BufferedReader bufferedReader = null; // placeholder for the service response HttpResponse response = null; getRequest.setURI(new URI(requestUrl)); getRequest.setHeader("Content-Type", "text/xml"); getRequest.setHeader("Host", getRequest.getURI().getHost());

5. Execute the request.
response = client.execute(getRequest); bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer stringBuffer = new StringBuffer(""); String line = ""; try { while ((line = bufferedReader.readLine()) != null) { stringBuffer.append(line); } bufferedReader.close(); }

Copyright/Trademark

catch (IOException e) { Log.e("IO exception", e.toString()); } // XML response, needs to be parsed as described below. return stringBuffer.toString(); }

To parse the properties from the entry xml, follow the example below:
public void parsePropertiesFromEntry(String xml) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); String propertyValue = null; String propertyName = null; try { DocumentBuilder builder = factory.newDocumentBuilder(); Document dom = builder.parse(new ByteArrayInputStream(xml.getBytes())); Element root = dom.getDocumentElement(); NodeList properties = root.getElementsByTagName("m:properties").item(0).getChildNodes(); // iterate over the entry properties for (int i = 0; i < properties.getLength(); i++) { propertyName = properties.item(i).getNodeName(); propertyValue = properties.item(i).getFirstChild().getNodeValue(); Toast.makeText(getApplicationContext(), propertyName + ": " + propertyValue, Toast.LENGTH_SHORT).show(); } } catch (Exception e) { throw new RuntimeException(e.getMessage()); } }

Response
<?xml version="1.0" encoding="utf-8" ?> - <atom:entry xml:base="<Gateway_Host>:<Gateway_Port>/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:sap="http://www.sap.com/Protocols/SAPData"> <atom:author /> <atom:content src="http://www.aa.com" /> - <m:properties> <d:carrid>AA</d:carrid> <d:CARRNAME>American Airlines</d:CARRNAME> <d:CURRCODE>USD</d:CURRCODE> <d:URL>http://www.aa.com</d:URL> <d:mimeType /> </m:properties> <atom:id><Gateway_Host>:<Gateway_Port>/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/CarrierCollection(carrid='AA')</atom:i d> <atom:link href="CarrierCollection(carrid='AA')" rel="self" type="application/atom+xml;type=entry" /> <atom:link href="CarrierCollection(carrid='AA')/carrierFlights" rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/carrierFlights" type="application/atom+xml;type=feed" title="RMTSAMPLEFLIGHT.CarrierToFlight" /> <atom:title>Carrier</atom:title> <atom:updated>2011-09-27T10:00:38Z</atom:updated> </atom:entry>

Copyright/Trademark

Create Example To book a flight, trigger the HTTP POST method on the Booking Collection (with the Booking details in the request body). Check for the HTTP response code. If the response code is 201, then the HTTP-POST is successful. The response contains the newly created Booking ID in the bookid field, as well as the entire information that was part of the request body. Refer to the code snippet below for details on how to invoke a create request from an Android application: 1. Prepare a new Booking entry by creating an entry payload.
String content = "<atom:entry xml:base=" + "'http://<Gateway_Host>:<Gateway_Port>/sap/opu/sdata/IWFND/RMTSAMPLEFLIGHT/' " + "xmlns:atom='http://www.w3.org/2005/Atom' " + "xmlns:d='http://schemas.microsoft.com/ado/2007/08/dataservices' " + "xmlns:m='http://schemas.microsoft.com/ado/2007/08/dataservices/metadata' " + "xmlns:sap='http://www.sap.com/Protocols/SAPData'>" + "<atom:content type='application/xml'><m:properties>" + "<d:carrid>AA</d:carrid>" + "<d:connid>0017</d:connid>" + "<d:fldate m:Type='Edm.DateTime'>2011-07-27T00:00:00</d:fldate>" + "<d:bookid></d:bookid>" + "<d:CUSTOMID>00004617</d:CUSTOMID>" + "<d:CUSTTYPE>P</d:CUSTTYPE>" + "<d:SMOKER/>" + "<d:WUNIT>KG</d:WUNIT>" + "<d:LUGGWEIGHT m:Type='Edm.Decimal'>14.4000</d:LUGGWEIGHT>" + "<d:INVOICE/><d:CLASS>Y</d:CLASS>" + "<d:FORCURAM m:Type='Edm.Decimal'>879.82</d:FORCURAM>" + "<d:FORCURKEY>USD</d:FORCURKEY>" + "<d:LOCCURAM m:Type='Edm.Decimal'>803.58</d:LOCCURAM>" + "<d:LOCCURKEY>USD</d:LOCCURKEY>" + "<d:ORDER_DATE m:Type='Edm.DateTime'>2011-05-22T00:00:00</d:ORDER_DATE>" + "<d:COUNTER>00000000</d:COUNTER>" + "<d:AGENCYNUM>00000325</d:AGENCYNUM>" + "<d:CANCELLED/><d:RESERVED/>" + "<d:PASSNAME>Joe Smith</d:PASSNAME>" + "<d:PASSFORM>1234567</d:PASSFORM>" + "<d:PASSBIRTH m:Type='Edm.DateTime' m:null='true'>1990-10-10</d:PASSBIRTH>" + "</m:properties></atom:content></atom:entry>"; /**

Copyright/Trademark

2.

Use the Method below to book a new flight.
* * @param content * @return * @throws IOException * @throws ClientProtocolException */ public String createBooking(String content) throws ClientProtocolException, IOException { DefaultHttpClient client; client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("<Gateway_User>", "<Gateway_Password>")); HttpPost post = new HttpPost( "http://<Gateway_Host>:<Gateway_Port>/sap/opu/sdata/IWFND/RMTSAMPLEFLIGHT/BookingCollection") ;

3. Add the following header to the Post requests:
post.addHeader("X-Requested-With", "XMLHttpRequest");

4. Add the request body.
StringEntity entity = new StringEntity(content); entity.setContentType(new BasicHeader("Content-Type", "application/atom+xml")); post.setEntity(entity);

5. Execute the request.
HttpResponse response; response = client.execute(post); if (response.getStatusLine().getStatusCode() != 201) { throw new RuntimeException(response.getStatusLine().getReasonPhrase()); } InputStream inputStream = response.getEntity().getContent(); // convert to String and return the response return convertInputStreamToString(inputStream); }

Copyright/Trademark

Creation of Request Body for Create Method The request body can be easily created by looking at the tags in the collection’s metadata. For example, the metadata for Booking Collection provides information about the various fields (tags) that are needed for creating a booking:
<Property Name="carrid" Type="Edm.String" Nullable="false" MaxLength="3" sap:label="Airline" sap:filterable="false"/> <Property Name="connid" Type="Edm.String" Nullable="false" MaxLength="4" sap:label="Flight Number" sap:filterable="false"/> <Property Name="fldate" Type="Edm.DateTime" Nullable="false" Precision="10" sap:label="Date" sap:filterable="false"/> <Property Name="bookid" Type="Edm.String" Nullable="false" MaxLength="8" sap:label="Booking number" sap:filterable="false"/> <Property Name="CUSTOMID" Type="Edm.String" MaxLength="8" sap:label="Customer Number" sap:filterable="false"/> <Property Name="CUSTTYPE" Type="Edm.String" MaxLength="1" sap:label="B/P customer" sap:filterable="false"/> <Property Name="SMOKER" Type="Edm.String" MaxLength="1" sap:label="Smoker" sap:filterable="false"/> <Property Name="WUNIT" Type="Edm.String" MaxLength="3" sap:label="Unit of measure" sap:filterable="false"/> <Property Name="LUGGWEIGHT" Type="Edm.Decimal" Precision="10" Scale="4" sap:label="Luggage Weight" sap:filterable="false" sap:unit="WUNIT"/> <Property Name="INVOICE" Type="Edm.String" MaxLength="1" sap:label="Invoice pty." sap:filterable="false"/> <Property Name="CLASS" Type="Edm.String" MaxLength="1" sap:label="Class" sap:filterable="false"/> <Property Name="FORCURAM" Type="Edm.Decimal" Precision="20" Scale="2" sap:label="Amount" sap:filterable="false"/> <Property Name="FORCURKEY" Type="Edm.String" MaxLength="5" sap:label="Paymnt currency" sap:filterable="false"/> <Property Name="LOCCURAM" Type="Edm.Decimal" Precision="20" Scale="2" sap:label="Amount" sap:filterable="false"/> <Property Name="LOCCURKEY" Type="Edm.String" MaxLength="5" sap:label="Airline Currency" sap:filterable="false"/> <Property Name="ORDER_DATE" Type="Edm.DateTime" Precision="10" sap:label="Booking date" sap:filterable="false"/> <Property Name="COUNTER" Type="Edm.String" MaxLength="8" sap:label="Sales office" sap:filterable="false"/> <Property Name="AGENCYNUM" Type="Edm.String" MaxLength="8" sap:label="Agency No." sap:filterable="false"/> <Property Name="CANCELLED" Type="Edm.String" MaxLength="1" sap:label="Cancelation flag" sap:filterable="false"/> <Property Name="RESERVED" Type="Edm.String" MaxLength="1" sap:label="Reserved" sap:filterable="false"/> <Property Name="PASSNAME" Type="Edm.String" MaxLength="25" sap:label="Passenger Name" sap:filterable="false"/> <Property Name="PASSFORM" Type="Edm.String" MaxLength="15" sap:label="Title" sap:filterable="false"/> <Property Name="PASSBIRTH" Type="Edm.DateTime" Nullable="true" Precision="10" sap:label="DOB of Passeng." sap:filterable="false"/>

Copyright/Trademark

Authentication Using X.509 Certificate
The procedure above describes requests sent to the service using Basic Authentication. If X.509 Certificate Authentication is needed, the X.509 Client Certificate should be attached to any request sent to the service. In addition, a CA Certificate of the SAP NetWeaver Gateway server should be used for server authentication, as part of the SSL Handshake process. Note: OData generated proxies do not support X.509 Certificate Authentication. Therefore, the service requests should be sent using Java libraries which support SSL and X.509 Certificates. In addition, the developer is responsible for parsing the service response according to the OData/SAP Data Protocols. Prerequisites The following tools are required for developing a Java application for Android using X.509 Certificate Authentication.
Software Version

Portecle-1.7

1.7

Make sure you have performed the following procedures:  Download Portecle. On a Windows operating system, this can be done by downloading the Portecle-1.7.zip file and extracting it to a selected folder.  Export the root CA Certificate of the SAP NetWeaver Gateway server into a local file. You may use any browser program for that. Make sure the certificate is saved in Base64-encoded format. Store the X.509 Client Certificate (which should be attached to each request sent to the service) in a local file. Make sure the certificate is saved in PEM format. If the certificate is saved in a different format, you may convert it to PEM format using a converter tool, such as OpenSSL. For example, to convert a PKCS#12 file (pfx.p12) containing a private key and certificates to PEM format, execute the following command:
openssl pkcs12 -in <Original_Certificate_Path>.pfx -out <Converted_Certificate_ Path>.pem –nodes

 You may need to install a patch to your JRE, and set the encryption to unlimited strength depending on your key strength. For this, you must copy the jar files from JCE 6.0 unlimited strength Jurisdiction Policy Files and override those in your JRE (for example, C:\Program Files\Java\jre6\lib\security)

Copyright/Trademark

Android Project Configuration To allow the code to use a CA Certificate and an X.509 Client Certificate: 1. Using the Portecle tool, create a trust store and a key store file. The key store will contain your X.509 Client Certificate and the trust store will contain the CA Certificate. Both files must be of type BKS when created using the Portecle tool. Note: For instructions on how to create a key store/trust store, refer to the Portecle documentation at http://portecle.sourceforge.net/create-keystore.html. 2. Import a CA Certificate to the trust store and an X.509 Client Certificate to the key store.   For instructions on how to import a CA Certificate to a trust store, refer to the Portecle documentation at http://portecle.sourceforge.net/import-trusted-cert.html. For instructions on how to import an X.509 Client Certificate to a key store, refer to the Portecle documentation at http://portecle.sourceforge.net/import-keypair.html.

3. Add the key store and the trust store to your Android project under /res/raw/. Read Example using X.509 Refer to the code snippet below for details on how to send a request to a Java Android application using X.509 Certificate Authentication: 1. Load the truststore certificate.
InputStream clientTruststoreIs = getResources().openRawResource(R.raw.truststore); KeyStore trustStore = null; trustStore = KeyStore.getInstance("BKS"); trustStore.load(clientTruststoreIs, password.toCharArray()); System.out.println("Loaded server certificates: " + trustStore.size());

2. Initialize the trust manager factory using the read truststore.
TrustManagerFactory trustManagerFactory = null; trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore);

3. Load the client certificate.
InputStream keyStoreStream = getResources().openRawResource(R.raw.keystore); KeyStore keyStore = null; keyStore = KeyStore.getInstance("BKS"); keyStore.load(keyStoreStream, password.toCharArray()); System.out.println("Loaded client certificates: " + keyStore.size());

4. Initialize the key manager factory with the read client certificate.
KeyManagerFactory keyManagerFactory = null; keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore,password.toCharArray());

Copyright/Trademark

5. Initialize the SSLSocketFactory to use the certificates.
SSLSocketFactory socketFactory = null; socketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, keyStore, password, trustStore, null, null);

6. Set the basic data.
HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUseExpectContinue(params, true); HttpProtocolParams.setUserAgent(params, "Android app/1.0.0");

7. Initialize the ConnPerRouteBean parameters.
ConnPerRoute connPerRoute = new ConnPerRouteBean(12); ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute); ConnManagerParams.setMaxTotalConnections(params, 20);

8. Set timeout.
HttpConnectionParams.setStaleCheckingEnabled(params, false); HttpConnectionParams.setConnectionTimeout(params, 20 * 1000); HttpConnectionParams.setSoTimeout(params, 20 * 1000); HttpConnectionParams.setSocketBufferSize(params, 8192);

9. Initialize HTTP client parameters.
HttpClientParams.setRedirecting(params, false);

10. Register the schemes in the scheme registry.
SchemeRegistry schReg = new SchemeRegistry(); schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 50009)); schReg.register(new Scheme("https", socketFactory, 44309)); ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg); DefaultHttpClient sClient = new DefaultHttpClient(conMgr, params); HttpGet httpGet = new HttpGet("https://vmw3815.wdf.sap.corp:44309/sap/opu/sdata/iwfnd/sflight/?sapclient=100&$format=xml"); HttpResponse response = sClient.execute(httpGet); HttpEntity httpEntity = response.getEntity();

Note: The service response should be parsed according to the OData/SAP Data Protocols. This parsing is not demonstrated in this code snippet, and should be implemented by the developer, if needed. For further details, refer to Appendix 2 – Code Snippets. For the original X.509 code usage, refer to Appendix 3 – Code Snippets using x.509.

Copyright/Trademark

Appendix 1 - RMTSAMPLEFLIGHT Service Metadata Description
<?xml version="1.0" encoding="utf-8"?> <edmx:Edmx Version="1.0" xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx" xmlns:gp="http://www.sap.com/Protocols/SAPData/GenericPlayer" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:sap="http://www.sap.com/Protocols/SAPData"> <edmx:DataServices m:DataServiceVersion="2.0"> <Schema Namespace="RMTSAMPLEFLIGHT" xmlns="http://schemas.microsoft.com/ado/2008/09/edm"> <EntityType Name="Subscription" sap:content-version="1"> <Key> <PropertyRef Name="ID"/> </Key> <Property Name="ID" Type="Edm.String" Nullable="false" MaxLength="32" sap:label="Sub. ID" sap:filterable="false"/> <Property Name="user" Type="Edm.String" MaxLength="12" sap:label="User Name" sap:filterable="false" m:FC_TargetPath="SyndicationAuthorName" m:FC_KeepInContent="false"/> <Property Name="updated" Type="Edm.DateTime" Precision="19" sap:label="Time Stamp" sap:filterable="false" m:FC_TargetPath="SyndicationUpdated" m:FC_KeepInContent="false"/> <Property Name="title" Type="Edm.String" MaxLength="255" sap:label="Title" sap:creatable="true" sap:filterable="false" m:FC_TargetPath="SyndicationTitle" m:FC_KeepInContent="false"/> <Property Name="deliveryAddress" Type="Edm.String" sap:label="Delivery Address" sap:creatable="true" sap:filterable="false"/> <Property Name="collection" Type="Edm.String" MaxLength="40" sap:label="Collection" sap:creatable="true" sap:filterable="false"/> <Property Name="filter" Type="Edm.String" sap:label="Filter" sap:creatable="true" sap:filterable="false"/> <Property Name="select" Type="Edm.String" MaxLength="255" sap:label="Select" sap:creatable="true" sap:filterable="false"/> </EntityType> <EntityType Name="Notification" sap:content-version="1"> <Key> <PropertyRef Name="ID"/> </Key> <Property Name="ID" Type="Edm.String" Nullable="false" MaxLength="32" sap:label="Notification ID" sap:filterable="false"/> <Property Name="collection" Type="Edm.String" MaxLength="40" sap:label="Collection" sap:filterable="false"/> <Property Name="title" Type="Edm.String" sap:label="Notif. Text" sap:filterable="false"/> <Property Name="updated" Type="Edm.DateTime" Precision="19" sap:label="Time Stamp" sap:filterable="false"/> </EntityType> <EntityType Name="Flight" sap:content-version="1"> <Key> <PropertyRef Name="carrid"/> <PropertyRef Name="connid"/> <PropertyRef Name="fldate"/> </Key> <Property Name="carrid" Type="Edm.String" Nullable="false" MaxLength="3" sap:label="Airline" sap:filterable="false"/> <Property Name="connid" Type="Edm.String" Nullable="false" MaxLength="4" sap:label="Flight Number" sap:filterable="false"/> <Property Name="fldate" Type="Edm.DateTime" Nullable="false" Precision="10" sap:label="Date" sap:filterable="false"/>

Copyright/Trademark

<Property Name="PRICE" Type="Edm.Decimal" Precision="20" Scale="2" sap:label="Airfare" sap:filterable="false"/> <Property Name="CURRENCY" Type="Edm.String" MaxLength="5" sap:label="Airline Currency" sap:filterable="false"/> <Property Name="PLANETYPE" Type="Edm.String" MaxLength="10" sap:label="Plane Type" sap:filterable="false"/> <Property Name="SEATSMAX" Type="Edm.Int32" sap:label="Max. capacity econ." sap:filterable="false"/> <Property Name="SEATSOCC" Type="Edm.Int32" sap:label="Occupied econ." sap:filterable="false"/> <Property Name="PAYMENTSUM" Type="Edm.Decimal" Precision="22" Scale="2" sap:label="Total" sap:filterable="false"/> <Property Name="SEATSMAX_B" Type="Edm.Int32" sap:label="Max. capacity bus." sap:filterable="false"/> <Property Name="SEATSOCC_B" Type="Edm.Int32" sap:label="Occupied bus." sap:filterable="false"/> <Property Name="SEATSMAX_F" Type="Edm.Int32" sap:label="Max. capacity 1st" sap:filterable="false"/> <Property Name="SEATSOCC_F" Type="Edm.Int32" sap:label="Occupied 1st" sap:filterable="false"/> <Property Name="flightDetails" Type="RMTSAMPLEFLIGHT.FlightDetails" Nullable="false" sap:label="FlightDetails" sap:creatable="true" sap:updatable="true" sap:filterable="false"/> <NavigationProperty Name="flightbooking" Relationship="RMTSAMPLEFLIGHT.BookingFlight" FromRole="FromRole_Flight_Booking" ToRole="ToRole_Booking_Flight"/> <NavigationProperty Name="flightBookings" Relationship="RMTSAMPLEFLIGHT.FlightBookings" FromRole="FromRole_Flight_Booking" ToRole="ToRole_Booking_Flight"/> </EntityType> <EntityType Name="Booking" sap:content-version="1" sap:semantics="FLIGHT_BOOKING"> <Key> <PropertyRef Name="carrid"/> <PropertyRef Name="connid"/> <PropertyRef Name="fldate"/> <PropertyRef Name="bookid"/> </Key> <Property Name="carrid" Type="Edm.String" Nullable="false" MaxLength="3" sap:label="Airline" sap:filterable="false"/> <Property Name="connid" Type="Edm.String" Nullable="false" MaxLength="4" sap:label="Flight Number" sap:filterable="false"/> <Property Name="fldate" Type="Edm.DateTime" Nullable="false" Precision="10" sap:label="Date" sap:filterable="false"/> <Property Name="bookid" Type="Edm.String" Nullable="false" MaxLength="8" sap:label="Booking number" sap:filterable="false"/> <Property Name="CUSTOMID" Type="Edm.String" MaxLength="8" sap:label="Customer Number" sap:filterable="false"/> <Property Name="CUSTTYPE" Type="Edm.String" MaxLength="1" sap:label="B/P customer" sap:filterable="false"/> <Property Name="SMOKER" Type="Edm.String" MaxLength="1" sap:label="Smoker" sap:filterable="false"/> <Property Name="WUNIT" Type="Edm.String" MaxLength="3" sap:label="Unit of measure" sap:filterable="false"/> <Property Name="LUGGWEIGHT" Type="Edm.Decimal" Precision="10" Scale="4" sap:label="Luggage Weight" sap:filterable="false" sap:unit="WUNIT"/> <Property Name="INVOICE" Type="Edm.String" MaxLength="1" sap:label="Invoice pty." sap:filterable="false"/> <Property Name="CLASS" Type="Edm.String" MaxLength="1" sap:label="Class" sap:filterable="false"/> <Property Name="FORCURAM" Type="Edm.Decimal" Precision="20" Scale="2" sap:label="Amount" sap:filterable="false"/> <Property Name="FORCURKEY" Type="Edm.String" MaxLength="5" sap:label="Paymnt currency" sap:filterable="false"/> <Property Name="LOCCURAM" Type="Edm.Decimal" Precision="20" Scale="2" sap:label="Amount" sap:filterable="false"/>

Copyright/Trademark

<Property Name="LOCCURKEY" Type="Edm.String" MaxLength="5" sap:label="Airline Currency" sap:filterable="false"/> <Property Name="ORDER_DATE" Type="Edm.DateTime" Precision="10" sap:label="Booking date" sap:filterable="false"/> <Property Name="COUNTER" Type="Edm.String" MaxLength="8" sap:label="Sales office" sap:filterable="false"/> <Property Name="AGENCYNUM" Type="Edm.String" MaxLength="8" sap:label="Agency No." sap:filterable="false"/> <Property Name="CANCELLED" Type="Edm.String" MaxLength="1" sap:label="Cancelation flag" sap:filterable="false"/> <Property Name="RESERVED" Type="Edm.String" MaxLength="1" sap:label="Reserved" sap:filterable="false"/> <Property Name="PASSNAME" Type="Edm.String" MaxLength="25" sap:label="Passenger Name" sap:filterable="false"/> <Property Name="PASSFORM" Type="Edm.String" MaxLength="15" sap:label="Title" sap:filterable="false"/> <Property Name="PASSBIRTH" Type="Edm.DateTime" Nullable="true" Precision="10" sap:label="DOB of Passeng." sap:filterable="false"/> <NavigationProperty Name="bookedFlight" Relationship="RMTSAMPLEFLIGHT.BookingFlight" FromRole="ToRole_Booking_Flight" ToRole="FromRole_Flight_Booking"/> </EntityType> <EntityType Name="Carrier" sap:content-version="1"> <Key> <PropertyRef Name="carrid"/> </Key> <Property Name="carrid" Type="Edm.String" Nullable="false" MaxLength="3" sap:label="Airline" sap:filterable="false"/> <Property Name="CARRNAME" Type="Edm.String" MaxLength="20" sap:label="Airline" sap:filterable="false"/> <Property Name="CURRCODE" Type="Edm.String" MaxLength="5" sap:label="Airline Currency" sap:filterable="false"/> <Property Name="URL" Type="Edm.String" MaxLength="255" sap:label="URL" sap:filterable="false"/> <NavigationProperty Name="carrierFlights" Relationship="RMTSAMPLEFLIGHT.CarrierToFlight" FromRole="FromRole_Carrier_Flight" ToRole="ToRole_Flight_Carrier"/> </EntityType> <EntityType Name="Travelagency" m:HasStream="true" sap:content-version="1"> <Key> <PropertyRef Name="agencynum"/> </Key> <Property Name="agencynum" Type="Edm.String" Nullable="false" MaxLength="8" sap:label="Agency No." sap:filterable="false"/> <Property Name="NAME" Type="Edm.String" MaxLength="25" sap:label="Travel agency name" sap:filterable="false"/> <Property Name="STREET" Type="Edm.String" MaxLength="30" sap:label="Street" sap:filterable="false"/> <Property Name="POSTBOX" Type="Edm.String" MaxLength="10" sap:label="PO Box" sap:filterable="false"/> <Property Name="POSTCODE" Type="Edm.String" MaxLength="10" sap:label="Postal Code" sap:filterable="false"/> <Property Name="CITY" Type="Edm.String" MaxLength="25" sap:label="City" sap:filterable="false"/> <Property Name="COUNTRY" Type="Edm.String" MaxLength="3" sap:label="Country" sap:filterable="false"/> <Property Name="REGION" Type="Edm.String" MaxLength="3" sap:label="Region" sap:filterable="false"/> <Property Name="TELEPHONE" Type="Edm.String" MaxLength="30" sap:label="Tel." sap:filterable="false"/> <Property Name="URL" Type="Edm.String" MaxLength="255" sap:label="Travel agency URL" sap:filterable="false"/> <Property Name="LANGU" Type="Edm.String" MaxLength="2" sap:label="Language" sap:filterable="false"/>

Copyright/Trademark

<Property Name="CURRENCY" Type="Edm.String" MaxLength="5" sap:label="Trav.Agency.Curr" sap:filterable="false"/> <Property Name="mimeType" Type="Edm.String" MaxLength="128" sap:label="MIME Type" sap:filterable="false"/> </EntityType> <ComplexType Name="FlightDetails"> <Property Name="countryFrom" Type="Edm.String" MaxLength="3" sap:label="Country" sap:filterable="false"/> <Property Name="cityFrom" Type="Edm.String" MaxLength="20" sap:label="Depart.city" sap:filterable="false"/> <Property Name="airportFrom" Type="Edm.String" MaxLength="3" sap:label="Dep. airport" sap:filterable="false"/> <Property Name="countryTo" Type="Edm.String" MaxLength="3" sap:label="Country" sap:filterable="false"/> <Property Name="cityTo" Type="Edm.String" MaxLength="20" sap:label="Arrival city" sap:filterable="false"/> <Property Name="airportTo" Type="Edm.String" MaxLength="3" sap:label="Dest. airport" sap:filterable="false"/> <Property Name="flightTime" Type="Edm.Int32" sap:label="Flight time" sap:filterable="false"/> <Property Name="departureTime" Type="Edm.Time" Precision="8" sap:label="Departure" sap:filterable="false"/> <Property Name="arrivalTime" Type="Edm.Time" Precision="8" sap:label="Arrival Time" sap:filterable="false"/> <Property Name="distance" Type="Edm.Decimal" Precision="11" Scale="4" sap:label="Distance" sap:filterable="false"/> <Property Name="distanceUnit" Type="Edm.String" MaxLength="3" sap:label="Distance in" sap:filterable="false"/> <Property Name="flightType" Type="Edm.String" MaxLength="1" sap:label="Charter" sap:filterable="false"/> <Property Name="period" Type="Edm.Byte" sap:label="n day(s) later" sap:filterable="false"/> </ComplexType> <ComplexType Name="FlightAvailability"> <Property Name="ECONOMAX" Type="Edm.Int32" sap:label="Max. capacity econ." sap:filterable="false"/> <Property Name="ECONOFREE" Type="Edm.Int32" sap:label="Free seats" sap:filterable="false"/> <Property Name="BUSINMAX" Type="Edm.Int32" sap:label="Max. capacity bus." sap:filterable="false"/> <Property Name="BUSINFREE" Type="Edm.Int32" sap:label="Free seats" sap:filterable="false"/> <Property Name="FIRSTMAX" Type="Edm.Int32" sap:label="Max. capacity 1st" sap:filterable="false"/> <Property Name="FIRSTFREE" Type="Edm.Int32" sap:label="Free seats" sap:filterable="false"/> </ComplexType> <ComplexType Name="FlightAvailability2" BaseType="RMTSAMPLEFLIGHT.FlightAvailability"/> <Association Name="FlightBookings" sap:content-version="1"> <End Type="RMTSAMPLEFLIGHT.Flight" Multiplicity="1" Role="FromRole_Flight_Booking"/> <End Type="RMTSAMPLEFLIGHT.Booking" Multiplicity="*" Role="ToRole_Booking_Flight"/> </Association> <Association Name="BookingFlight" sap:content-version="1"> <End Type="RMTSAMPLEFLIGHT.Flight" Multiplicity="1" Role="FromRole_Flight_Booking"/> <End Type="RMTSAMPLEFLIGHT.Booking" Multiplicity="1" Role="ToRole_Booking_Flight"/> <ReferentialConstraint> <Principal Role="FromRole_Flight_Booking"> <PropertyRef Name="carrid"/> <PropertyRef Name="connid"/> <PropertyRef Name="fldate"/> </Principal> <Dependent Role="ToRole_Booking_Flight"> <PropertyRef Name="carrid"/>

Copyright/Trademark

<PropertyRef Name="connid"/> <PropertyRef Name="fldate"/> </Dependent> </ReferentialConstraint> </Association> <Association Name="CarrierToFlight" sap:content-version="1"> <End Type="RMTSAMPLEFLIGHT.Carrier" Multiplicity="1" Role="FromRole_Carrier_Flight"/> <End Type="RMTSAMPLEFLIGHT.Flight" Multiplicity="*" Role="ToRole_Flight_Carrier"/> </Association> <EntityContainer Name="RMTSAMPLEFLIGHT" m:IsDefaultEntityContainer="true"> <EntitySet Name="SubscriptionCollection" EntityType="RMTSAMPLEFLIGHT.Subscription" sap:content-version="1"/> <EntitySet Name="NotificationCollection" EntityType="RMTSAMPLEFLIGHT.Notification" sap:content-version="1"/> <EntitySet Name="FlightCollection" EntityType="RMTSAMPLEFLIGHT.Flight" sap:contentversion="1"/> <EntitySet Name="BookingCollection" EntityType="RMTSAMPLEFLIGHT.Booking" sap:contentversion="1" sap:semantics="FLIGHT_BOOKING"/> <EntitySet Name="CarrierCollection" EntityType="RMTSAMPLEFLIGHT.Carrier" sap:contentversion="1" sap:creatable="false" sap:updatable="false" sap:deletable="false"/> <EntitySet Name="TravelagencyCollection" EntityType="RMTSAMPLEFLIGHT.Travelagency" sap:content-version="1" sap:searchable="true"/> <EntitySet Name="TravelAgencies" EntityType="RMTSAMPLEFLIGHT.Travelagency" sap:contentversion="1" sap:searchable="true"/> <AssociationSet Name="AssocSet_FlightBookings" Association="RMTSAMPLEFLIGHT.FlightBookings" sap:content-version="1"> <End EntitySet="FlightCollection" Role="FromRole_Flight_Booking"/> <End EntitySet="BookingCollection" Role="ToRole_Booking_Flight"/> </AssociationSet> <AssociationSet Name="AssocSet_BookingFlight" Association="RMTSAMPLEFLIGHT.BookingFlight" sap:content-version="1"> <End EntitySet="FlightCollection" Role="FromRole_Flight_Booking"/> <End EntitySet="BookingCollection" Role="ToRole_Booking_Flight"/> </AssociationSet> <AssociationSet Name="AssocSet_CarrierToFlight" Association="RMTSAMPLEFLIGHT.CarrierToFlight" sap:content-version="1" sap:creatable="false" sap:updatable="false" sap:deletable="false"> <End EntitySet="CarrierCollection" Role="FromRole_Carrier_Flight"/> <End EntitySet="FlightCollection" Role="ToRole_Flight_Carrier"/> </AssociationSet> <FunctionImport Name="CheckFlightAvailability" ReturnType="RMTSAMPLEFLIGHT.FlightAvailability" m:HttpMethod="GET" sap:actionfor="RMTSAMPLEFLIGHT.Flight"> <Parameter Name="airlineid" Type="Edm.String" Mode="In"> <Documentation> <Summary/> <LongDescription>Airline</LongDescription> </Documentation> </Parameter> <Parameter Name="connectionid" Type="Edm.String" Mode="In"> <Documentation> <Summary/> <LongDescription>Flight Number</LongDescription> </Documentation> </Parameter> <Parameter Name="flightdate" Type="Edm.DateTime" Mode="In"> <Documentation> <Summary/> <LongDescription>Date</LongDescription> </Documentation> </Parameter> </FunctionImport>

Copyright/Trademark

<FunctionImport Name="GetAvailableFlights" ReturnType="Collection(RMTSAMPLEFLIGHT.Flight)" EntitySet="FlightCollection" m:HttpMethod="POST"> <Parameter Name="fromdate" Type="Edm.DateTime" Mode="In"> <Documentation> <Summary/> <LongDescription>Date</LongDescription> </Documentation> </Parameter> <Parameter Name="todate" Type="Edm.DateTime" Mode="In"> <Documentation> <Summary/> <LongDescription>Date</LongDescription> </Documentation> </Parameter> <Parameter Name="cityfrom" Type="Edm.String" Mode="In"> <Documentation> <Summary/> <LongDescription>Depart.city</LongDescription> </Documentation> </Parameter> <Parameter Name="cityto" Type="Edm.String" Mode="In"> <Documentation> <Summary/> <LongDescription>Arrival city</LongDescription> </Documentation> </Parameter> </FunctionImport> </EntityContainer> </Schema> </edmx:DataServices> </edmx:Edmx>

Copyright/Trademark

APPENDIX 2 – CODE SNIPPETS
Read - Get Carrier by Carrier ID
Implement the Java Doc.

/** * Method for getting Carrier information by its carrierId * @param carrid the carrier id to search for, e.g. LH * @return Carrier xml entry * @throws URISyntaxException * @throws ClientProtocolException * @throws IOException */ public String getCarrier(String carrid) throws URISyntaxException, ClientProtocolException, IOException { // create the request URL String requestUrl = http://<Gateway_Host>:<Gateway_Port>/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/CarrierC ollection(carrid=' + carrid + "')"; // http get client DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("<Gateway_User>", "<Gateway_Password>")); HttpGet getRequest = new HttpGet(); // buffer reader to read the response BufferedReader bufferedReader = null; // the service response HttpResponse response = null; // construct a URI object getRequest.setURI(new URI(requestUrl)); getRequest.setHeader("Content-Type", "text/xml"); getRequest.setHeader("Host", getRequest.getURI().getHost()); // execute the request response = client.execute(getRequest); bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer stringBuffer = new StringBuffer(""); String line = ""; try { while ((line = bufferedReader.readLine()) != null) { stringBuffer.append(line); } bufferedReader.close(); } catch (IOException e)

Copyright/Trademark

{ Log.e("IO exception", e.toString()); } // response, needs to be parsed return stringBuffer.toString(); } // example on how to parse the properties from the entry xml public void parsePropertiesFromEntry(String xml) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); String propertyValue = null; String propertyName = null; try { DocumentBuilder builder = factory.newDocumentBuilder(); Document dom = builder.parse(new ByteArrayInputStream(xml.getBytes())); Element root = dom.getDocumentElement(); NodeList properties = root.getElementsByTagName("m:properties").item(0).getChildNodes(); // iterate over the entry properties for (int i = 0; i < properties.getLength(); i++) { propertyName = properties.item(i).getNodeName(); propertyValue = properties.item(i).getFirstChild().getNodeValue(); Toast.makeText(getApplicationContext(), propertyName + ": " + propertyValue, Toast.LENGTH_SHORT).show(); } } catch (Exception e) { throw new RuntimeException(e.getMessage()); } }

Copyright/Trademark

Function Import
/** * Method for executing a Function Import that returns a collection of * flights. * @param from * @param to * @param date * @return available flights * @throws URISyntaxException * @throws ClientProtocolException * @throws IOException */ public String getFlightList(String cityFrom, String cityTo, String date) throws URISyntaxException, ClientProtocolException, IOException { // create the request URL String requestUrl = http://<Gateway_Host>:<Gateway_Port>/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/GetAvail ableFlights?cityfrom= + cityFrom + "&cityto=" + cityTo + "&fromdate=" + date + "&todate=" + date; // http get client DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("<Gateway_User>", "<Gateway_Password>")); HttpGet getRequest = new HttpGet(); // buffer reader to read the response BufferedReader bufferedReader = null; // the service response HttpResponse response = null; // construct a URI object getRequest.setURI(new URI(requestUrl)); getRequest.setHeader("Content-Type", "text/xml"); getRequest.setHeader("Host", getRequest.getURI().getHost()); // execute the request response = client.execute(getRequest); bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer stringBuffer = new StringBuffer(""); String line = ""; try { while ((line = bufferedReader.readLine()) != null) { stringBuffer.append(line); } bufferedReader.close(); }
Copyright/Trademark

catch (IOException e) { Log.e("IO exception", e.toString()); } // response, needs to be parsed return stringBuffer.toString(); } // an example of how to parse the properties for each entry from the feed // xml public void parsePropertiesFromFeed(String xml) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); String propertyValue = null; String propertyName = null; try { DocumentBuilder builder = factory.newDocumentBuilder(); Document dom = builder.parse(new ByteArrayInputStream(xml.getBytes())); Element root = dom.getDocumentElement(); NodeList entries = root.getElementsByTagName("atom:entry"); // iterate over entries for (int i = 0; i < entries.getLength(); i++) { Toast.makeText(getApplicationContext(), "entry number: " + i, Toast.LENGTH_SHORT).show(); Node atomContentNode = entries.item(i).getChildNodes().item(1); If (atomContentNode.getNodeName().equalsIgnoreCase("atom:content")) { Node mpropertiesNode = atomContentNode.getChildNodes().item(0); if (mpropertiesNode.getNodeName().equalsIgnoreCase("m:properties ")) { NodeList mpropertiesList = mpropertiesNode.getChildNodes(); // iterate over entry properties for (int j = 0; j < mpropertiesList.getLength(); j++) { propertyName = mpropertiesList.item(j).getNodeName(); propertyValue = mpropertiesList.item(j).getFirstChild().getNodeV alue(); Toast.makeText(getApplicationContext(), propertyName + ": " + propertyValue, Toast.LENGTH_SHORT).show(); } } } } }
Copyright/Trademark

catch (Exception e) { throw new RuntimeException(e.getMessage()); } }

Create - Booking a Flight
// create the entry payload String content = "<atom:entry xml:base=" + "'http://<Gateway_Host>:<Gateway_Port>/sap/opu/sdata/IWFND/RMTSAMPLEFLIGHT/' " + "xmlns:atom='http://www.w3.org/2005/Atom' " + "xmlns:d='http://schemas.microsoft.com/ado/2007/08/dataservices' " + "xmlns:m='http://schemas.microsoft.com/ado/2007/08/dataservices/metadata' " + "xmlns:sap='http://www.sap.com/Protocols/SAPData'>" + "<atom:content type='application/xml'><m:properties>" + "<d:carrid>AA</d:carrid>" + "<d:connid>0017</d:connid>" + "<d:fldate m:Type='Edm.DateTime'>2011-07-27T00:00:00</d:fldate>" + "<d:bookid></d:bookid>" + "<d:CUSTOMID>00004617</d:CUSTOMID>" + "<d:CUSTTYPE>P</d:CUSTTYPE>" + "<d:SMOKER/>" + "<d:WUNIT>KG</d:WUNIT>" + "<d:LUGGWEIGHT m:Type='Edm.Decimal'>14.4000</d:LUGGWEIGHT>" + "<d:INVOICE/><d:CLASS>Y</d:CLASS>" + "<d:FORCURAM m:Type='Edm.Decimal'>879.82</d:FORCURAM>" + "<d:FORCURKEY>USD</d:FORCURKEY>" + "<d:LOCCURAM m:Type='Edm.Decimal'>803.58</d:LOCCURAM>" + "<d:LOCCURKEY>USD</d:LOCCURKEY>" + "<d:ORDER_DATE m:Type='Edm.DateTime'>2011-05-22T00:00:00</d:ORDER_DATE>" + "<d:COUNTER>00000000</d:COUNTER>" + "<d:AGENCYNUM>00000325</d:AGENCYNUM>" + "<d:CANCELLED/><d:RESERVED/>" + "<d:PASSNAME>Joe Smith</d:PASSNAME>" + "<d:PASSFORM>1234567</d:PASSFORM>" + "<d:PASSBIRTH m:Type='Edm.DateTime' m:null='true'>1990-10-10</d:PASSBIRTH>" + "</m:properties></atom:content></atom:entry>"; /** * Method for creating a new flight booking. * * @param content * @return * @throws IOException * @throws ClientProtocolException */ public String createBooking(String content) throws ClientProtocolException, IOException { DefaultHttpClient client; client = new DefaultHttpClient();

Copyright/Trademark

client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("<Gateway_User>", "<Gateway_Password>")); HttpPost post = new HttpPost( "http://<Gateway_Host>:<Gateway_Port>/sap/opu/sdata/IWFND/RMTSAMPLEFLIGHT/Booking Collection"); // you must add this header to post requests post.addHeader("X-Requested-With", "XMLHttpRequest"); HttpResponse response; StringEntity entity = new StringEntity(content); entity.setContentType(new BasicHeader("Content-Type", "application/atom+xml")); post.setEntity(entity); response = client.execute(post); if (response.getStatusLine().getStatusCode() != 201) { throw new RuntimeException(response.getStatusLine().getReasonPhrase()); } InputStream inputStream = response.getEntity().getContent(); // convert to String and return the response return convertInputStreamToString(inputStream); }

Copyright/Trademark

APPENDIX 3 – CODE SNIPPETS USING X.509
final String password = "mysecret"; /** Called when the activity is first created. */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

try { // setup truststore to provide trust for the server certificate // load truststore certificate InputStream clientTruststoreIs = getResources().openRawResource(R.raw.truststore); KeyStore trustStore = null; trustStore = KeyStore.getInstance("BKS"); trustStore.load(clientTruststoreIs, password.toCharArray()); System.out.println("Loaded server certificates: " + trustStore.size()); // initialize trust manager factory with the read truststore TrustManagerFactory trustManagerFactory = null; trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); // setup client certificate // load client certificate InputStream keyStoreStream = getResources().openRawResource(R.raw.keystore); KeyStore keyStore = null; keyStore = KeyStore.getInstance("BKS"); keyStore.load(keyStoreStream, password.toCharArray()); System.out.println("Loaded client certificates: " + keyStore.size()); // initialize key manager factory with the read client certificate KeyManagerFactory keyManagerFactory = null; keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore,password.toCharArray());

// initialize SSLSocketFactory to use the certificates SSLSocketFactory socketFactory = null; socketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, keyStore, password, trustStore, null, null); // Set basic data HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUseExpectContinue(params, true);

Copyright/Trademark

HttpProtocolParams.setUserAgent(params, "Android app/1.0.0"); // Make pool ConnPerRoute connPerRoute = new ConnPerRouteBean(12); ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute); ConnManagerParams.setMaxTotalConnections(params, 20); // Set timeout HttpConnectionParams.setStaleCheckingEnabled(params, false); HttpConnectionParams.setConnectionTimeout(params, 20 * 1000); HttpConnectionParams.setSoTimeout(params, 20 * 1000); HttpConnectionParams.setSocketBufferSize(params, 8192); // Some client params HttpClientParams.setRedirecting(params, false); // Register http/s shemas! SchemeRegistry schReg = new SchemeRegistry(); schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 50009)); schReg.register(new Scheme("https", socketFactory, 44309)); ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg); DefaultHttpClient sClient = new DefaultHttpClient(conMgr, params); HttpGet httpGet = new HttpGet("https://vmw3815.wdf.sap.corp:44309/sap/opu/sdata/iwfnd/sflight/?sapclient=100&$format=xml"); HttpResponse response = sClient.execute(httpGet); HttpEntity httpEntity = response.getEntity(); InputStream is = httpEntity.getContent(); BufferedReader read = new BufferedReader(new InputStreamReader(is)); String query = null; while ((query = read.readLine()) != null) System.out.println(query); } catch (Exception e) { e.printStackTrace(); }

Copyright/Trademark

Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close