Anda di halaman 1dari 270

SAP NetWeaver Gateway Productivity Accelerator Document Version: - 2013-05-15

SAP NetWeaver Gateway Productivity Accelerator: Development Guide

Table of Contents
1 2 Introduction to SAP NetWeaver Gateway Productivity Accelerator. . . . . . . . . . . . . . . . . . . . . . . . . 5 OData Perspective. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 Properties and Problems Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10 3 4 4.1 4.2 4.3 4.4 5 5.1 5.2 Creating a Project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Creating an OData Model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 Creating a Blank OData Model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 Creating an OData Model Using Service Metadata File. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 Creating an OData Model Using Service URL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17 Creating an OData Model Using the Service Catalog. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 Working with the OData Model Editor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 Creating OData Model Elements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 Working with the OData Model Element. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 OData Model Element. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 Selecting an OData Element. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 Resizing the OData Model Element. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 Expand and Collapse of Sections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24 Shortcut Keys. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 Things to Remember. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 5.2.1 5.2.2 5.2.3 5.2.4 5.2.5 5.2.6 5.2.7 5.3 5.4 5.5 Creating an Entity Type. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 Adding an Entity Set. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 Adding Properties. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 Creating a Complex Type. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 Creating a Function Import. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .40 Creating an Enum Type. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 Creating an Association. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

Saving the OData Model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 Deleting OData Model Elements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 Layouting in OData Model Editor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 5.5.1 5.5.2 5.5.3 Basic Layout. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 Additional Layouts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .54 Creating a Custom Layout. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 Adding EDMX References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 Working with the Referenced Entity Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 Connection Settings: Service Catalog. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

5.6

Adding References to an OData Model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .59 5.6.1 5.6.2

5.7

Service Catalog. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 5.7.1

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Table of Contents

5.7.2 5.7.3 5.7.4 5.7.5 5.7.6 5.7.7 6 6.1 6.2 6.3 6.4 6.5 6.6 6.7 6.8 7 7.1 7.2 7.3 8 8.1

Opening the Service Catalog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 Viewing the Service Catalog. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 Browsing an OData Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 Generating a Service Proxy. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 Generating a Starter Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 Importing an OData Model from Service Catalog. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

Extensibility. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 Extensibility. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 Implementing a New Template. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 Adding Code to Your Custom Template. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 Modifying an Existing Template. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .75 Editing Your Custom Android Template. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 Implementing a New Environment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .78 Adding Code to the New Environment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 Implementing Custom Export Format for OData Models. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 Service Implementation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 Introduction to Service Implementation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .85 Exporting an OData Model from the OData Model Editor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 Importing an OData Model to the Service Builder. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 Service Consumption. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 OData Toolkit for Java Platform, Standard Edition. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 8.1.1 8.1.2 8.1.3 8.1.4 Generating a JAVA SE Starter Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 Generating Proxy for Java SE. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 Introduction to the OData Java Client Library. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 Troubleshooting for the OData Toolkit for Java Platform, Standard Edition. . . . . . . . . . . . . . 102 Creating a Starter Application Project for Android . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 Generating a Proxy for an Android Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .115 Running your Android Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 Securing Your Android Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 Working with the Sybase Unwired Platform Server. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 Creating Your Own Custom Android Template. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 Troubleshooting for the Toolkit for Android (GWPA). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 Generated Application Flow. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .132 Running the Toolkit for HTML5 (GWPA). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 Creating an HTML5 Starter Application Project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 Working with the Generated HTML5 Starter Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 JQuery Mobile Application Deployment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146

8.2

Toolkit for Android (GWPA) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 8.2.1 8.2.2 8.2.3 8.2.4 8.2.5 8.2.6 8.2.7 8.2.8

8.3

Toolkit for HTML5 (GWPA). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 8.3.1 8.3.2 8.3.3 8.3.4

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Table of Contents

2013 SAP AG or an SAP affiliate company. All rights reserved.

8.3.5 8.3.6 8.3.7 8.3.8 8.4 8.4.1 8.4.2 8.4.3 8.4.4 8.4.5 8.4.6 8.4.7 8.4.8 8.4.9 8.4.10 8.4.11 8.4.12 8.4.13 8.4.14 8.4.15 8.4.16 8.4.17 8.5 8.5.1 8.5.2 8.5.3 8.5.4 8.5.5 8.5.6 8.5.7 8.5.8 8.5.9 8.5.10

Running the SAPUI5 Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 Configuration of the Generated Application to Use a Reverse Proxy. . . . . . . . . . . . . . . . . . . 148 Security of the Generated HTML5 Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 Troubleshooting for the Toolkit for HTML5 (GWPA). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .149 Creating a Starter Application Project for iOS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 Creating Proxies for an iOS Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 Using the Proxy in your iOS Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .171 Generated Application Flow. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 About the Basic Generated Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 About the Generated List/Details iOS Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .207 About the Workflow Generated iOS Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .212 About the Form Generated Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 Running the Generated iOS Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232 Configuring a Starter Kit Application to Work with SUP. . . . . . . . . . . . . . . . . . . . . . . . . . . . 233 Translation Enablement in iOS Generated Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . 234 Configuring an iOS Starter Kit Application to Work with Local Service Document and Metadata. . . . . 235 Service Versioning Negotiation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236 Configuring the User Authentication in an iOS Starter-Kit Application. . . . . . . . . . . . . . . . . .236 About the Application Logs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .238 Extending the Generated iOS Starter Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238 Troubleshooting for the Toolkit for iOS (GWPA). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248 Running the Toolkit for PHP (GWPA). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250 Creating a Starter Application Project for PHP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250 Creating a Proxy for a PHP Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .257 Using the Proxy in your PHP Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260 The Generated PHP Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .261 Running your PHP Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263 Security of the Generated PHP Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263 PHP Application Support for Cross Site Request Forgery Protection. . . . . . . . . . . . . . . . . . 264 Custom PHP Template Creation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265 Troubleshooting for the Toolkit for PHP (GWPA). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .267

Toolkit for iOS (GWPA). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150

Toolkit for PHP (GWPA). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Table of Contents

1 Introduction to SAP NetWeaver Gateway Productivity Accelerator


Introducing SAP NetWeaver Gateway Productivity Accelerator for the efficient and simple creation of OData models and consumption of OData services. Combined with the Service Builder for SAP NetWeaver Gateway, it supports the end-to-end service development process and comprises a variety of consumption toolkits for designing service consumption applications. SAP NetWeaver Gateway Productivity Accelerator introduces an OData Model Editor in Eclipse that enables you to create new OData models or view and change existing OData models using an easy-to-use graphical modeler. The editor empowers you to create new custom-built OData models with ease and efficiency, allowing you to work with the SAP data you want to retrieve without the need for ABAP development skills. An OData model export function is available for a seamless transition to ABAP for service implementation using SAP NetWeaver Service Builder, for instance. To complete this Eclipse offering, the powerful capabilities of SAP NetWeaver Gateway Productivity Accelerator enable a versatile consumption of OData services irrespective of the service provisioning platform in place and your chosen consumption device.

OData Model Creation


In real business situations, you know the precise SAP data you want to retrieve using a given OData service and how you need to consume it. SAP NetWeaver Gateway Productivity Accelerator recognizes this need and addresses developers who want the freedom to concentrate on the data they require in a given business context without demanding they first acquire ABAP development skills. The graphical OData Model Editor in SAP NetWeaver Gateway Productivity Accelerator enables you to create new OData models or display and change existing OData models visually. For instance, you can add and change an OData model's entity types, properties, and associations visually making it easier than ever before to tailor an OData model to suit your precise needs. In this way, you can define new OData models or extend existing OData models to provide additional details for a subsequent implementation on an arbitrary SAP or non-SAP platform. In short, the OData Model Editor enables you to create custom-built OData models on the fly without the need for expert ABAP knowledge. After the OData model creation phase has been completed, you can export your OData model definition and implement your service using the SAP NetWeaver Gateway Service Builder. If you are not familiar with ABAP, you can handover the exported OData model definition xml file to an ABAP developer who can implement, activate, and register the service for you.

Service Implementation
The export function in SAP NetWeaver Gateway Productivity Accelerator facilitates the transition between OData model creation in Eclipse and service implementation in the Service Builder. In the Service Builder for SAP NetWeaver Gateway, ABAP developers use the exported OData model definition to implement a new OData service. To do this, ABAP developers define the runtime artifacts (operations and methods) for the appropriate data provider class by mapping operations to a data source or by generating the required ABAP classes defined in the OData model and using these as the foundation on which they can implement the service (code-based implementation).

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Introduction to SAP NetWeaver Gateway Productivity Accelerator

2013 SAP AG or an SAP affiliate company. All rights reserved.

After the service has been implemented, the OData service is exposed on the SAP NetWeaver Gateway system and service consumption is enabled.

Service Consumption
SAP NetWeaver Gateway Productivity Accelerator includes a variety of sophisticated consumption tools enabling you to create applications that consume the SAP data retrieved by your OData service according to a specified data structure. These toolkits enable you to generate a starter application which is ready to run immediately after generation. Depending on the consumption device you want to use, you install the appropriate consumption toolkits. The SAP NetWeaver Gateway consumption tools promote the easy creation of versatile consumption applications regardless of whether the underlying OData model, on which the service is based, was created using the OData Model Editor or the Service Builder.

Summary
Put simply, SAP NetWeaver Gateway Productivity Accelerator empowers you to create custom-built OData models so you are free to consume SAP data more efficiently and flexibly than ever before. You define the SAP data and structure you need, the provisioning platform that is right for your OData services, and the consumption tools for your preferred consumption device. SAP NetWeaver Gateway Productivity Accelerator supports the development, implementation, and consumption phases by allowing you to: Create new OData models. Create new OData models based on OData service metadata retrieved using an OData service URL. Create new OData models based on OData service metadata imported from a file. Create new OData models based on OData service metadata from the Service Catalog in your SAP Business Suite system. Browse OData service definitions in the Service Catalog. Export OData model definition files. Import OData model definition files to the Service Builder to implement, activate, and register service or delegate these tasks to an ABAP developer. Design consumption applications using consumption tools or delegate this task to an application developer/UI designer. Consume SAP data according to your required data structure using the consumption device of your choice.

SAP NetWeaver Gateway Productivity Accelerator succinctly establishes the link between service provisioning tools and consumption tools. For instance, it can empower technical consultants with expert knowledge, but limited programming skills, to develop use-case specific OData services to release the potential of data stored in SAP databases. Whatever your skillset and requirements, SAP NetWeaver Gateway Productivity Accelerator provides comprehensive guidance throughout the OData service lifecycle, while providing ABAP developers the option to work with the Service Builder for a classic ABAP development experience integrated with Eclipse.

Note

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Introduction to SAP NetWeaver Gateway Productivity Accelerator

While SAP NetWeaver Gateway uses OData, the OData implementation in place is not a full implementation according to the official OData specification at http://www.odata.org. This restriction applies to all OData versions. Related Links

https://help.hana.ondemand.com/gateway_gwpa https://help.hana.ondemand.com/gateway_gwpa/pdf/ SAP_NetWeaver_Gateway_Productivity_Accelerator_Master_Guide_en.pdf https://help.hana.ondemand.com/gateway_gwpa/pdf/ SAP_NetWeaver_Gateway_Productivity_Accelerator_Inst_Guide_en.pdf

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Introduction to SAP NetWeaver Gateway Productivity Accelerator

2013 SAP AG or an SAP affiliate company. All rights reserved.

OData Perspective

The OData Perspective provided by SAP NetWeaver Gateway Productivity Accelerator (GWPA) is a customized view, which is recommended to be used to create OData models. This section will describe the default views available in the OData Perspective. 1. In your Eclipse installation, choose Window Open Perspective Other .

The Open Perspective window appears. 2. Locate and choose OData from the list of perspectives.

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide OData Perspective

The OData Perspective opens.

The table below summarizes the views that are available in the OData Perspective. Table 1: OData Perspective-Views Views Project Explorer Description The project explorer displays all the project(s) created in the current workspace. Actions The project folder holds folders, packages etc. The OData file created using the OData Model Editor will be stored in the relevant folder and when expanded, the underlying artifacts of the OData model can be seen. Furthermore, you can select an OData artifact and the properties view will show the properties of this artifact, which can then be edited. Select either the Properties or Problems views to view the appropriate information . On selecting an error message, the corresponding erroneous artifact will be highlighted.

Properties View

This region displays the properties of the artifacts selected in the OData Model Editor/Project Explorer. OData model validation errors are displayed in the Problem view. On saving a OData model validation will be triggered for the underlying model.

Problems

Miniature View

This view displays a copy of the OData You can also activate/deactivate the Miniature Model Editor in a very small scale. View from the Windows Show View OthersGeneral menu.

Service Catalog

The Service Catalog feature allows the At least one connection to a SAP NetWeaver user to view the services available in Gateway system should be configured to view the configured SAP system.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide OData Perspective

2013 SAP AG or an SAP affiliate company. All rights reserved.

Views

Description

Actions underlying service. See Service Catalog [page 65] for more information.

Properties and Problems Views


The Properties View is the region that is below the OData Model Editor. This region has a customized view, and you can select the views to be displayed here from the Windows Show View .

Properties- Choose either the element or the OData model element in the OData Model Editor to view its property. You can also edit the values for the selected elements here, and the changes will be reflected in the OData model element.

Problems- On saving a OData model, the underlying OData errors are displayed in the OData Model Editor. The details of error can be viewed by selecting the Problem tab. On selecting an error message and

10

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide OData Perspective

corresponding erroneous elements are selected in the OData model element. The Problems view displays all the existing errors and warnings and information of all the existing projects in the eclipse workspace. Any java or xml validation errors are also listed here.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide OData Perspective

2013 SAP AG or an SAP affiliate company. All rights reserved.

11

Creating a Project

Creating a project After the OData Perspective is selected as detailed in the OData Perspective [page 8], the next step is to create a project. To create a project proceed as follows: 1. Click The 2. 3. 4. File New New Other . window appears.

Select a wizard

Expand the General folder and choose Project . Click Next to proceed. The New Project Project window appears. Enter a name for the project in the Project name field and click Finish to create the project. The new project is displayed in the Project Explorer region.

Related Links

Creating a Blank OData Model [page 13] Creating a blank OData model. Creating an OData Model [page 13] Creating an OData Model https://help.hana.ondemand.com/gateway_gwpa/pdf/ SAP_NetWeaver_Gateway_Productivity_Accelerator_Inst_Guide_en.pdf

12

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Creating a Project

Creating an OData Model

Creating an OData Model After creating a project as detailed in the Creating a Project [page 12] section, the next step is to define the attributes for creating a OData model. Once the project is successfully created, the project folder appears in the project explorer region. The next step is to create an OData model. GWPA provides multiple options to create an OData Model: From a Blank OData Model. See Creating a Blank OData Model [page 13] for more information. From a OData service metadata url. See Creating an OData Model Using Service URL [page 17] for more information. From a OData service metadata file. See Creating an OData Model Using Service Metadata File [page 15] for more information. From existing OData service using the service catalog. See Creating an OData Model Using the Service Catalog [page 19] for more information.

4.1

Creating a Blank OData Model

Creating a blank OData model. To create a blank OData model proceed as follows: 1. 2. Open Eclipse screen. Right-click the new project in the Project Explorer and choose The 3. 4. Click on New File New Other . window appears. folder. New Other in the resulting menu.

Select a wizard

Locate and expand the

OData Development

Choose OData Model and click Next. The New OData Service-Create New OData Service window appears.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Creating an OData Model

2013 SAP AG or an SAP affiliate company. All rights reserved.

13

5.

Enter a name for the model in the Model Name field.

Note
In step 2, if you had right clicked on the project folder and selected New Other then the Folder will be defaulted to the project. If you had selected File New Other then the Folder field will be empty, and you can choose Browse to select a project for the new OData model. 6. Choose Blank OData Model in the Initial model content region and click Finish.

14

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Creating an OData Model

The new model is created and opens as a tab page in the OData Model Editor for editing.

Related Links

Creating an OData Model Using Service Metadata File [page 15] Creating an OData model using an existing metadata file. Creating an OData Model Using Service URL [page 17] Creating an OData model using the URL of an existing service. Creating an OData Model Using the Service Catalog [page 19] Create an OData model using an existing file from the Service Catalog.

4.2

Creating an OData Model Using Service Metadata File

Creating an OData model using an existing metadata file. The File Import function is used to import metadata files types (edmx and xml) to create an OData model in GWPA. During the import of an EDMX file, the graphical information is computed, and the corresponding shapes are created in the OData Model Editor and arranged as follows: Entities Complex Types Function Import

To create an OData model using a service metadata file proceed as follows: 1. 2. Create a project as outlined in the Creating a Project Creating a Project [page 12]section. Right click on the project in the Project Tree region, and select The Select a Wizard window displays. New Other .

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Creating an OData Model

2013 SAP AG or an SAP affiliate company. All rights reserved.

15

3. 4.

Locate OData Development folder, expand it and select OData Model. Click Next to proceed. The Create New OData Model window appears.

5. 6. 7. 8.

Choose Browse or enter the folder name in the Folder field to select a project folder for the new OData model. Enter a name for the model in the Model Name field. Select OData Service Metadata File from the list and click Next. The New OData model from the file system window appears. Enter the path to access the edmx or xml file, or click Browse to choose the file from the system and click Go. On selection of a valid file the contents of the file will be populated in the Service details region of the window.

9.

Click Finish. The selected file is converted to OData service and displayed in the OData Model Editor. All the sections in entities open up in a expanded state for editing.

Note
The errors in the imported model are indicated by the error icons. The Problems tab view in the properties view displays the errors in the model. The service is now ready to be edited and will be stored under the selected folder in the Project Explorer.

16

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Creating an OData Model

Related Links

Creating a Blank OData Model [page 13] Creating a blank OData model. Creating an OData Model Using Service URL [page 17] Creating an OData model using the URL of an existing service. Creating an OData Model Using the Service Catalog [page 19] Create an OData model using an existing file from the Service Catalog.

4.3

Creating an OData Model Using Service URL

Creating an OData model using the URL of an existing service. To create an OData model using a service metadata URL proceed as follows: 1. 2. 3. 4. Create a project as outlined in the Creating a Project Creating a Project [page 12]section. Right click on the project in the Project Tree region, and select The Select a Wizard window displays. Click Next to proceed. The Create New OData Model window appears. 5. 6. 7. 8. Choose Browse or enter the folder name in the Folder field to select a project folder for the new OData model. Enter a name for the model in the Model Name field. Select OData Service Metadata URL from the list and click Next. The New OData model from remote source window appears. Enter the service URL of the service to be imported in the Service URL field and click Go. New Other .

Locate OData Development folder, expand it and select OData Model.

Note
Ensure that you have authorizations to access the services. If you do not have authorizations, an error message will be displayed. You can also create a connection to a SAP NetWeaver Gateway system, see Connection Settings: Service Catalog [page 65] for more information.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Creating an OData Model

2013 SAP AG or an SAP affiliate company. All rights reserved.

17

On providing a valid URL the service will be populated in the Service details region of the window.

9.

Click Finish. The selected file is converted to OData service and displayed in the OData Model Editor. All the sections in entities open up in a expanded state for editing.

Note
The errors in the imported model are indicated by the error icons. The Problems tab view in the properties view displays the existing errors in the service. The service is now ready to be edited and will be stored under the selected folder in the Project Explorer. Related Links

Creating a Blank OData Model [page 13] Creating a blank OData model. Creating an OData Model Using Service Metadata File [page 15] Creating an OData model using an existing metadata file. Creating an OData Model Using the Service Catalog [page 19] Create an OData model using an existing file from the Service Catalog.

18

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Creating an OData Model

4.4

Creating an OData Model Using the Service Catalog

Create an OData model using an existing file from the Service Catalog. This section will guide you to create new OData model based on existing OData service in SAP NetWeaver Gateway. 1. 2. 3. 4. Create a project as outlined in the Creating a Project Creating a Project [page 12]section. Right click on the project in the Project Tree region, and select The Select a Wizard window displays. Click Next to proceed. The Create New OData Model window appears. 5. 6. 7. Choose Browse or enter the folder name in the Folder field to select a project folder for the new OData model. Enter a name for the model in the Model Name field. Select Service Catalog from the list and click Next. New Other .

Locate OData Development folder, expand it and select OData Model.

Note
Atleast one connection should be added to the SAP NetWeaver Gateway system to view the service catalog available in the system. See Connection Settings: Service Catalog [page 65] for more information. The Connections and Services window appears. The Select OData service from Service Catalog window appears. The available connection and services are displayed in the Connections and services region.

Note
You can also choose Manage Connections links to open the Preferences Connection Settings: Service Catalog [page 65] for more information. Connections window. See

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Creating an OData Model

2013 SAP AG or an SAP affiliate company. All rights reserved.

19

8.

Select a service from the service catalog and click Finish. The selected service opens in the OData Model Editor for editing.

Related Links

Creating an OData Model Using Service Metadata File [page 15] Creating an OData model using an existing metadata file. Creating an OData Model Using Service URL [page 17] Creating an OData model using the URL of an existing service. Creating an OData Model Using the Service Catalog [page 19] Create an OData model using an existing file from the Service Catalog.

20

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Creating an OData Model

Working with the OData Model Editor

Working in the OData Model Editor This section guides you to use the OData Model Editor to create an OData model. The objective of this section is to familiarize the users to perform some basic functions while creating an OData model.

Related Links

Creating OData Model Elements [page 21] Creating OData Model Elements in the OData Model Editor. Working with the OData Model Element [page 23] Understanding the OData model element.

5.1

Creating OData Model Elements

Creating OData Model Elements in the OData Model Editor. This section will guide you to use the elements in the palette. There are two ways to transport the elements from the palette onto the OData Model Editor: Select the element in the palette by clicking on it and then clicking inside the OData Model Editor. Alternatively, you can also select an element under Objects in the pallete, press and hold down the left mouse button, drag the element onto the OData Model Editor.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

2013 SAP AG or an SAP affiliate company. All rights reserved.

21

Drop the element by releasing the mouse button.

The OData Model Element is created in the OData Model Editor.

Note
Every new element created in the OData Model Editor will have a unique name at the time of creation. The object's name field is editable immediately. Related Links

Working with the OData Model Editor [page 21] Working in the OData Model Editor

22

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

5.2

Working with the OData Model Element

Understanding the OData model element. Every OData model element will have sections and each section will have section headers and properties under them. For example, the entity object element will have: This section will guide you to understand the various functions available in the OData model element.

OData Model Element


The OData model element is graphical representation of the artifacts in the OData Model Editor. For example, the entity type OData model element has three sections with the following headers: Entity Sets Properties Navigation Properties

Note
The section header names cannot be modified.

Selecting an OData Element


You can move the OData model element by first selecting the shape. Left click inside the OData model element. Ensure to click on the borders, dividers or the object icon.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

2013 SAP AG or an SAP affiliate company. All rights reserved.

23

The OData model element is selected and now you can move and position the shape inside the OData Model Editor as required.

Resizing the OData Model Element


The OData model element re-sizes automatically to accommodate additional properties, You can also resize the OData model element manually by selecting it and dragging the corners. Select the OData model element and drag the corners to re-size the OData model element manually.

Expand and Collapse of Sections


The OData Model Editor provides an universal expand and collapse button on the tool bar to expand and collapse all the section headers of the objects in the OData model element. You can also expand and collapse the sections in the OData model element. Table 2: Properties Description Expand All Collapse All Button Shortcut Keys Ctrl + Alt + E Ctrl + Alt + C

24

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

1.

Click the Collapse All OData Model Editor.

button on the tool bar to collapse all the objects in the OData Model Elements in the

Click the arrow head button in the expanded section header to collapse the sections

2.

Click the Expand All OData Model Editor.

button on the tool bar to expand all the objects in the OData model elements in the

Click the arrow head button in the collapsed section header to expand it.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

2013 SAP AG or an SAP affiliate company. All rights reserved.

25

Context Pad
A context pad is provided for every OData model element to assist the user to perform some basic functions in the OData Model Editor with just a click. Just hover the mouse cursor on the OData model element to view the context

pad. The context pad provides the following functions: Delete - Click to delete the OData model element along with the related entities and associations.

Add Property- Click to add a simple property to the OData model element. See Adding Properties for more information.

Add Complex Property- Click to add a complex property to the OData model element.

26

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

Add Navigation Property - Click to add a navigation property to the OData Model Element.

Add Association- Click and drag the arrow to another entity to create associations between entity types.

Context Menu
This section describes the common options available in the context menu of the OData Model Elements. Some options are specific to OData Model Elements and are not addressed in this section. 1. Right click on the header of the OData Model Element to open the Context menu.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

2013 SAP AG or an SAP affiliate company. All rights reserved.

27

2.

Do the following using the context menu of the OData Model Element: Context Menus
Undo Create a new Enum Type Add Member Show Usages

Description
Use this menu to revert a creation of a new enum type Adds a member under the Members section Use this menu to show and hide the all relationships of this enum type with other artifacts on the canvas. The relationships are represented by arrows Deletes the OData model element Use this menu to export and save the object as a diagram Collapse All Use this menu to either expand all or collapse all the objects in the OData model element Use this menu to choose the preferred layouts to layout the OData model elements in the OData model Use this menu print the diagram

Delete Export Diagram Diagram Layout Print Expand All

Show/Hide All Usages


The objective of the Show/Hide All Usages button is to provide the user with the facility to view all the relationships between the artifacts on the graphical editor. Clicking the button in the when relationships are displayed will hide all the relationship(s). The Show/Hide button is a toggle button and can be located on the tool bar of the eclipse application and in the context pad of the objects. This button switches between two states; Show Usage (showing the relationship between the artifacts) and Hide Usage (hiding relationship between the artifacts). The appearance of the button changes with its state to provide visual assistance for the user. Table 3: Show /Hide All Usages Button State Active Description When the Show/Hide Usage button has a box around it (pressed state) signifies that all the relationships between the artifacts in

28

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

Button

State

Description the graphical editor are being visible. You can press the button to hide the relationships.

Inactive

When the Show/Hide Usage button appears without a box around it, then you can press it to view all the relationships between the artifacts in the graphical editor.

The following condition are adhered while using the Show/Hide button: When an OData model is opened in the graphical editor and when the Show/Hide All Usages toggle button is pushed, the usage for all artifacts are shown in graphical editor canvas. The graphical editor switches to unsaved state & the button is in active state. The relationship between the artifacts are shown by arrows. Show usage will be available for entity types, complex types and Enum types. For complex types, if the same complex type is used in multiple properties in an entity, then link will be shown only to the parent entity. It is also applicable for entity types and enum types. Show/Hide usage function is available for property usage and base type if the entity type and complex type.

Show usage is available for property usage for Enum type. Show usage is available for parameter usage and return type for function import. When show usage is enabled, and if any changes are made in the properties view, the OData Model Editor reflects the changes instantly.

Note

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

2013 SAP AG or an SAP affiliate company. All rights reserved.

29

Whenever the Show/Hide All Usages toggle button is used, the graphical editor returns to the unsaved mode to maintain the state of Show/Hide All Usages toggle button. On saving & reopening the model file, the last state of the Show/Hide All Usages toggle button will be maintained.

Shortcut Keys
The table below provides the list of shortcut keys that can be used in the OData Model Editor. Table 4: Show /Hide Usage Action To Navigation Left between the OData Model Elements Navigate right between the OData Model Elements Navigate down within the OData Model Elements Navigate up within the OData Model Elements Navigate into a section in the OData Model Element Navigate out of a section in the OData Model Element Cycle through an OData Model Element Move an OData Model Element Shortcut Key Left arrow Right arrow Down arrow Up arrow Alt+Down arrow with the OData model element selected Alt+Up arrow Select the OData model element and press the period key Cycle once to the Move handle using the period key. Use navigation keys to move. Press Enter to accept new location. Press Escape to cancel the move Cycle to desired resize handle using the period key. Use navigation keys to resize. Press Enter to accept new size. Press Escape to cancel the resize Slash or backslash while on an element with connections Hold down Ctrl. Use navigation keys to navigate to additional OData model element. Press Space to select additional shapes or deselect already selected ones. Hold down Shift, use navigation keys to select additional shapes or deselect already selected ones. Shift + Tab Tab (currently only works with active selection tool) RETURN

Resize an OData Model Element

Cycle through connections Select multiple

Select in sequence Go from OData model editor to palette Go from palette to OData model editor Create selected palette element

30

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

Action To Create relation between OData Model Element

Shortcut Key Apply multi selection to the OData model element with SPACE. Navigate to palette with Shift + Tab and create the desired relation with RETURN

Things to Remember
Whenever a change is made on the canvas the OData Model Editor displays a star icon in the tab page of the OData Model Editor indicating that the model needs to be saved.

Select and press F2 to edit any objects in the entity shape. On saving the model, an error icon displays on the elements that are erroneous and also in the OData Model Editor.

Multiple elements and attributes can be deleted by either using CTRL key or SHIFT key and selecting the objects. A delete confirmation window appears during such operations.

5.2.1

Creating an Entity Type

This section guides you to create an Entity Type.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

2013 SAP AG or an SAP affiliate company. All rights reserved.

31

The Entity Type describe the structure of data in an OData Model. Entity types represent a specific type of data, for example an item or a concept. Entity type OData Model Element comprises of: Entity name-Unique name Entity Sets Properties Key, which can be defined by one or more properties (Is Key) Navigation Properties (optional to navigate between associations)

To create an entity type in your project, proceed as follows: 1. 2. Select Entity Type under Objectsin the palette, press and hold down the left mouse button, drag the element onto the graphical editor region. Drop the element by releasing the mouse button. A graphical representation of the entity type (OData Model Element) is created on the OData Model Editor. Alternatively, you can also click on the Entity Type in the palette and click inside the OData Model Editor to create the entity type.

Note
Every new entity will have a unique name at the time of creation. The Entity name field is in editable status immediately. 3. Enter a name for the Entity and press "Enter" in the keyboard or click outside the entity name field. The following elements are updated for the selected entity with new entity name: Entity Set Key Property ID

Note
Renaming the entity type will rename the corresponding entity sets, navigation properties and the default key properties.

5.2.2

Adding an Entity Set

This section provides information to add entity sets to the entitites. An entity set is automatically created when an entity type is created. Further, you can also add more entity sets to the entity type as required.

32

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

1.

Right click on the header of the Entity Type OData Model Element and select Add Entity Sets You can also create an entity set, by selecting the existing entity set and pressing the Enter key.

The new entity set is added under the Entity Sets section and is ready for editing.

Note
An unique name will be displayed for the new entity set.

2.

Select an Entity Set to view and edit its properties in the Properties View.

Related Links

Working with the OData Model Element [page 23] Understanding the OData model element.

5.2.3

Adding Properties

This section provides instructions to add properties for an entity and complex type.

Note

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

2013 SAP AG or an SAP affiliate company. All rights reserved.

33

A key property is automatically added to the entity when the entity is created.

1.

Right click on the header of the Entity Type OData Model Element and select Add Properties and select the property to be added of your choice:

You can also create similar properties by selecting the existing property and pressing the Enter key. The properties have different icons as shown in the table below: Table 5: Properties Properties Key Simple Complex Enum Navigation Icons

Note
The navigation property will be added under the Navigation Properties region.

34

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

2.

Select a Property to view and edit its properties in the Properties View.

Note
To delete a property, right click on the property and select Delete Related Links

Working with the OData Model Element [page 23] Understanding the OData model element.

5.2.3.1

Working in the Properties View

The Properties View allows you to edit OData properties. These properties are used to define the different artifacts in the model.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

2013 SAP AG or an SAP affiliate company. All rights reserved.

35

Each artifact displays a different set of attributes according to the OData specifications. When you change the selection of an artifact in the OData Model Editor, the SAP Service Catalog view, or in the project explorer tree, the attributes displayed in the Properties View change accordingly.

Note
When selecting an artifact in the SAP Service Catalog view, its properties are displayed in the Properties view in read-only mode. If you double-click on a service from the SAP Service Catalog, it is displayed in the OData Model Editor, but its properties are still read-only in the Properties view. When you change an attribute in the OData Model Editor, the changes are reflected automatically in the Properties view and vice-versa. For example, you can change the name of the artifact in either place and it will be updated in both. The Properties view also allows you to change attributes that are not editable in the OData Model Editor, for example, changing the name of the schema. To display the Properties view: 1. 2. Select Select Window General Show View Other . The Show View dialog is displayed

Properties . The Properties view is displayed.

To edit the properties of OData artifacts: 1. 2. Select the desired artifact. From the General tab, give the desired value to the artifacts attributes displayed.

36

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

Referential Constraints
A referential constraint asserts that the entity on the principal end of the referential constraint must exist in order for the entity on the dependent end to exist. This assertion is established by the edm:ReferentialConstraint element. A referential constraint must contain exactly one edm:Principal element and exactly one edm:Dependent element. To maintain association referential constraints:

Note
Referential constraints are not relevant for associations in a many to many relationship. 1. 2. 3. 4. Select desired association. The associations attributes are displayed in the Properties view. Select Referential Constraint. In the Value column, choose . The Referential Constraint page is displayed.

From the Principle drop-down list, select the entity with the principal role. The Dependent column is filled in automatically with the second entity in the association.

Note
If the association is 1:many, the entity from which the association goes to many is automatically selected as Principal. 5. In the Principle Key column, select the property key that will act as lead in the association.

Note
The properties displayed in the Principal Key column, depend on the properties defined as Key in the OData Model Editor. 6. From the Dependent Property drop-down list, select the desired property to be dependent on the principal key.

Note
You cannot use the same property for two different Principle keys. 7. Choose OK. The referential constraint is displayed in the Value column of the Properties Editor.

To delete a referential constraint: 1. 2. 3. 4. Select desired association. The associations attributes are displayed in the Properties view. Select Referential Constraint. In the Value column, choose . The Referential Constraint page is displayed.

Choose Delete. All the referential constraints for these entities are deleted.

To maintain association set: 1. Select desired association. The associations attributes are displayed in the Properties view.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

2013 SAP AG or an SAP affiliate company. All rights reserved.

37

2. 3. 4. 5. 6. 7. 8.

Select Association Sets. In the Value column, choose . The Association Sets page is displayed. On the displayed page you can see a table with the association set properties (name of the association set, end1 entity set, and end2 entity set). To add a new association set, choose the Add. To delete an association set, select it from the table and choose Remove. To edit the name of the association set, in the Name column, select the desired name and edit it. To change an entity set of the association set, select the desired entity set and change it by selecting a different one from the drop-down list. Choose Apply.

Annotations
You can apply annotations to OData artifacts from the Properties View Annotations tab.

Note
The Annotations tab is enabled only when an OData artifact that supports annotations is selected. To apply annotations to an OData artifact: 1. Select the desired artifact from the model and choose (maintain annotation) from the Properties view toolbar. The Maintain Annotation page is displayed showing the available (loaded) vocabularies. These vocabularies contain the applicable terms for the selected artifact. Expand the desired vocabulary.

2.

Note
If terms have already been selected for this vocabulary, they appear in the list with thier checkbox selected. 3. 4. 5. 6. If the desired vocabulary is missing, you can add it manually using the edmx references. For more information see the Adding EDMX References topic. Select the checkbox of the desired term(s). When finished, choose OK. The annotations tab is displayed in the Properties view. You can edit each term in the Value column according to the term's limitations.

To edit simple value annotations: Entering the appropriate value (according to the annotation type). Selecting an artifact from the Value drop-down list. If there are other artifacts of the same type (for example, edm.string type), they are displayed in the drop-down list.

Note
For Boolean annotations, the drop-down list contains True, False, and Artifacts of type Boolean (in this case you cannot enter the value).

Note

38

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

If the term is annotated with the annotation isPropertyPath, you can choose its value only from the dropdown list . You can check the annotations for the terms in each of the vocabularies. To acces the vocabularies provided out-of-the-box, go to the OASIS repositories webpage. Annotations of type record can contain simple value annotations and annotation collections within them. To see what the record annotiation is composed of, expand the term cell. To edit record annotations: Edit the simple value annotations. Edit collections: 1. 2. 3. 4. selecting the value cell and choosing . The Maintain Dynamic Annotation dialog is opened.

Expand the collection to set the value for each annotation. To add a collectable expression, select the desired collection row and choose Add. To remove a collectable expression, select the desired collectable expression's row and choose Remove.

Related Links

Adding EDMX References [page 59] Adding EDMX references to the OData model. OASIS repositories webpage

5.2.4

Creating a Complex Type

Creating a Complex Type To create a complex type in the OData Model Editor proceed as follows 1. Select Complex Type under Objects in the palette, press and hold down the left mouse button, drag the object onto the OData Model Editor.

Note
The new complex type will be created with a unique default name. The context pad of the complex type OData Model Element has three menus:

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

2013 SAP AG or an SAP affiliate company. All rights reserved.

39

Add Property - Choose

to add a new property to the Complex Type to add a new Complex property

Add Complex Property - Choose

Add Enum Property- Choose to add new Enum property

See Working with the OData Model Editor [page 21] for more information of working with the OData Model Elements.

Note
The OData Model Element also comes with a context menu Alternatively, the context menu can be used to add preferred property. 2. Select the added property and navigate to the Properties view and configure the newly added properties. Choose the drop-down in the Type field and select a type to be assigned for new property.

3.

Save the Odata Model Editor.

Related Links

Working with the OData Model Element [page 23] Understanding the OData model element.

5.2.5

Creating a Function Import

This section provides instructions to create a Function Import. To create a Function Import proceed as follows: 1. 2. Select Function Import under Objects in the pallete, press and hold down the left mouse button, drag the object onto the OData Model Editor. Drop the object by releasing the mouse button. A graphical representation of the entity type object is created in the graphical editor.

40

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

Alternatively, you can also click on Function Import in the palette and click inside the OData Model Editor to create a complex type.

Note
The new Function Import will be created with a unique name by default.

The context pad of the complex type has the following menus: Delete - Choose to delete the function import from this model. to add a new input parameter to the Function Import. to add a simple return type.

Add Parameter - Choose

Add Simple Return Type - Choose

Add Complex Return Type - Choose to add a complex type. Ensure that you have created a complex type. the drop-down list displays all the available complex types.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

2013 SAP AG or an SAP affiliate company. All rights reserved.

41

Add Entity Return Type - Choose to add a entity type. Ensure that you have created a entity type. the drop-down list displays all the available entity type in the model.

Add Enum Return Type- Choose to add a enum return type to the Function Import.

Note
Only one Return Type can be added and on adding a return type the return type menus becomes inactive. On deleting a return type the return type menus becomes active.

42

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

3.

Do the following to complete the function import definition: Select the function import and navigate to the properties view. Click the drop-down list in the Type field and select an entity type.

4.

Right click and select Delete in the resulting menu to select an element. The Delete key from the keyboard can also be used to delete an element. On selecting Delete, the Confirm Delete window appears. Click Yes to delete the entity type.

5.

Related Links

Working with the OData Model Element [page 23] Understanding the OData model element.

5.2.6

Creating an Enum Type

This section provides instructions to create an Enum Type. An enum type is a data type consisting of a fixed set of constants. For example, to define a variable whose value will represent a day of the week, there are only seven values the variable can store. So, to define those values, you can use an enumeration type, which is declared by using the enum keyword. Enum type will have an underlying type and member variables, which are basically the fixed values for that enum type. The graphical editor allows you to create Enum types for your model. 1. Click on the Enum Type in the Pallete and then click in the OData Model Editor to create a enum type. Click and drag the Enum Type icon on to the OData Model Editor to create a enum type.

The Enum type appears on theOData Model Editor. The Enum Type has a fixed Underlying Type. 2. Click the Add Member icon in the context pad of the EnumType object.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

2013 SAP AG or an SAP affiliate company. All rights reserved.

43

A member will be added to enum type. The member can be renamed as required. 3. Select an Enum Type to view and edit its properties in the Properties View.

Related Links

Working with the OData Model Element [page 23] Understanding the OData model element.

5.2.7

Creating an Association

This sectoin provides information to create Association between Entities. An association is a named relationship between two entities. Association defines a peer-to-peer relationship between participating entity types and can support different multiplicities at both the ends. An example of an association is the relationship between the Customer and Order entities. You can create three types of association: Single Association - This is the unidirectional association, which allows navigation in only one direction. See Creating a Single Association [page 44] . Bi-directional Association - The bi-directional association allows navigation in both directions of the association. The bi-directional association is defaulted to one-to-many. See Creating a Bidirectional Association [page 47] . Self Association - Self association has the ends of the association point to the same entity . See Creating a Self Association [page 48].

5.2.7.1

Creating a Single Association

To define single association proceed as follows: 1. 2. Create entity types as detailed in the Creating an Entity TypeCreating an Entity Type [page 31] section. Select the Single menu under Associations.

44

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

Once Single is selected and on moving the mouse pointer into the OData Model Editor, the mouse pointer

changes its shape indicating that the association creation mode in active. 3. Click in the source entity type shape to create an association and drag the mouse to the destination shape.

Once on the destination entity shape, left click the mouse to complete the creation of the association. The association is created and a dotted arrow line connects the shapes. 4. Choose the Select Icon in the Palette to come out of the association create mode.

Press escape from the keyboard to come out of the association create mode.

Note

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

2013 SAP AG or an SAP affiliate company. All rights reserved.

45

A Navigation Property is automatically created for the new association. You can rename the navigation property by double clicking on it. Every navigation propery should have a unique name. The association is created and an arrow with a singe head appears representing the single association. Also the cardinality is displayed on both ends of the arrow implying the relationship one-to-many (star sign represent many). 5. On saving the project, the tree region displays the entity types, new association and the corresponding navigation property.

Note
Association Sets, Referential Constraints and the soruce and target roles are automatically created on creation of an association. Related Links

Creating a Bidirectional Association [page 47] Instructions about how to create a bidirectional associations. Creating a Self Association [page 48]

46

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

Explains how to create self associations in the entities.

5.2.7.2

Creating a Bidirectional Association

Instructions about how to create a bidirectional associations. To create a bidirectional association proceed as follows: 1. 2. Create two entity types as mentioned in the Creating an Entity Type [page 31]section. Select the Bidirectional object under Associations Once Bidrectional is selected and on moving the mouse pointer into the OData Model Editor, the mouse pointer changes its shape indicating that the association creation mode in active. Click in the source entity type to create a bidrectional association and drag the mouse to the destination entity type.

3.

Note
The destination OData Model Element cannot be a complex type, function import, enum type. The cursor icon changes for invalid destination OData Model Element. The association is created and a line with an arrow at both the ends connects the shapes. 4. 5. Create multiple birectional association as required. Choose the Select Icon in the Pallete to come out of the association create mode.

Press escape from the keyboard to come out of the association create mode.

Note
A Navigation Property is automatically created for the new association. You can rename the navigation property by double clicking on it or by pressing F2 . Every navigation propery should have a unique name.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

2013 SAP AG or an SAP affiliate company. All rights reserved.

47

On saving the project, the tree region populates the Entity Types, new Asscociation and the corresponding Navigation Properties. Related Links

Creating a Single Association [page 44] Creating a Self Association [page 48] Explains how to create self associations in the entities.

5.2.7.3

Creating a Self Association

Explains how to create self associations in the entities. To create a self single/bidirectional association proceed as follows: 1. 2. Create an entity type as mentioned in the Creating an Entity Type Creating an Entity Type [page 31]section. Select Single to create a single self association and select Bidirectional bidirectional self association. to create a

Note
An example for single self association is the association between a Manager and his direct reports. An example for birectional seft association is the association between the Employees and Manager as well as Employees and DirectReports. 3. Double click (click in the entity type shape and drag the mouse inside the entity type. Then click again inside the entity type shape) in the entity type shape to create a single/bidrectional self association. The self association is created and a dotted arrow line appears.

4.

Choose the Select

Icon in the Palette to come out of the association create mode.

Press escape from the keyboard to come out of the association create mode.

48

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

Note
A Navigation Property is automatically created for the new association. You can rename the navigation property by double clicking on it. Every navigation propery should have a unique name. 5. Select the association in the graphical editor. The properties of the association are displayed in the Properties view.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

2013 SAP AG or an SAP affiliate company. All rights reserved.

49

6. 7.

Click in the Value column for the Multiplicity to edit the multiplicity. Select a multiplicity and the OData Model Element displays the changes. The value for the Role of the association can also be edited in the Properties view.

Related Links

Creating a Single Association [page 44] Creating a Bidirectional Association [page 47] Instructions about how to create a bidirectional associations.

5.3

Saving the OData Model

Saving the OData model. Whenever a change is made in the OData Model Editor, the page title displays a star sign indicating that the Odata model needs to be saved.

50

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

On saving the OData model, if it contains any errors, an error icon is displayed next to the affected artifacts. The title tab also displays the star sign.

Note
The details of the errors can be seem in the Problems view.

5.4

Deleting OData Model Elements

Explains how to delete OData model elements in the OData Model Editor. To delete OData model elements, proceed as follows: 1. Click Delete from the context pad. 2. Press Delete from the keyboard. Right-click and select Delete in the resulting menu.

On selecting Delete, the Confirm Delete window appears.

Note

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

2013 SAP AG or an SAP affiliate company. All rights reserved.

51

On choosing to delete in the entity type OData model element, any existing Entity Sets/Associations will be also deleted. Ensure that the OData model element to be deleted is not being used in any OData model.

5.5

Layouting in OData Model Editor

Explains layouting for the OData model in the OData Model Editor. The OData Model Editor enables you to select and create your own layouts to view the OData model. The layouting can be used in the following scenarios: When importing the EDMX file When creating a model using the Service Metadata URL When viewing the services from the Service Catalog On active OData Model Editor with context menu

The Layouting options can be classified into two categories: Basic Layout - The basic layout provides basic layouting options and few of the advanced options will not be addressed, for example the objects will not overlap each other but the association will cross each other. See Basic LayoutBasic Layout [page 52] section for more information. But the user can create their own layout using the extension points. See Creating Layout Extensions, Creating a Custom Layout [page 57] for more information. Additional Layouts - The advanced layout options provides the user with more layout preferences. See Advanced Layout OptionsAdditional Layouts [page 54] for more information.

Related Links

Additional Layouts [page 54] This section will guide you to select different layouts to layout your OData model in the OData Model Editor.

5.5.1

Basic Layout

This section provides information on setting up the basic layout for your OData model in the OData model editor. The Basic layout provides the user with only one default option to layout the model in the OData model editor. But, you can create your own layout by using the extension points. See Creating a Custom Layout Creating a Custom Layout [page 57]for more information. 1. 2. From the Eclipse main menu, select Windows and then Preferences The Preferences page appears. Expand OData Development and choose OData Model Editor. The OData Model Editor Layout options opens in the details region and the Basic Layout is selected by default. Here is a sample of the basic layouting:

52

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

The basic layout avoids overlapping of the models and layouts the model in the following order: 1. 2. 3. 4. 5. Self associated entities and non-associated entitites. Associated entities Function Imports Complex Types Enum Types

Note
You can also select a layout by right clicking on the OData Model Editor and choosing Layout and selecting a layout of your choice from the context menu. If there are no extra layouts other than basic, then no additional layout(s) will be displayed.

3. 4.

Choose Apply to apply the layout for the OData Model Editor. Open the OData Model Editor to view the OData model in the selected layout.

Related Links

Additional Layouts [page 54] This section will guide you to select different layouts to layout your OData model in the OData Model Editor. Creating a Custom Layout [page 57]

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

2013 SAP AG or an SAP affiliate company. All rights reserved.

53

This section provides information on creating custom layout for the OData model.

5.5.2

Additional Layouts

This section will guide you to select different layouts to layout your OData model in the OData Model Editor. The additional layout preferences are if the SAP Framework is installed, the following additional layout options are available: Orthogonol Layout Incremental Hierarchic Layout Smart Organic Layout Layout Association Only ( only availble with the context menu in the OData Model Editor) See Basic Layout section for more information on basic layout options

Note
You can also create your own layouts using the extension points, refer section Creating Custom Layouts.

Orthogonal Layout
The orthogonal layout algorithm is based on the topology-shape-metrics approach and consists of three phases. In the first phase the edge crossings in the OData model editor are calculated. The second phase computes the bends in the model, in the third phase the final coordinates are determined. Here is a sample:

The layout algorithm is well suited for medium-sized sparse graphs. It produces compact drawings with no overlaps, few crossings, and few bends.

54

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

Incremental Hierarchical Layout


The Incremental hierarchical layout arrranges the OData elements in the main direction of flow within the OData model. The OData elements are hierarchically arranged to show the overall orientation, for example:

Smart Organic Layout


The smart organic layout style is based on the force-directed layout paradigm. When calculating a layout, the OData elements are considered to be physical objects with mutually repulsive forces. The connections between OData elements also follow the physical analogy and are considered to be springs attached to the pair of nodes. These springs produce repulsive or attractive forces between their end points if they are too short or too long. The layout algorithm simulates these physical forces and rearranges the positions of the nodes in such a way that the sum of the forces emitted by the nodes and the edges reaches a (local) minimum. Resulting layouts often expose the inherent symmetric and clustered structure of a service, they show a well-balanced distribution of associations and have few edge crossings.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

2013 SAP AG or an SAP affiliate company. All rights reserved.

55

Layout Association Only


The Layout Only Association option will arrange the OData elements in such way that the association do not overlap each other. Here is sample:

56

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

5.5.3

Creating a Custom Layout

This section provides information on creating custom layout for the OData model. The prerequisites to create custom layouts are: Create Plug-in project Create the Dependencies. Add dependency to "com.sap.odata.dt.framework.model.editor" plug-in Graphiti Graphiti.ui

This section will guide you to create your own layouts using the extension points in GWPA. When a plug-in wants to allow other plug-ins to extend or customize portions of its functionality, it will declare an extension point. The extension point declares a contract, typically a combination of XML markup and Java interfaces that extensions must conform to. Plug-ins that wants to connect to that extension point must implement that contract in their extension. The key attribute is that the plug-in being extended knows nothing about the plug-in that is connecting to it beyond the scope of that extension point contract. 1. 2. 3. 4. 5. 6. Create a plug-in project in GWPA. Choose the Extensions tab. The Extensions tab view opens. ClickAdd to to search and add an extension point. The Extension Point Selection window appears. Search for "com.sap.odata.dt.framework.model.editor.layout" extension point under All Extensions. Click Finish. The selected extension point is now added and will be available under All Extensions. Right-click the new extension point and choose New and then Layout.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

2013 SAP AG or an SAP affiliate company. All rights reserved.

57

The Extension Element Details opens for the new extension point. The Extension Element Details list the following fields: Table 6: Extensions Elements Fields id name class Entries Unique Identification String Display name of the layout Description This is a mandatory field This is a mandatory field

Layout class, which implements This is a mandatory field "com.sap.odata.dt.framework.mod el.editor.layout.ILayout" interface Setting the current layout as the default layout Choose True to set the layout as the default layout.Choose False if you do not want the layout to be the default layout.

isDefault

7. 8.

Create a class that implements the com.sap.odata.dt.framework.model.editor.layout.ILayout interface and define the custom layout implementation in the layout method. Save the settings and restart Eclipse. Now you can see the new layout added to the layout preferences in the Preferences window under Select a Layout. The context menu in the OData model editor will also display the custom layout in the Layout menu.

Related Links

58

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

Basic Layout [page 52] This section provides information on setting up the basic layout for your OData model in the OData model editor. Additional Layouts [page 54] This section will guide you to select different layouts to layout your OData model in the OData Model Editor.

5.6

Adding References to an OData Model

Adding EDMX references. Explains how to create an advanced OData model by adding the EDMX references to SAP NetWeaver Gateway Productivity Accelerator. The advantage of this function is that it reduces the effort of recreating similar OData models/artifacst and basically reuses the existing artifacts from the referenced schema. You need to create just one OData model in the OData Model Editor and add one or many references to it. Related Links

Adding EDMX References [page 59] Adding EDMX references to the OData model. Working with the Referenced Entity Type [page 64]

5.6.1

Adding EDMX References

Adding EDMX references to the OData model. This section will guide you to add EDMX references in the OData Model Editor. You will be able to add EDMX references only after creating an OData model. 1. Click the References tab located on the lower left end of OData Model Editor.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

2013 SAP AG or an SAP affiliate company. All rights reserved.

59

The References view appears.

Every OData model will have a set of edmx references assigned to it by default. Two commonly used default vocabularies, and another one is the core vocabulary on which these default vocabularies are dependent. These references can be removed using the Remove button if they are not be used in the OData Model, for example in an association etc.

60

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

Note
A confirmation message is displayed when attempting to delete the references: If the EDMX reference is already in use, an appropriate error message is displayed. 2. Click the Add Default button to restore the default EDMX references if they were removed. If you try to restore the available references then an error message displays:

3. 4.

Click Add to add a new reference. The Add EDMX Reference window appears. Follow one of the scenarios in the Add EDMX Reference window: Scenario 1 a) Select the Service URL radio button to import a edmx reference using its service URL. b) Enter the service url of the service and click GO. The service populates in the Service Details region.

Note
The Browse button will be disabled for Service URL selection.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

2013 SAP AG or an SAP affiliate company. All rights reserved.

61

Scenario 2 a) Select the Service Metadata File radio button to import a edmx reference file using the Browse button. b) Select a service and click Add. The service populates in the Service Details region.

Note
The Go button will be disabled for the Service Metadata File selection.

Note
The messages related to the import of the service will be displayed in the title region of the window. For example, "Service valid"

62

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

5. 6.

On successful addition of the service/OData Model, the service appears under the Referenced Schemas region. Expand the service and select the schema. The Schema Details view displays. You can create new aliases for different schemas for reuse schema as required.

7. 8.

Save the changes. Navigate to the OData Model tab. The palette now will have another OData model element "Referenced Entity Type" added under Objects, if the added reference points to an OData model and not an vocabulary and if the referenced model contains entity types . You can now use this entity referenced type in your models

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

2013 SAP AG or an SAP affiliate company. All rights reserved.

63

Note
If the referenced schema is removed, than the Referenced Entity Type will be automatically removed from the palette. Also, if the you have used the referenced entity type in you model, then the referenced schema will not get deleted until the referenced entity is deleted. Related Links

Working with the Referenced Entity Type [page 64]

5.6.2

Working with the Referenced Entity Type

As we saw in the Adding EDMX ReferencesAdding EDMX References [page 59], when a new edmx reference is added, it is immediately available in the GWPA Palette. This section will guide you to use this referenced entity type in your OData model. 1. Click and drag the referenced entiy type onto the editor from the palette or click on the entity type and click in the editor. The referenced entity type is now available on the editor. The Referenced Entity Type comes with a context pad, with the following options: a) Delete - Click to delete the model b) Add Entity Set - Click to add an entity set The referenced entity type's background color is grey, which vizually differentiates it from the other OData model elements. 3. 4. Drag and drop an entiy type and a referenced entity type onto the OData model editor. Choose single association either from the context menu or from the Palette from the entity type. You cannot create birectional association to the referenced entity types. Also the referenced entity types can only be the destination for an association.

2.

64

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

Related Links

Adding EDMX References [page 59] Adding EDMX references to the OData model.

5.7

Service Catalog

The Service Catalog feature allows you to view the metadata of an OData service in the SAP NetWeaver Gateway landscape, inside the OData Model Editor. You can browse and discover the OData services that are available in the SAP NetWeaver Gateway system. You define the connection settings to an SAP NetWeaver Gateway so that you can browse through the system for the OData services and acquaint yourself with their capabilities.

Note
At least one connection to an SAP NetWeaver Gateway system should be configured to view underlying service. Related Links

Viewing the Service Catalog [page 67] On adding a connection, you can now view the services available in the connected system using the Service Catalog.The metadata of the service will be converted to OData service and will be displayed in the graphical editor. Connection Settings: Service Catalog [page 65] Explains how to configure the connection to the SAP NetWeaver Gateway system to view the Service Catalog.

5.7.1

Connection Settings: Service Catalog

Explains how to configure the connection to the SAP NetWeaver Gateway system to view the Service Catalog. To create a connection to a SAP NetWeaver Gateway system proceed as follows: 1. 2. In the Eclipse, choose Window and then Preferences. The Preferences window appears. Expand SAP NetWeaver Gateway and choose Connections.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

2013 SAP AG or an SAP affiliate company. All rights reserved.

65

3. 4.

Click Add to add a connection. The Create SAP NetWeaver Gateway Connection window appears. Complete the authentication to add the system.

Related Links

Viewing the Service Catalog [page 67] On adding a connection, you can now view the services available in the connected system using the Service Catalog.The metadata of the service will be converted to OData service and will be displayed in the graphical editor.

5.7.2

Opening the Service Catalog

After configuring the connection settings to a host, such as, a specific SAP NetWeaver Gateway server, you can open the Service Catalog to explore the the OData services in the connected host. To open the Service Catalog: 1. From the Eclipse menu, select Window > Show View > Others > SAP NetWeaver Gateway .

66

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

2.

Select Service Catalog, and choose OK. The Service Catalog View displays.

5.7.3

Viewing the Service Catalog

On adding a connection, you can now view the services available in the connected system using the Service Catalog.The metadata of the service will be converted to OData service and will be displayed in the graphical editor. Atleast one connection to a SAP NetWeaver Gateway system should be configured to view underlying service. See Connection Settings: Service Catalog [page 65] section to create a connection to the SAP NetWeaver Gateway system. To view the service in the graphical editor proceed as follows: 1. 2. Choose Window Show View in the Eclipse screen. The Show View window appears. Expand SAP NetWeaver Gateway folder and double click on Service Catalog. The Service Catalog menu is now available in the Properties View, and the available connection(s) are displayed in the Service Catalog tab view.

3. 4.

Expand a connection to view the services under it. Either double click on a service or right click and select Open to open the service in the graphical editor.

Note
Any services that contain errors are indicated by a red cross sign and will not be displayed in the graphical editor.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

2013 SAP AG or an SAP affiliate company. All rights reserved.

67

The selected service opens in the OData Model Editor in the read only mode.

Actions
The following actions can be performed in the graphical editor: 1. 2. You can move the objects in the graphical editor. You can expand and collapse the sections in the objects. You cannot save the changes after the above actions. Related Links

Connection Settings: Service Catalog [page 65] Explains how to configure the connection to the SAP NetWeaver Gateway system to view the Service Catalog.

5.7.4

Browsing an OData Service

The Service Catalog view allows you to view and browse all the OData services that are available in each connected host, in a tree form. To view and browse the services in an SAP NetWeaver Gateway system: 1. Choose the SAP NetWeaver Gateway system to expand it and to view the list of OData services in the selected system.

Note
Services that are not properly formed are marked with a red cross icon. The services are sorted in alphabetical order. Alternatively, if you know a part of the name or the description of the service you want, you can search for it the search box containing, type filter text. 2. Expand a service to view its details, such as, the entity containers, entities, associations, function imports, for example. The following is a description of the entity icons within a service. The entity and its icon is availabe in a service depending on the presence of the entity in the service. Entity Icon
collection image navigation property image association image Schema image

Description
Denotes a collection entry in the selected service. Represents a navigation property entry. Represents an association entry. Represents schema for a service in the selected SAP NetWeaver Gateway system.

68

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

Entity Icon
well formed service image malformed service image key property image property image

Description
Represents a properly formed OData service in the selected SAP NetWeaver Gateway system. Represents a malformed OData service in the selected SAP NetWeaver Gateway system. Indicates a property entry as a key entry in the selected service. Represents a property entry in the service.

3.

Right-click a service to: Command


Open

Description
Select this option to open a read-only view of the modeled service, graphically or its XML based file, in the OData Model Editor. Alternatively, double click the service to view its modeled entities in the OData Model Editor.

Refresh Generate Service Proxy Generate Starter Application Import OData Model

Select this option to restore the connection to the selected SAP NetWeaver Gateway, or to get the updated metedata of the selected service. Select this option to generate a proxy for the selected service in order to use it with your custom application in the environment supported by a toolkit. Select this option to generate a starter application for the selected service in an environment supported by a toolkit. Select this option to create a new model based on the selected service.

5.7.5

Generating a Service Proxy

You can quickly generate a service proxy for use with your custom application based on the selected OData service in the Service Catalog view. To do so, proceed as follows: 1. 2. Open the Service Catalog, and locate the service you want. Right click the service, and choose Generate Service Proxy. The Service Proxy Generation wizard opens. If the service is not well formed, you cannot perform this step.

Note
There is no context menu for the entries under the selected service. 3. 4. 5. Click Browse to select the project in which to generate the proxy. From Create proxy for, select the target extension or toolkit for which you want to create the proxy, and specify the package name. Choose Next. The Location of OData Service page opens. The URL of the selected service is displays in Service URL, and the Service Details pane displays only the selected service and its entities. 6. Click Finish, to generate the proxy. If you choose Next, the SAP NetWeaver Gateway host and the URL of the selected service are provided.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

2013 SAP AG or an SAP affiliate company. All rights reserved.

69

5.7.6

Generating a Starter Application

You can quickly generate code for a starter application using the selected OData service in the Service Catalog view. To do so, proceed as follows: 1. 2. Open the Service Catalog, and browse to locate the service you want. Right click the service, and choose Generate Starter Application. The Starter Application wizard opens.

Note
If the service is not well formed, you cannot perform this step.

5.7.7

Importing an OData Model from Service Catalog

You can import an OData model for further editing to suit your needs. There are two ways to import an OData model into the OData Model Editor; directly using the Eclipse main menu, or by choosing the Import OData Model command from the submenu of a selected service in the Service Catalog. To do so: 1. 2. 3. 4. 5. Open the Service Catalog, and locate the service you want. Right-click the service, and choose Import OData Model. If the service is not well formed, you cannot perform this step. The Create New OData Model wizard opens. Click Browse to select the project in which to create the model. In Model name, enter a name for the new OData model. The Initial OData model content pane displays only the selected service and its entities. Click Finish, to create the OData model.

70

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Working with the OData Model Editor

6
6.1

Extensibility
Extensibility

SAP NetWeaver Gateway Productivity Accelerator offers extension points for creating your own custom extensions, including, templates for client applications to consume OData services, and extending the export functionality to support your own file format. The extensions that you create are added to and available in SAP NetWeaver Gateway Productivity Accelerator. Applications for SAP solutions, for example in Android, intended to run in different runtime environments can have patterns that you reuse many times. The SAP NetWeaver Gateway Productivity Accelerator allows application developers who want to provide SAP solutions for multiple environments (such as, PHP, HTML5, or Java), to generate code automatically for their specific target environment, and to develop their applications faster. The generated source code for a specified target environment can be customized according to the specific needs and purposes of the different business solutions. SAP NetWeaver Gateway Productivity Accelerator enables extensibility in the following ways: Implementing new templates You can create a new template as an extension of a template that describes the set of coding patterns that can be reused to generate code for applications that run in a specific target environment. SAP NetWeaver Gateway Productivity Accelerator provides its own extension point from which you derive new extension templates. The outcome of each new extension template is the generation of a template class with code for a fully-functional template for a starter application. Templates are customizable, as you can modify and customize the code generated for the template. Implementing new environments You can create a new environment as an extension of the environment of SAP NetWeaver Gateway Productivity Accelerator. Your new environment describes the target runtime platform (toolkit) for a generated application. The environment in which you generate code for an application must closely match the target runtime platform. SAP NetWeaver Gateway Productivity Accelerator supplies its own extension point from which you can derive new extensions for environments. Implementing new export formats for OData elements You can implement a custom export format for OData services that describes the set of coding patterns that can be reused to define your own custom export format for OData services in the framework. The framework offers its own extension point from which you derive a new extension for your custom export format. The outcome of each new extension is the generation of a class with code for a fully-functional custom export format.

6.2

Implementing a New Template

Templates are customizable, as you can modify and customize the code generated for the template.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Extensibility

2013 SAP AG or an SAP affiliate company. All rights reserved.

71

You create a new template by extending the specific extension point, com.sap.odata.dt.framework.template, supplied for templates in SAP NetWeaver Gateway Productivity Accelerator. Prerequisites Make sure that you have the following: A new plug-in project. The SAP NetWeaver Gateway Productivity Accelerator plug-in, com.sap.odata.dt.framework, on which your template is dependent. The file, Manifest.mf, or plug-in.xml, is available in your new plug-in project.

The following are the steps for creating a new template: 1. Add the plug-in for the framework as the required plug-in. a) Optionally create a new Plug-in Project in Java if you have not done so. b) Double click the file, Manifest.mf, in your new plug-in project. The Manifest Editor opens. c) Open the Dependency tab, and click Add under Required Plug-in. The Plug-in Selection dialog opens. d) In Select a Plug-in, enter the term, com.sap*, to search for all plug-ins containing the search term. e) Select the plug-in for the framework, com.sap. Starter Application wizard.framework, from the list and choose OK. 2. Create a new template class based on the required dependency plug-in a) Create a new Plug-in Project, if you have not done so. b) Double click the file, Manifest.mf, under META-INF in your new plug-in project. c) Open the Extensions tab, and click Add under All Extensions. The Extension Points Selection dialog displays a list of all the extensions points. d) In Extention Points filter, enter the term, *template, to search for all extension points containing the search term. e) Select the extension point, com.sap.odata.dt.framework.template, from the list and choose Finish. A new extension element with the same name as the extension point is created. f) Right click the new extension element, select New, and then specify the type of template (exists as child elements) you want. The following template types are available: Proxy: This template type allows you to generate code for an OData service proxy that interfaces with your own application, Service Proxy wizard. If you choose the Proxy child element, enter the required values for the attributes with asterisks: id: A unique ID for the template. Template: A fully qualified name of a class that will extend, com.sap.odata.dt.framework.template.<environment>, interface. environmentId: The identifier of an existing environment to be referenced by the new template. patternId: Optionally provide a pattern ID. It does not contain any value.

Starter Application: This template type allows you to generate code for a starter application for a target environment, such as, Android, Java, PHP and others, using the Starter Application wizard. If you choose the Starter Application child element, enter the required values for the attibutes with asterisks:

72

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Extensibility

id: A unique name that will be used to identify this template. Template: A fully qualified name of a class that will extend, com.sap.odata.dt.framework.template.<environment>, interface. environmentId: The identifier of an existing environment to be referenced by the new template.

Note
The environment implementation of the productivity accelerator plug-in determines access to the new template, as the template is available for selection in a specific environment. displayName: A translatable name that will be used for the template in the wizard. Enter a name for your template. description: Descriptive text that displays information about the new template in the wizard. Enter some text describes your template. icon: The path of a graphic file that will visually represent the template in the wizard. Enter the path to the image you want to use. patternId: It does not contain any value. Optionally, provide a pattern ID.

g) Click the attribute (it is a link to the new template class), Template, under Extension elements details. The New Java Class dialog opens. h) Enter a name for your template class. The Superclass points to the class within the framework that must be implemented. The selected modifier is Public, and the selected method stubs are constructors from the superclass and inherited abstract class. i) 3. Click Finish, and then click Save in the Eclipse main menu. Code is generated for the new template and a Java class is created with empty method subs.

Generate a Starter Application from a Your Custom Template You can create a fully functional starter application based on your new template for a specified target environment, as the new template is added to the Starter Application wizard of the framework. 1. 2. 3. To run and test your new template, select Run from the main menu and choose Run. Eclipse builds and runs the new template in a new instance of Eclipse. From the second instance, press ( Ctrl+N ), select OData Development and then select Starter Application Project wizard, specify the target toolkit (the environment for which you declared the new template). Provide the required entries for it, and then select your new template to generate a starter application.

6.3

Adding Code to Your Custom Template

The custom new template inherits an environment and a pattern from the productivity accelerator plug-in, which then saves them as private members. Some templates do not have a pattern, and so they can be null. You can cast the elements to their specific types in this method, or later in a different method, such as, onFinish(), for example.

Example

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Extensibility

2013 SAP AG or an SAP affiliate company. All rights reserved.

73

Example Code Snippets: Based on the Basic Starter Application template: /** * The template receives an environment and a pattern and a UI shell from the framework. <br> * <br> * Some templates don't have a pattern (can be null).<br> * <br> * Below is an example for a Java template:<br> * <br> * IJavaSeEnvironment javeSeEnvironment = (IJavaSeEnvironment) * this.context.get(TemplateConstants.ENVIRONMENT)<br> * Pattern pattern = (Pattern) this.context.get(TemplateConstants.PATTERN)<br> * Shell shell = (Shell) this.context.get(TemplateConstants.PATTERN)<br> * <br> * @param context - the given context. */ public void setContext(EnumMap<TemplateConstants, Object> context) { this.context = context; } public EnumMap<TemplateConstants, Object> getContext() { return context; }

Returns the template's wizard pages. Can return null. public List<IWizardPage> getWizardPages(); This method is responsible for the logic when you choose the Finish button. You can use the abilities of the environment and pattern models. public abstract void onFinish() throws TemplateException; Below is an example code that is based on the Java Basic starter application template: @Override public void onFinish(IProgressMonitor monitor) throws TemplateException { try { monitor.beginTask(generate Java Basic template, 6); /** * This method is responsible for the logic when any template error occurs.<br> * Here you can revert any changes done till now.<br> */ public void onError() { } Create new java project with client library jar this.javaSeEnvironment = this.context.get(TemplateConstants.ENVIRONMENT); this.javaSeEnvironment.createNewProject(new SubProgressMonitor(monitor, 1)); monitor.worked(1); Bundle bundle = Platform.getBundle(Activator.PLUGIN_ID); Path path = new Path("/templateDocs/custom/CustomDocument.vm"); //$NON-NLS-1$ EnumMap<JavaSeEnvConstants, Object> model = this.javeSeEnvironment.getModel(); String fileOutputPath = (String) model.get(JavaSeEnvConstants.PACKAGE_PATH); String mainClassJavaFile = (String)

74

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Extensibility

model.get(JavaSeEnvConstants.MAIN_CLASS_NAME); String javaPackage = (String) model.get(JavaSeEnvConstants.PACKAGE_NAME); Building an input model Map<String,Object> inputMap = new HashMap<String, Object>(); inputMap.put("package", javaPackage); //$NON-NLS-1$ inputMap.put("MAIN_CLASS", mainClassJavaFile); //$NON-NLS-1$ monitor.worked(1); Generating a basic Java file IFileGenerator generator = new FileGenerator(); String filePath = generator.generate(bundle, path, fileOutputPath + mainClassJavaFile + ".java", inputMap); //$NON-NLS-1$ monitor.worked(1); String projectName = (String) model.get(JavaSeEnvConstants.PROJECT_NAME); Refresh the generated project ProjectUtils.refreshProject(projectName); monitor.worked(1); Organize imports List<String> generatedFilesPathes = new ArrayList<String>(); generatedFilesPathes.add(filePath); ProjectUtils.organizeJavaImportsAndSave(projectName, generatedFilesPathes); monitor.worked(1); Opens the generated file ProjectUtils.openFile(projectName, filePath); monitor.worked(1); monitor.done(); } catch (FileGeneratorException e) { throw new TemplateException(e); } catch (EnvironmentException e) { throw new TemplateException(e); } catch (CoreException e) { throw new TemplateException(e); } }

6.4

Modifying an Existing Template

You can modify the templates provided in the toolkits for SAP NetWeaver Gateway Productivity Accelerator and save them as new templates for use in the wizard. The changes you make are visible at the runtime of the either the service proxy, or starter application project wizards, and the generated application on which you base the modified template. The following is the sequence of tasks for modifying a template: 1. You must create a new plug-in development project based on the template component for the specific toolkit you want to modify. 1. 2. From the Eclipse menu, choose File > Import. Expand Plug-in and Development in the Import Source, and choose Plug-ins and Fragments.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Extensibility

2013 SAP AG or an SAP affiliate company. All rights reserved.

75

3. 4.

Click Next, leave the default values and click Next. In ID, enter the search item for the template component of the toolkit you want to modify. For example,com.sap.odata.dtand click Add, and then click Finish. Eclipse creates a new plug-in project with the name of the selected template component.

2.

Rename the project for the imported template. You must rename the project created for the template component. This helps to avoid naming conflicts. 1. 2. Right click the project for the new template, and select Refactor > Rename. Change the name of the project, select Update references, and then click OK.

3.

Edit and run the template. You can modify the template to be displayed in the wizard, to show your custom specific logo, template name, description, and many more. In addition, you can change aspects of the template for rendering of the generated applications that are based on the modified template. 1. Expand the project for the template in the Package Explorer, and double click the file, Plugin.xml.

Recommendation
We recommend that you change the following: 2. Version: Specify your own version number. Provider: Specify your organization or company name. Name: Specify a name for the template

Choose the Extensions tab, and specify the following: ID: Change the identifier for the template, so that it can be presented in the list of templates of the wizard. The specified ID is already assigned. Template: Do not modfy the template value. environmentid: Do not modify the environment identifier value. displayName: Optionally, change the name of the template. The name you specify is presented as the name of the template in the wizard. icon: Optionally, change the icon for the template. The specified image is presented for the template in the wizard. Description: Optionally, change the description for the template. The descriptive text is presented for the template in the wizard. Patternid: Do not modify the pattern identifier.

3.

Click Save to save your changes. Restart Eclipse.

76

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Extensibility

6.5

Editing Your Custom Android Template

You can change the text, the labels, and the icons in the default template supplied with your toolkit. This section is an example, using the Toolkit for Android (GWPA), that comes with a set of default text, page, and icons for both the list view and the details view for each page. Below is example code that shows how to change the default icons for the Android template that is available in the Toolkit for Android (GWPA).

Note
The framework supports icons of 100 by 100 pixels in size. Add an AndroidIconsProvider class with the new icons, in the custom template you have implemented. public class AndroidIconsProvider extends IconsProvider { // list and details page images private static final String LIST_IMAGE_PATH = "res/images/list.png"; //$NON-NLS-1$ private static final String DETAILS_IMAGE_PATH = "res/images/details.png"; //$NONNLS-1$ private Bundle bundle; public AndroidIconsProvider() { this.bundle = Activator.getDefault().getBundle(); } @Override public Image getListIcon() { URL url = this.bundle.getEntry(LIST_IMAGE_PATH); ImageDescriptor imageDescriptor = ImageDescriptor.createFromURL(url); Image image = imageDescriptor.createImage(); return image; } @Override public Image getDetailsIcon() { URL url = this.bundle.getEntry(DETAILS_IMAGE_PATH); ImageDescriptor imageDescriptor = ImageDescriptor.createFromURL(url); Image image = imageDescriptor.createImage(); return image; } } Inside AndroidList class overrides the setContext method which passes the new icons from the template to the pattern. @Override public void setContext(EnumMap<TemplateConstants, Object> context) { super.setContext(context); if (context == null) { Logger.logWarning("AndroidList template will display default icons and texts because context argument is null."); return; } Object pattern = context.get(TemplateConstants.PATTERN); if (pattern == null) { Logger.logWarning("AndroidList template will display default icons and texts because ListPattern is null."); return; } if (pattern instanceof ListPattern)

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Extensibility

2013 SAP AG or an SAP affiliate company. All rights reserved.

77

ListPattern listpattern = (ListPattern) context.get(TemplateConstants.PATTERN); listpattern.setIconsProvider(new AndroidIconsProvider()); listpattern.setLabelsProvider(new AndroidLabelsProvider()); } else { Logger.logWarning("AndroidList template will display default icons and texts because pattern type is not instanceof ListPattern."); } }

6.6

Implementing a New Environment

An environment describes the target runtime platform (toolkit) for a generated application. The environment in which you generate code for an application must closely match the target runtime platform. The productivity accelerator plug-in offers a service proxy wizard and a starter application wizard. Both wizards can generate code for consuming an OData service in SAP NetWeaver Gateway. Since OData is platform-independent, such code can be written in any technology, such as Android, IOS, PHP and many more. These technologies are bundled as toolkits, wher each toolkit has its own environment. The productivity accelerator plug-in supplies its own extension point from which you can derive new extensions for the environments. You can create a new environment by extending the specific extension point, for example, com.sap.odata. dt.<toolkit name>.eclipse.framework.environment, available in the framework. The result of each new environment is the generated environment class file, which you can extend. The generated code for the environment class is commented and has placeholders for you to add your own code. When you create a new environment, it is added to the list of environment in the plug-in. Prerequisites Make sure that you have the following: 1. A plug-in project. The file, Manifest.mf, or plug-in.xml is available in your project. Create a new environment. 1. 2. 3. 4. 5. 6. 7. Create a new Plug-in Project if you have not done so. Double click the file, Manifest.mf, under META-INF in your new plug-in project. Open the Extensions tab, and click Add under All Extensions. The Extension Points Selection dialog displays a list of all the extensions points. In Extention Points filter, enter the term, *environment, to search for all extension points containing the search term. Select the extension point, com.sap.odata.dt.framework.environment, from the list and choose Finish. A new extension element with the same name as the extension point is created. Right click the new extension element, select New, and then choose Environment. Enter the required values for the attibutes with asterisks:

78

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Extensibility

Recommendation
We recommend that you save your changes after modifying the value of each attribute. 8. 9. ID: A unique ID for the environment. Environment: The path of the new environment class to be generated. displayName: A translatable name that will be used in UI representation of this environment in the wizard. description: Descriptive text for the new environment. icon: The path of a graphic file that will visually represent the environment in the wizard.

Click the attribute (a link to the new class), Environment. The New Java Class dialog opens. Enter a name for your Environment class. The superclass field contains the fully qualified name of the superclass. The extension point schema requires, that the class specified in the attribute, environment, inherits from a specific superclass.

10. Click Finish, and then click Save in the Eclipse main menu. Code is generated for implementing the new environment, and the new environment class is created with method subs. 2. Generate a Starter Application from the New Environment. You can create a fully functional starter application based on a template that references your new environment, as the new environment is added to the Starter Application Project wizard . 3. Generate a Proxy from a New Environment You can create a fully functional proxy based on your new environment, as the new environment is added to the Service Proxy wizard. 1. 2. To run and test your new environment, select Run from the main menu and choose Run. Open the Service Proxy wizard, select the target environment from the drop down box, provide the required entries, and then generate the service proxy.

6.7

Adding Code to the New Environment

The environment receives a template type; Proxy, or Starter Application. Based on this template type, it presents a corresponding user interface (UI) from the framework plug-in. Below is an example showing a method that creates a specific UI control for the environment. This method returns an environment UI that corresponds to the given template type. public EnvironmentUi createCompositeUI(TemplateType templateType) throws EnvironmentException From the Java Standard Edition Environment @Override public EnvironmentUi createCompositeUI(TemplateType templateType) throws EnvironmentException

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Extensibility

2013 SAP AG or an SAP affiliate company. All rights reserved.

79

{ {

switch(templateType)

case Proxy: this.envUi = new ProxyEnvironmentUi(); break; case Starter_Application: this.envUi = new StarterAppEnvironmentUi(); break; default: this.envUi = null; } return this.envUi; } Recommendation: Each environment will implement an interface, and only that interface will be exposed in the exported packages. From the IJavaSeModel interface: public interface IJavaSeModel { Returns the name of a project. public String getProject(); Returns the name of the main class of the project. public String getMainClass(); Returns the package name in the project. public String getPackage(); Returns the output path of the generated file. public String getOutputPath(); Creates a new project for a Java Starter Application template. public void createNewProject() throws EnvironmentException; Updates the project to a proxy project, by adding the Client library, .project and .classpath files. public void updateProxyProject() throws EnvironmentException; }

6.8

Implementing Custom Export Format for OData Models

A custom export format for OData models describes the set of coding patterns that can be reused to define your own custom export format for OData models in the productivity accelerator plug-in. Make sure that you have the following: A new plug-in project. The productivity accelerator plug-in on which your custom export format is dependent. See the details for the required plug-in in the section below. The file, Manifest.mf, or plug-in.xml, is available in your new project.

Using the Export wizard of the productivity accelerator, you can export OData models into an XML file suitable for a specifed version of the Common Shema Definition Language (CSDL):

80

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Extensibility

The productivity accelerator plug-in offers an extension point from which you can create a new extension for your custom export format. The outcome of each new extension is the generation of a class, in which you provide code for the specific implementation for a custom export format. You create a custom export format for adding support for latest versions of the CSDL, that you want to use. You create a new custom export format by extending the specific extension point, com.sap.odata.dt.framework.model.export.modelExport. The following is the sequence of steps for creating a new export format for a model: 1. Add the plug-in for the framework as required dependency plug-in. Before you create a new export format extension, you must specify the plug-in, com.sap.odata.dt.framework.model. The plug-in is required in the classpath of the project in order to compile. To define the required plug-in dependency: 1. 2. 3. 4. 5. 2. Optionally create a new Plug-in Project in Java if you have not done so. Double click the file, Manifest.mf, in your new plug-in project. The Manifest Editor opens. Open the Dependency tab, and click Add under Required Plug-in. The Plug-in Selection dialog opens. In Select a Plug-in, enter the term, *com.sap*, to search for all plug-ins containing the search term. Select the plug-in, com.sap.odata.dt.framework.model.export, from the list and choose OK.

Create the New Export Format Extension After adding the dependency plug-in, you can create a new export format extension that extends the extension point which is defined in the productivity accelerator plugin, (the equired plugin). To create the export format class 1. 2. 3. 4. 5. 6. Create a new Plug-in Project if you have not done so. Double click the file, Manifest.mf, under META-INF in your new plug-in project. Open the Extensions tab, and click Add under All Extensions. The Extension Points Selection dialog displays a list of all the extensions points. In Extention Points filter, enter the term, *export*, to search for all extension points containing the search term. Select the extension point, com.sap.odata.dt.framework.model.export.modelExport, from the list and choose Finish. A new extension element with the same name as the extension point is created. Double click the new extension element, and then specify the type of export format you want.

Recommendation
We recommend that you save your changes after modifying the value of each attribute. The following types are available: id: A unique name that will be used to identify this export format. displayName: A translatable name that will be used for the model export extension. It displays in the model export wizard. description: Descriptive text that displays information about the new model export extension in the wizard. It displays in the model export wizard when this export format is selected. ModelExportProvider: The Java class for ModelExportProvider. The specified class must implement the interface:

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Extensibility

2013 SAP AG or an SAP affiliate company. All rights reserved.

81

com.sap.odata.dt.framework.model.export.util.extensionpoint.IModelExportProvi der. 7. 8. 9. icon: The path of a graphic file that will visually represent the export format in the wizard. Click the attribute (a link to the class), ModelExportProvider, under Extension elements details. The New Java Class dialog opens. Enter a name for your ModelExportProvider class. The interface which has to be implemented has been added. Click Finish, and then click Save in the Eclipse main menu.

The following code (empty method subs) is generated for the new export model in the specified class: You must provide your implementation code. public class ModelExportProvider2 implements IModelExportProvider { public ModelExportProvider2() { // TODO Auto-generated constructor stub } @Override public void createFirstPageUI(Composite arg0, IModelExportFirstPage arg1) { // TODO Auto-generated method stub } @Override public String getPageDescription() { // TODO Auto-generated method stub return null; } @Override public List<IWizardPage> getPages() { // TODO Auto-generated method stub return null; } @Override public void performFinish(EDMXSet arg0) throws ModelExportException { // TODO Auto-generated method stub } } You must add your own code to implement your export format. The following is an example of existing code. It is based on the code used for testing this feature.: mport java.util.List; import public class ModelExportProviderTest implements IModelExportProvider { private Text text1; private Label label1; private Text text2; private Label label2; private Text text3; private Label label3; private IModelExportFirstPage wizardPage; public ModelExportProviderTest() { // TODO Auto-generated constructor stub } @Override public void performFinish(EDMXSet edmxSet) throws ModelExportException { // TODO Auto-generated method stub }

82

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Extensibility

@Override public void createFirstPageUI(Composite parent, IModelExportFirstPage wizardPage) { this.wizardPage = wizardPage; GridData gridData = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); gridData.grabExcessHorizontalSpace = true; parent.setLayoutData(gridData); // create label 01 this.label1 = new Label(parent, SWT.NONE); this.label1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); this.label1.setText("Label 01:"); // create text 01 this.text1 = new Text(parent, SWT.BORDER); this.text1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); // Set default text this.text1.setText("Text 01"); this.text1.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent arg0) { validatePage(); } } ); this.text1.notifyListeners(SWT.Modify, new Event()); GridLayout gridLayout2 = new GridLayout(2, false); gridLayout2.marginWidth = 0; parent.setLayout(gridLayout2); GridData gridData2 = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); gridData2.grabExcessHorizontalSpace = true; parent.setLayoutData(gridData2); // create label 02 this.label2 = new Label(parent, SWT.NONE); this.label2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); this.label2.setText("Label 02:"); // create text 02 this.text2 = new Text(parent, SWT.BORDER); this.text2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); // Set default text this.text2.setText("Text 02"); this.text2.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent arg0) { validatePage(); } } ); this.text2.notifyListeners(SWT.Modify, new Event()); GridLayout gridLayout3 = new GridLayout(2, false); gridLayout3.marginWidth = 0; parent.setLayout(gridLayout3); GridData gridData3 = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); gridData3.grabExcessHorizontalSpace = true; parent.setLayoutData(gridData3); // create label 03 this.label3 = new Label(parent, SWT.NONE);

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Extensibility

2013 SAP AG or an SAP affiliate company. All rights reserved.

83

this.label3.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); this.label3.setText("Label 03:"); // create text 03 this.text3 = new Text(parent, SWT.BORDER); this.text3.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); this.text3.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent arg0) { validatePage(); } } ); this.text3.notifyListeners(SWT.Modify, new Event()); } private void validatePage() { IStatus status = null; if (text1 == null || text1.getText() == null || text1.getText().isEmpty()) { status = new Status(IStatus.ERROR, "pluginId", "Fill Label 01"); } if (text2 == null || text2.isDisposed() || text2.getText() == null || text2.getText().isEmpty()) { status = new Status(IStatus.ERROR, "pluginId", "Fill Label 02"); } if (text3 == null || text3.isDisposed() || text3.getText() == null || text3.getText().isEmpty()) { status = new Status(IStatus.ERROR, "pluginId", "Fill Label 03"); } wizardPage.updateExtensionValidations(status); } @Override public List<IWizardPage> getPages() { return null; } @Override public String getPageDescription() { return "Test extension for export service model"; } } 3. Generating the New Export Format from Your Extension You can export OData models based on your new export format for a specified version of OData Common Schema Definition Language (CDSL) formats; as the new export format is added to the productivity accelerator. 1. 2. To run and test your new export model format, select Run from the main menu and choose Run. Open the export model of the framework, and then select your new export format.

84

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Extensibility

7
7.1

Service Implementation
Introduction to Service Implementation

The service implementation phase is a mandatory step in the development process that is required before you can use a new OData service to consume the data you defined in the OData model at design time. The service implementation phase requires ABAP knowledge and can be carried out using the Service Builder for SAP NetWeaver Gateway. You can define OData models in Eclipse using the OData Model Editor or directly in ABAP using the Service Builder. If you created the OData model in Eclipse, you can import the OData model definition file into the Service Builder.

From OData Model to Service Implementation


To implement a new OData service, you can have an OData model definition file that outlines the data structure to be used by the new OData service to retrieve data and let you consume it at runtime. Depending on your requirements, you can reuse (and change) an existing OData model from an existing OData service or create an entirely new one. You can create an OData model file in Eclipse using the OData Model Editor or, if you have ABAP development skills, you can use the Service Builder for SAP NetWeaver Gateway. If you have created the OData model using the graphical OData Model Editor in Eclipse, you can export your OData model definition file from the Eclipse plug-in and import this file into the Service Builder for the service implementation phase. Regardless of whether the OData model has been defined in the OData Model Editor in Eclipse or in the Service Builder in ABAP, the service implementation phase is identical. In the service implementation phase, an ABAP developer defines the runtime artifacts (for example, operations and methods) for the appropriate data provider class either by mapping operations to a data source or by generating the required ABAP classes for the OData model (code-based implementation). The generated ABAP classes are then used as a foundation on which the service is implemented. After the service has been implemented, the ABAP developer activates and registers the new OData service implementation in the relevant SAP NetWeaver Gateway systems. Related Links

Exporting an OData Model from the OData Model Editor [page 86] Use the Export OData Model wizard to export an OData model file, *.odata, from a project in the OData Model Editor, to an XML file. Later, you can use the exported file in another tool, such as, the SAP NetWeaver Gateway Service Builder to quickly implement an OData service from the model. Importing an OData Model to the Service Builder [page 87] In SAP NetWeaver Gateway Service Builder (using transaction SEGW), you can import XML and EDMX files into a project, and implement an OData service from the imported model. http://help.sap.com/saphelp_gateway20sp06/helpdata/en/56/d0cc05b564411e841141f68294e29f/ frameset.htm

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Implementation

2013 SAP AG or an SAP affiliate company. All rights reserved.

85

7.2

Exporting an OData Model from the OData Model Editor

Use the Export OData Model wizard to export an OData model file, *.odata, from a project in the OData Model Editor, to an XML file. Later, you can use the exported file in another tool, such as, the SAP NetWeaver Gateway Service Builder to quickly implement an OData service from the model. The export feature allows you to specify the supported XML format based on the version of the OData Common Schema Definition Language (CSDL) you want. The exported file can be in one of the following versions of CSDL:

Note
While SAP NetWeaver Gateway uses OData, the OData implementation in place is not a full implementation according to the official OData specification at http://www.odata.org. This restriction applies to all OData versions. OData V2 Select this option if you want the exported file to be saved in version two of OData CSDL. OData V2 for SAP Select this option if you want the exported file to be saved with SAP terms that are compliant with version two of OData CDSL. OData V3 Select this option if you want the exported file to be saved in the version three of OData CSDL.

Recommendation
We recommend that, first export the model file (*.odata) as an OData V2, or an OData V2 for SAP, before you import its XML file into Service Builder. In addition, the framework enables you to create and implement your own custom export functionality to save the exported file to your custom file formats. To export the OData model file, proceed as follows: 1. 2. 3. 4. 5. From the File menu, choose Export > Next. The Export Service Model window opens. OData Development > OData Model , and choose

In Model Name, choose Browse to select the specific *.odata file you want to export. If you have already selected the specific *.odata file, it is displayed with the full pathname. From Export Format, select the OData protocol version in which you want to save the file. The following are the supported formats, OData V2, OData V3, and OData V2 SAP-specific. In Export As, choose Browse to specify the folder in which you want to save the new file, and enter a name for the file. The file is saved as an XML file. Choose Finish to export the file.

Related Links

http://help.sap.com/saphelp_gateway20sp06/helpdata/en/56/d0cc05b564411e841141f68294e29f/ frameset.htm

86

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Implementation

7.3

Importing an OData Model to the Service Builder

In SAP NetWeaver Gateway Service Builder (using transaction SEGW), you can import XML and EDMX files into a project, and implement an OData service from the imported model. Make sure that you have the following: Exported and saved the OData model you want to use, as an XML file, in one of the supported versions of CSDL formats.

Recommendation
We recommend that, first export the model file (*.odata) as an OData V2, or an OData V2 SAP-specific, before you import its XML file into Service Builder. You have a project in Service Builder. You can choose to import the OData model file into a new project or into an existing project.

Note
You can export OData model files, *.odata, that have been created, modeled, and defined in SAP NetWeaver Gateway Productivity Accelerator as XML files. Later, you can import the XML file of the model into Service Builder. The entity entries in the imported model are organized into the relevant folders of the project in Service Builder. You can do the following in Service Builder: Edit the model and change its artifacts, or create new artifacts. Include a different OData service and create an Association. Import entities from other data sources to enhance the model. Generate, maintain and activate an OData service based on the model in the SAP NetWeaver Gateway host.

Related Links

http://help.sap.com/saphelp_gateway20sp06/helpdata/en/56/d0cc05b564411e841141f68294e29f/ frameset.htm

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Implementation

2013 SAP AG or an SAP affiliate company. All rights reserved.

87

Service Consumption

The service consumption toolkits in SAP NetWeaver Gateway Productivity Accelerator enable the easy and efficient consumption of data retrieved and published by OData services from your existing SAP systems. These features simplify the development process and increase the efficiency at which you can create and design applications that consume data on your chosen device or platform. Furthermore, they enable you to create code for your target environment in either an existing application or in an entirely new application. SAP NetWeaver Gateway Productivity Accelerator provides service consumption toolkits that enable you as a developer to create and design applications that consume the data retrieved from SAP systems using OData services. In this way, OData service enables you to create, update, and delete the data stored in your SAP systems without having to log onto the relevant systems. The toolkits allow for greater efficiency in the development process since they enable you to create code on the fly for your target environment. You can create code for existing applications or entirely new applications depending on your development needs.

Note
If you have created a new OData service, you must create a service implementation using the Service Builder for SAP NetWeaver Gateway and then activate and register your service in the relevant systems before you can use the toolkits to design applications for consumption devices. That is, service consumption is only possible for existing service implementations. Each consumption toolkit defines a specific target environment and provides the tools for generating code and working applications for that particular platform. To use the consumption toolkits, you must explicitly install the appropriate features for SAP NetWeaver Gateway Productivity Accelerator. That is, the tookit features are not included in your SAP NetWeaver Gateway Productivity Accelerator installation if you have previously only selected the OData Tools Core for SAP feature.

Consumption Toolkits
The consumption toolkits enable developers using Eclipse with SAP NetWeaver Gateway to: Browse, explore, and search OData services available in the Service Catalog for SAP NetWeaver Gateway Generate code (semantic proxies) for OData services created in SAP NetWeaver Gateway that can be used in new and existing applications Create and design starter applications based on OData services created using SAP NetWeaver Gateway

SAP NetWeaver Gateway Productivity Accelerator provides the following toolkits, listed here in alphabetical order, for your convenience: OData Toolkit for Java Platform, Standard Edition Toolkit for Android (GWPA) Toolkit for HTML5 (GWPA) Toolkit for iOS (GWPA) Toolkit for PHP (GWPA)

88

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

Extensibility
To cater for your wider needs, SAP NetWeaver Gateway Productivity Accelerator supports extensibility and empowers you to create your own toolkit to create a generated application for a new and existing environments based on the patterns List/Details, Workflow, Exploration, and Form. For example, you might want to add additional templates to an existing environment. To facilitate this, it provides extension points so you can create custom templates as extensions that are added to the tools and wizards. Application developers who need to provide SAP solutions for multiple environments (consumption devices) can use SAP NetWeaver Gateway Productivity Accelerator to generate source code automatically and thereby develop new consuming applications quickly and simply. You can modify the generated source code according to the specific needs and purposes of different business solutions.

Note
The generated code contains comments which explain what is being done or what needs to be done.

Working with the Toolkits


The installation and use of the service consumption toolkits is optional. To use them, you must install the corresponding features for SAP NetWeaver Gateway Productivity Accelerator. That is, the toolkits are not included in the minimum installation of SAP NetWeaver Gateway Productivity Accelerator if you have previously only installed the OData Tools Core for SAP feature. OData Toolkit for Java Platform, Standard Edition The OData Toolkit for Java Platform, Standard Edition is for developing SAP solutions and client applications (to run on the Java platform) that interface with OData services in SAP NetWeaver Gateway. Toolkit for Android (GWPA) The Toolkit for Android (GWPA) consists of an environment, a pattern and templates, suitable for developing SAP solutions for use in the Android environment. Toolkit for HTML5 (GWPA) The Toolkit for HTML5 (GWPA) is a collection of environments, patterns and templates, suitable for developing SAP solutions for use in any browser environment that supports HTML5 protocol (SAPUI5 and JQuery) including browsers on mobile devices. Toolkit for iOS (GWPA) The Toolkit for iOS (GWPA) enables you to create starter kit applications easily and quickly that consume OData services for the iPhone and iPad devices which can retrieve data from your existing SAP systems. You can then take the generated code and extend it to support your needs. Toolkit for PHP (GWPA) The Toolkit for PHP (GWPA) is a collection of environment, pattern and a template, which are suitable for developing SAP solutions and applications for PHP.

Packaging your custom environment and its associated templates together, you create a custom toolkit through the extensible processing system of the framework. When you make your custom toolkit available to other developers, they can use it to develop and deliver SAP solutions and applications in the specifc target environment. Related Links

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

89

https://help.hana.ondemand.com/gateway_gwpa/pdf/ SAP_NetWeaver_Gateway_Productivity_Accelerator_Inst_Guide_en.pdf

8.1

OData Toolkit for Java Platform, Standard Edition

The OData Toolkit for Java Platform, Standard Edition (Java SE) is for developing and delivering SAP solutions and client applications that interface with OData services in the SAP NetWeaver Gateway for use on the Java platform.

8.1.1

Generating a JAVA SE Starter Application

You can create a Java SE starter application that calls an existing OData service in SAP NetWeaver Gateway. Using the Starter Application Project wizard, you generate code into the new Java SE project that you specify.

Note
Using the Java SE toolkit, you can only generate code for a basic application. To create your application: 1. 2. 3. 4. 5. 6. From the File menu, choose New > Other > SAP NetWeaver Gateway , or from the keyboard press CTRL +N, and select Starter Application Project. The New wizard dialog displays. Enter a new name for your project. The project and the relevant resources will be created for only your application. For example, SAPCRMCONTACTJSE. From Create new project for, select Java SE. A pane for specifying the details of the application as required by the selected toolkit opens. Specify a name for the Package and the Main class. Choose Next. The page for the templates for the supported toolkit displays. Custom Application template is the only template available for your Java SE application. Click Finish to generate the code.

8.1.1.1

Generated Basic Application

A Java class file is created using the package name you have defined. Use the basic application template to familiarize yourself with writing code that calls the OData Java library provided with the framework, to consume OData services in an SAP NetWeaver Gateway system. The generated project consists of the following: SRC folder

90

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

This folder contains the specified package with a Java file that contains the main() method for calling and initiating the Java library JRE system library Contains the Java Platform, Standard Edition library components. LIB folder Contains the SAP NetWeaver Gateway Java library component.

8.1.1.2

Extending the Generated Basic Application

Use the generated basic application to develop your own application using the Java library API to call SAP NetWeaver Gateway. The following is an example of how to use the generated basic application. First, determine the business scenario for your application. For example, your application will do the following: Enable users to search for flights from one location to another. Users should be able to get details about a flight, such as, city of origin, destination city, departure date, and arrival date.

The following is an example code that calls the OData Java library to consume the OData service, RMTSAMPLEFLIGHT in an SAP NetWeaver Gateway server: Creating the request URL. String requestUrl = "/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/CarrierCollection (carrid='" + carrid + "')"; Defining Gateway connection settings. IServerConnectionParameters gateway = new ServerConnectionParameters ("<host>", "<port>","<client_id>", <useSSL>); Create the authentication object. The example below shows basic authentication implementation. IAuthentication credentials = new UsernamePasswordCredentials("<user>","<password>");

Note
You must replace <user>, <password> with the appropriate values. You can add your own interceptors and authentication implementation. Initializing the REST client based on the connection details. The following are the option for setting the representation: ATOM, or JSON. IRestClient restClient = RestClientFactory.createInstance(gateway, credentials, Representation.ATOM);

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

91

Executing the request. IRestRequest request = new RestRequest(requestUrl); IRestResponse response = restClient.execute(request); return response.getBody();

Example code for parsing returned response. Parsing the response string XML into an ODataEntry object. ODataEntry carrierEntry = ODataParserFactory.createInstance(Representation.ATOM).parseODataEntry(response);

Getting the carrier properties and printing to the standard output. ODataProperty[] properties = entry.getProperties(); for (ODataProperty oDataProperty : properties) { System.out.println(oDataProperty.getName() + ": " + oDataProperty.getValue()); } .

Example code for using a function import: GetAvailableFlights Create the request URL. String requestUrl = "/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/GetAvailableFlights? cityfrom=" + cityFrom + "&cityto=" + cityTo + "&fromdate=" + fromDate + "&todate=" + toDate;

Defining Gateway connection details. IServerConnectionParameters gateway = new ServerConnectionParameters ("<host>", "<port>","<client_id>", <useSSL>);

Initializing the REST client based on the connection settings. IRestClient restClient = RestClientFactory.createInstance(gateway, credentials,Representation.ATOM); IAuthentication credentials = new UsernamePasswordCredentials("<user>","<password>");

Calling the SAP NetWeaver Gateway server. IRestRequest request = new RestRequest(requestUrl); IRestResponse response = restClient.execute(request); return response.getBody(); }

8.1.2

Generating Proxy for Java SE

You can create a proxy for a supported toolkit to call OData services in your SAP NetWeaver Gateway server. The proxy provides the implementation interfaces for the OData service you choose to use. You can create your own application to interface with the generated proxy, or you can create a starter application based on the Basic Application template to interface with the generated proxy. Requirements Make sure that you have a project for the toolkit (target environment) in which you want to generate the proxy. You get a warning message when you attempt to generate code for an environment that is different from the target environment of the selected project.

92

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

To create your proxy: 1. 2. 3. 4. 5. 6. 7. From the File menu, choose New > Other > SAP NetWeaver Gateway , or from the keyboard press CTRL +N, and then select Service Proxy. The New wizard dialog displays. From Create new proxy for, selected Java SE. Select an existing project for the toolkit for which you want to create the proxy. Depending the properties of the environment for the selected toolkit, you can generate the code into a project or a folder in the file system. Specify the Package name. You can use the default package option without specifying a package name Choose Next. The page for specifying the OData services you want your application to call displays. Select Remote location, to connect to your SAP NetWeaver Gateway server within the network. Click Catalog to search for the specific OData services. The exploration dialog opens for you to search for the service. When you click Catalog, without providing a specific URL, the specified default SAP NetWeaver Gateway is automatically selected. If you have not saved the password of the default SAP NetWeaver Gateway, a popup displays requesting the password. Alternatively, select File system , and click Browse to specify the paths to both the service metadata document for the specific service, and the service document in your file system. If the specified URL of the service metadata comes from the Service Catalog, both the connection and the metadata document is verified. The Validate button is available only if you have manually entered the URL, or selected the metadata file from the file system.

8.

Choose Finish. The proxy wizard generates code for the selected target environment into the specified Eclipse project. In addition, it automatically creates class files for the selected OData service. The number of files created depends on the number of entities in the selected OData service.

8.1.2.1

Using the Generated Proxy for Java SE

Below is an example of the contents generated for the OData service, RMTSAMPLEFLIGHTService. The generated proxy consists of the following: SRC folder This folder contains the proxy classes for the selected OData service. JRE system library Contains the Java Platform, Standard Edition library components. LIB folder Contains the SAP NetWeaver Gateway Java library component. You can call the generated proxy classes from your application to interface with the selected OData services through the specified SAP NetWeaver Gateway server.

Note that, you have to create your own user interface for rendering your application. The following is an example of a class with a main method that calls the generated classes and methods for the OData service, RMTSAMPLEFLIGHTService. Each line in the example has comments to help you understand the expected process: Initialize the service REST Client IServerConnectionParameters serverConnectionDetails = new ServerConnectionParameters("<host>", "<port>", "<client>", <useSSL>);

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

93

IAuthentication authentication = new UsernamePasswordCredentials("<username>", "<password>"); IRestClient client = RestClientFactory.createInstance(serverConnectionDetails, authentication, Representation.ATOM); Create an instance of the service. RMTSAMPLEFLIGHTService proxy = new RMTSAMPLEFLIGHTService(client); Filter flight collection according to airline. List<Flight> flightCollection = service.getFlightCollection("$filter=carrid eq 'AA'"); System.out.println("Number of flights in the collection: " + flightCollection.size()); Create a booking object and provide the details of the booking information for a specific flight of the carrier. Date fldate = m_ISO8601Local.parse("2012-01-25T00:00:00"); Booking booking = new Booking(AA, 0017, fldate, 0, proxy ); booking.setCUSTOMID("00004617"); booking.setCOUNTER("00000000"); booking.setAGENCYNUM("00000325"); booking.setPASSNAME("Example Passenger Name1"); Create a new booking entry in the booking collection for a specific flight. It returns the newly created booking in Gateway with additional information, for example, the booking ID, and prints the booking ID of the newly created booking entry. Booking booking2 = service.createBookingCollectionEntry(booking); System.out.println("success:booking id: " + booking2.getbookid()); Update an entry: You can change a booking entry; update the booking entry object, for example, by providing a new passenger name and calling to Gateway to update the booking entry. If successful, it reads the booking entry from Gateway and prints the updated entry, passenger name booking2.setPASSNAME("Example Passenger Name2"); boolean updateSuccess = service.updateBookingCollectionEntry(booking2); if (updateSuccess) { Booking booking3 = service.getBookingCollectionEntry(booking2.getcarrid(), booking2.getconnid(), booking2.getfldate(), booking2.getbookid()); System.out.println("booking3: " + booking3.getPASSNAME()); Delete an entry: You can delete the booking entry you created and print the status. boolean deletedSuccess = service.deleteBookingCollectionEntry(booking3.getcarrid(), booking3.getconnid(), booking3.getfldate(), booking3.getbookid()); if (deletedSuccess) { System.out.println("Deleted"); } } Read: Read the booking collection of the specific flight (navigation property) and print all the passenger names. List<Booking> bookingCollection = service.getFlightCollectionEntry(booking.getcarrid(), booking.getconnid(), fldate).flightBookings(); for (Booking bookingEntry : bookingCollection) {

94

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

System.out.println("Passenger name - " + bookingEntry.getPASSNAME()); } Function import: Example for using the flight service specific method to get flights between specific dates and destination DateFormat formatter = new SimpleDateFormat("yyyyMMdd"); Date date = formatter.parse("20110420"); List<Flight> availableFlights = proxy.GetAvailableFlights(date, date, "NEW YORK", "SAN FRANCISCO"); System.out.println(availableFlights.size()); } catch (ProxyException e) { System.out.println(e.getMessage()); } Below is an example code for getting media links, based on the Gateway service, Workflow, which is different from the service used in the example above. It obtains a list of workflow tasks from the Gateway server. List<WorkflowTask> taskList = service.getWorkflowTaskCollection(); Obtains a specific attachment. This comes from the first task item in the list, and gets its attachment. Attachment taskAttachment = taskList.get(1).Attachments().get(1); Gets the mime type of the attachment. String taskAttachmentMimeType = taskAttachment.getMimeType(); Obtains the byte buffer (a fixed-capacity buffer that holds byte values) of the media resource byte[] bytes = service.getMediaResourceBytes(taskAttachment.getMediaResource()); Add your own code to use the media resource to suit your needs. For example, if the mime type is a GIF, then write the byte buffer to a file with the GIF suffix.

Using the Expand System Query Option ($expand)


Below is an example code for getting an entry's navigation property expanded:

Example
Get the flight collection with the expand system query option for the related bookings of each flight List<Flight> flightCollection = service.getFlightCollection("$top=1& $expand=flightBookings"); Get the related bookings of the flight List<Booking> flightBookings = flight.flightBookings();

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

95

Error and Exception handling in the Proxy


In your application, you should perform error handling and exceptions thrown by the proxy, (ProxyException), to suit your needs. For example, using the code above, you can display an error message such as: } catch (ProxyException e) { System.out.println(e.getMessage()); } Displayed as: Booking AA 00002161 has already been canceled

Running your JAVA SE Application


You can run and test the generated Java SE application in Eclipse just as you run any Java application created in Eclipse. .

Java SE Application Security


The framework automatically enables your application to make requests that include a challenge token, and ensures that the requests from your application are not coming from another source other than the user. Java SE Application Support for Cross Site Request Forgery Protection OData services are protected against Cross-Site Request Forgery (XCSRF) attacks. This protection mechanism appends challenge tokens to each request and associates them with each users session. Each token is unique per user session, and per request. All OData services that are compatible with OData library version 1.0 and above are protected and require XCSRF tokens. Some services that are compatible with OData library 0.2 also require these tokens. You can disable the protection using CSRF tokens, by implementing your custom code.

8.1.3

Introduction to the OData Java Client Library

The OData Java Client Library supplies a set of APIs and classes that handle the connectivity and processing of OData for SAP solutions on top of SAP NetWeaver Gateway. The OData Java Client Library comes with a set of APIs, interfaces, and classes for connecting to SAP NetWeaver Gateway and proocessing of OData for SAP solution. The library parses OData content and fills the appropriate objects with values. The library provides APIs for:

96

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

Connecting to an SAP NetWeaver Gateway system. It provides APIs of HTTP client for RESTful calls to an SAP NetWeaver Gateway system, supporting HTTP GET, POST, PUT and DELETE methods. In addition, it supports basic authentication over secure sockets layer (SSL). Parsing of OData elements as well as APIs for the construction of XML strings from OData elements encapsulated in an SAP Data Helper class.

To use the OData Java Client Library, you prepare the content of your request in your own application, or one that you have generated in the framework, that creates an OData entry. Then, you call the SAP Data Helper to convert the request to an ODataEntry XML text in the SAP format. The library also simplifies sending requests to SAP NetWeaver Gateway by providing APIs for creating the request content, sending it and parsing the response into Java entities. To send a request to an OData services, first make a connection to a specific SAP NetWeaver Gateway, and then set the feed or entry object. You call a library method to convert the object into XML and send it.

8.1.3.1

Getting Started

The following examples show how to use the various APIs in the OData Java Library to interact with OData services. In addition, the examples provide sample code showing how to use the library. To get started, you can create a custom application using the Starter Application Project wizard of the SAP NetWeaver Gateway Productivity Accelerator. This generates the library into your project. You must provide the appropriate authentication.

Example
The following is an overview for using the library: First, send a request to connect to an SAP NetWeaver Gateway host in which the OData service you want to call is available. For example: IGatewayConfiguration gateway = new GatewayConfiguration("<host>", "<port>", "", "<user>", "<password>", false); You must replace <host>, <port>, <user>, <password> with the appropriate values. Initialize the REST client based on the SAP NetWeaver Gateway connection details. RestClient restClient = new RestClient(gateway); Obtain the response from the connected SAP NetWeaver Gateway host about the OData service. String response = restClient.get("<collection>"); Where <collection> is the name of the OData service you to call. For instance, /sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/GetAvailableFlights

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

97

Transform the XML response into an ODataCollection object. ODataCollection collecion = ODataUtil.parseODataCollection(response); Extract the properties from the ODataCollection object. ODataEntry[] entries = collecion.getEntries(); for (int i = 0; i < entries.length; i++) { ODataEntry entry = entries[i]; String stringDataValue = entry.getProperty("<property name>"); System.out.println(stringDataValue); } } catch (RestClientException e)

8.1.3.2

Calling an OData service

After setting the connection and authentication, you use the RestService API class to form an HTTP request for the specific OData service.

Example
For example, to call an OData service called, RMTSAMPLEFLIGHT. You must provide the URI of the service. Initialize the REST client based on the connection details. RestClient restClient = new RestClient(gateway); Optionally, add a custom header. restClient.addHeader("<header>","<value>"); } Call Gateway. String response = restClient.get("/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/ FlightCollection");. getInstance(); Parse the string XML response into an ODataCollection object. ODataCollection collection = ODataUtil.parseODataCollection(response); Loop over the atom entries in the feed. ODataEntry[] entries = collection.getEntries(); for (int i = 0; i < collection.length; i++) { ODataEntry entry = collection[i]; String stringDataValue = entry.getProperty("<property name>"); System.out.println(stringDataValue); } }

98

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

catch (RestClientException e) { To call an SAP NetWeaver Gateway service, proceed as follows: 1. 2. 3. 4. Indicate to the Java library to call and use the RestClient class to obtain the response string from the OData service. Parse the response into Java objects. Call a method to send the request and receive the results. Handle errors and exceptions. The following is an example for updating data in your SAP backend system through SAP NetWeaver Gateway: /* * Code example for updating data (PUT) through SAP NetWeaver Gateway * @param entry with updated data * @throws MarshalerException * @throws RestClientException */ private static void updateExample(ODataEntry entry) throws MarshalerException, RestClientException { //update something entry. putProperty("PASSNAME", "John Smith"); //Convert to XML String body = ODataUtil.format(entry); //Call Gateway The following is an example for creating new data in your SAP backend system through SAP NetWeaver Gateway: /** Example code for CREATING new data (POST) through *SAP NetWeaver Gateway in the SAP backend system. */ private static ODataEntry createExample() throws MarshalerException, RestClientException, ParserException { //Create HashMap object HashMap<String, String> propertiesHashMap = new HashMap<String, String>(); //Add key value pairs to HashMap propertiesHashMap.put("carrid","AA"); propertiesHashMap.put("connid","0017"); propertiesHashMap.put("fldate","20120125"); propertiesHashMap.put("CUSTOMID","00004617"); propertiesHashMap.put("COUNTER","00000000"); propertiesHashMap.put("AGENCYNUM","00000325"); propertiesHashMap.put("PASSNAME","Joe Smith"); // Create an entry ODataEntry atomEntry = createAtomEntry(propertiesHashMap); //Convert to xml string String body = ODataUtil.format(atomEntry); //Call Gateway String responseString = restClient.post("/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/ BookingCollection", body); System.out.println(responseString); //Parse the response XML string from Gateway ODataEntry newEntry = ODataUtil.parseODataEntry(responseString); return newEntry; }

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

99

8.1.3.3

OData Java Library API Reference

The API reference section provides detailed descriptions of the packages, classes, methods and working code examples for the classes, and interfaces. Below are the OData Java Library APIs:

Package Index
Packages Description com.sap.nw.gateway.odata.client.connectivity.api,

com.sap.nw.gateway.odata.client.connectivity.ap The package, i

provides classes and interfaces for calling an SAP NetWeaver Gateway host.

com.sap.nw.gateway.odata.client.connectivity.im The package, pl

com.sap.nw.gateway.odata.client.connectivity.impl

, provides classes and interfaces for implementing connectivity to an SAP NetWeaver Gateway host.

com.sap.nw.gateway.odata.client.connectivity.int The package, erceptors

com.sap.nw.gateway.odata.client.connectivity.inter ceptors, provides classes and interfaces for intercepting calls to an

SAP NetWeaver Gateway host com.sap.nw.gateway.odata.client.connectivity.se The package, curity

com.sap.nw.gateway.odata.client.connectivity.secur ity, provides classes and interfaces for security calls to an SAP

NetWeaver Gateway host com.sap.nw.gateway.odata.client.connectivity.va The package, lidators

com.sap.nw.gateway.odata.client.connectivity.valid ators, provides classes and interfaces for validating calls to an SAP

NetWeaver Gateway host com.sap.nw.gateway.odata.client.exceptions The package,

com.sap.nw.gateway.odata.client.exceptions, provides
classes and interfaces for exception calls. The package,

com.sap.nw.gateway.odata.client.jsonsimple

com.sap.nw.gateway.odata.client.exceptions, provides
classes and interfaces for JSON client calls. The package,

com.sap.nw.gateway.odata.client.jsonsimple.par ser com.sap.nw.gateway.odata.client.nls.messages

com.sap.nw.gateway.odata.client.exceptions, provides
classes and interfaces for parsing JSON calls. The package,

com.sap.nw.gateway.odata.client.nls.messages,
provides classes and interfaces for handling messages. The package,

com.sap.nw.gateway.odata.client.odatamodel.at om

com.sap.nw.gateway.odata.client.odatamodel.atom,
provides classes and interfaces for ATOMPUB client calls.

100

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

Packages
com.sap.nw.gateway.odata.client.odatamodel.at om.sap

Description
The package,

com.sap.nw.gateway.odata.client.odatamodel.atom.sa p, provides classes and interfaces for calling ATOMPUB elements


provided by SAP.

com.sap.nw.gateway.odata.client.odatamodel.ed The package, mx

com.sap.nw.gateway.odata.client.odatamodel.edmx,

provides classes and interfaces for calling entity data models entries.

com.sap.nw.gateway.odata.client.odatamodel.ed The package, mx.v3

com.sap.nw.gateway.odata.client.odatamodel.edmx.v3

, provides classes and interfaces for calling entity data model entries that conform to version 3 of the OData Common Schema Defintion Language (CSDL).

com.sap.nw.gateway.odata.client.odatamodel.ed The package, mx.v3.expressions

com.sap.nw.gateway.odata.client.odatamodel.edmx.v3 .expressions, provides classes and interfaces for calling entity data

model entries that conform to version 3 of the CSDL expressions. com.sap.nw.gateway.odata.client.odatamodel.ed The package, mx.v3.expressions.primitive

com.sap.nw.gateway.odata.client.odatamodel.edmx.v3 .expressions.primitive , provides classes and interfaces for

calling entity data model entries that conform to version 3 of the CSDL primitive types. com.sap.nw.gateway.odata.client.odatamodel.ge neric The package,

com.sap.nw.gateway.odata.client.odatamodel.generic
, provides classes and interfaces for calling SAP supplied OData elements. The package,

com.sap.nw.gateway.odata.client.odatamodel.ge neric.v3

com.sap.nw.gateway.odata.client.odatamodel.generic .v3, provides classes and interfaces for calling SAP supplied OData
elements that conform to version of CDSL.

com.sap.nw.gateway.odata.client.odatamodel.jso The package, n com.sap.nw.gateway.odata.client.parser

com.sap.nw.gateway.odata.client.odatamodel.json,

provides classes and interfaces for implementing JSON formats. The package, com.sap.nw.gateway.odata.client.parser, provides classes and interfaces for parsing OData elements. The package,

com.sap.nw.gateway.odata.client.parser.impl

com.sap.nw.gateway.odata.client.exceptions, provides
classes and interfaces for exception calls.

com.sap.nw.gateway.odata.client.parser.impl.util The package,

com.sap.nw.gateway.odata.client.parser.impl.util,

provides classes and interfaces for utility that implements the parsing. com.sap.nw.gateway.odata.client.parser.impl.v3 The package,

com.sap.nw.gateway.odata.client.parser.impl.v3,
provides classes and interfaces for implementing version of the CDSL. The package,

com.sap.nw.gateway.odata.client.parser.util

com.sap.nw.gateway.odata.client.parser.util, provides
classes and interfaces for a utility that implements the parsing.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

101

Packages
com.sap.nw.gateway.odata.client.proxy.helper

Description
The package,

com.sap.nw.gateway.odata.client.proxy.helper,
provides classes and interfaces for calling the service proxy. The package, com.sap.nw.gateway.odata.client.uti, provides classes and interfaces for a utility that implements the APIs.

com.sap.nw.gateway.odata.client.util

For detailed information about the APIs, see the Javadocs.

8.1.4 Troubleshooting for the OData Toolkit for Java Platform, Standard Edition

Network Connections
Issue When Eclipse is configured to use native active provider in Network Connections, you cannot use short host name, such as, vmw.example.com. Eclipse attempts to connect through the proxy, even if the server is configured in the bypass list in Windows.

Solution Either use the fully qualified domain name (FQDN) of the SAP NetWeaver Gateway server, or configure the Network Connections as follows: 1. 2. 3. From the Eclipse menu, go to Window Preferences General Network Connections .

Select Manual in the Active Provider. In the proxy entries table, select Add Host and provide the SAP NetWeaver Gateway server details, including the host name, port, username and password.

Starter Application Wizard Template Error


Issue: When you choose to create a new starter application for the Java SE environment, after providing the entries for your application, you can go back to switch to creating a PHP application, however, the wizard presents you with the Finish option. Selecting Finish results in an error. Solution Do not choose Finish at this point as the wizard requires you to specify the entries for the List/Details Application template.

102

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

Service Proxy Generation Errors


Issue Some OData services may contain entities, complex types, or fields that are similar to Java reserved keywords, such as, return, class, public, and many more. When the Proxy Generation wizard comes across these occurrences, it creates proxy files with incorrect content, such as, return as the entity type name and abc-dfg as a property name. Solution After the proxy is generated, manually fix the compilation errors by renaming the generated code to use legal Java names. For example, return1, class1, public1.

8.2

Toolkit for Android (GWPA)

Toolkit for service consumption for Android platform. The Toolkit for Android (GWPA) consists of an environment, a pattern and templates, suitable for developing SAP solutions for use in the Android environment. Related Links

https://help.hana.ondemand.com/gateway_gwpa/pdf/ SAP_NetWeaver_Gateway_Productivity_Accelerator_Inst_Guide_en.pdf

8.2.1

Creating a Starter Application Project for Android

You can create a starter application for an Andriod device based on one of the following templates: A List/Details Starter Application Generates a starter application for utilizing SAP data in list and details screens. A Basic Starter Application Generates a starter application for consuming the SAP NetWeaver Gateway service. The generated application has a sample UI view, and contains a semantic proxy and a Request Handler that is responsible for the Gateway connectivity and parsing of the service data. . A Workflow Starter Application Generates a starter application which displays the Workflow task information and allows the user to make a decision on the task. The templates of the starter application provide a best-practice for creating a business-scenario application. In addition, the starter application wizard generates the resources required for an application to interface with SAP NetWeaver Gateway, including a proxy for the OData service that you select in the wizard.

To create your Android starter application: 1. From menu bar, select File New Other . The New wizard dialog is displayed.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

103

2. 3.

Expand the OData Development node and select Starter Application Project. Choose Next. The New Starter Application Project page is displayed.

104

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

4. 5. 6. 7. 8.

In the Project name field, enter a new name for your project. From the Create a new project for drop-down list, selectAndroid. In the Application name field, specify the name of the application that will be displayed to users. In the Build target field, specify the Android SDK version for the application. The minimum supported Android platform version is Android 2.2. In the Package name field, specify a package that conforms to the Java packaging naming format. For example, sap.android.crm.

Note
Android requires that the given package name consists of at least TWO tokens. 9. In the Activity field,specify the main entry activity for the application.

10. Choose Next. 11. Select the desired template. The wizard provides different options depending on the template you select.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

105

12. Choose Next. The Location of OData Service page is displayed.

106

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

13. Select the Remote location radio button. 14. Select the desired SAP NetWeaver Gateway service in one of the following ways: In the Service URL field, enter the desired services URL and then choose Go. Choose Catalog and select the desired SAP service using the Service Catalog dialog. Select the File system radio button and browse for the relevant service metadata and service document.

15. If you selected the List/Details template, you must configure the application as described on steps 16 to 27 :

Note
The Workflow and the Basic templates do not require further configuration.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

107

16. Click Next. The Activity Layout page is displayed.

17. In the Activity Title field, enter the name of the first activity. 18. From the Activity Type drop-down list, the List option is automatically selected. 19. From the Entity Set Navigation drop-down list, select the desired entity set. 20. Select additional operations you would like to support from the activity. For activities of type List the following options are available: Select the Add Create Option checkbox if you would like to add to this list activity the option of creating new items. Select the Add Edit Option checkbox if you would like to add to this list activity the option of deleting displayed items.

108

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

For views of type Details, select the Add Edit Option checkbox if you would like to add to this details activity the option of editing the displayed item.

Note
You can choose to add to the activity an option to perform an operation that is described above (creation, deletion or editing of the entity set items), only if this operation is supported by the selected entity set. 21. Choose Add (+) to see the fields available for the selected entity set. The Add Fields page is displayed.

22. Select the checkboxes of the desired fields for the activity.

Note
It is recommended not to include more than three or four fields in a list. 23. Click OK. 24. If needed, select a field and click Remove (-) to delete it. 25. Use the Up and Down arrows to change the positioning of the fields in the activity. The field positioned first in the list will appear bold in the relevant generated applications list activity. 26. In the Views section, choose to Add (+) another activity. 27. Repeat this procedure to configure the additional activities. 28. Choose Finish. The project is created.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

109

Android JUnit Project


A JUnit Test class is created in the JUNIT project under the specified package name for the basic application. The test class file is called DemoTest. Appended to the end of the package name is the term test.

Note
Available only when creating an Android application based on the Basic Starter Application template of the Toolkit for Android (GWPA).

8.2.1.1

Extending the Generated Android Starter Application

You can modify and extend the generated code for your Android starter application to suit your needs. Extending the List/Details Starter Application The Android starter application files based on the List/Details Application template are created and located in the specified Android project in the Eclipse workspace. The number of files created depends on the number of activities you defined in the wizard and the number of entity types defined in the selected service. The generated List/Details application contains code for using the SUP client library. The Settings screen has access from the Login screen and from the first screen. The Settings screen has two connection options: SAP NetWeaver Gateway and SUP. To use the SAP NetWeaver Gateway connection, the user must configure the Gateway URL and Gateway client. To use the SUP connection, the user must configure the SUP settings (Host, Port, Application ID, security configuration and Farm ID).

Extending the Basic Starter Application


You can modify and extend the generated code for the Basic Android application to suit your needs. The generated code provides an example for reading properties from one of the addressable collections of the selected OData services. Your Android application files based on the Basic Application template are created and located in the specified Android project in the Eclipse workspace. It includes code sample for using the generated proxy for the service in a user interface. Also, the generated Android application contains commented code for using the SUP client library to showcase probable uses for the application. To run the generated Android Basic application: 1. From the newly create Android project, go to the folder, src, expand your package and open the activity class, for example, <project_name>Activity.java

110

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2.

Go to the following line and replace the placeholder; <username> and <password> of the service with the actual logon credentials to your SAP system: public class AndroidCustomActivity extends Activity { private String userName = "<userName>"; private String password = "<password>";

3.

Run the application.

The Settings screen has access from the Login screen and from the first screen. The Settings screen has two connection options: SAP NetWeaver Gateway and SUP. To use the SAP NetWeaver Gateway connection, the user must configure the Gateway URL and Gateway client. To use the SUP connection, the user must configure the SUP settings (Host, Port, Application ID, security configuration and Farm ID).

Extending the Workflow Starter Application


The generated Workflow Android application enables users to view and manage their Workflow tasks using an OData service for Workflow in the SAP NetWeaver Gateway server. Depending on the Workflow service, your application is composed of four components: Splash Screen The splash screen is used to notify the user that, the application is in the process of loading. It disappears when the application's main window displays. The logic for the splash screen is handled by the code in the generated project within the class, SplashScreen.java. Login screen The login screen handles the user authentication with the OData services in SAP NetWeaver Gateway. Users must provide a user name and a password. The login and authentication logic is handled by the code of the login method in the class, LoginActivity.java. Workflow Task List The main screen of the application displays the Workflow task list and access to the details of each task.

Note
When your application loads for the first time, it obtains the content of the task list from SAP NetWeaver Gateway. Each task displays the following: Subject Creator Creation date Priority The service provides the task priorities as numbers that are mapped to strings as follows:

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

111

Priority
1 2 3 4 5 6 7 8 9

Description
Highest Very High Higher High Medium Low Lower Very Low Lowest

The task priorities are also marked with colors: high priorities, one to four (1-4) in red, medium priority (5) in black, and low priorities six to nine (6-9) in grey. Task Filter Tasks can be filtered by task name, which usually represents the type of task, such as, Leave Request, Purchase Order, and many more. To filter the tasks: Choose Filter and select the task name, or select All to view all tasks. The filtered task list displays according to your selection. Choose Cancel to exit the filter view.

Task Search In the task list view, you can search for tasks using the task name or part of the name. To perform a search: 1. 2. Click the search field at the top of the view. Type the search item or term. The search is performed on all presented properties and the results are displayed while typing the search item.

Note
Search is performed only on the tasks displayed in the list (which may be filtered). Workflow Task details After selecting a task from the task list, a view opens displaying the task details and enabling users to make a decision regarding the task. The task details displayed include the following: Task subject displayed at the top of the view as the task title. Task properties - status, creation date, creator and priority. Task extended properties (X-props). Note: Default extended properties are not displayed. Links to additional related task details, such as, comments, participants and attachments.

The task details logic is handled by the code in the generated project within the class, TaskDetailsActivity.java. Decisions To make a decision regarding the task: 1. 2. Choose Make Decision. The list of actions received from the service for the task displays. Choose an action to apply it or choose Cancel to return to the task details. After selecting an action, you can add a comment to be sent together with the task.

112

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

3.

Choose the button with the action name to apply it.

Choose Cancel to return to the task details without applying the action. After applying the action, the Details view is once more displayed. Completed tasks do not appear in the task list, when the application loads the next time. Viewing Task Attachments The Details view includes a link to task attachments (if there are any), showing also the number of attachments included. To view attachments: 1. 2. Choose Attachments. A view showing the file names of the tasks attachments is displayed. Choose an attachment. The attachment opens in the appropriate content viewer according to the file type,

Viewing Task Participants The Details view includes a link to the task participants (if there are any). Also, it shows the number of participants included. Choose Participants. A view showing the task participant names and types is displayed. Viewing Task Comments The Details view includes a link to the task comments (if there are any) showing also the number of comments included. Choose Comments. A view showing a list of task comments including each comments creator, creation date, and content is displayed. Viewing Task Description The Details view includes a link to the task description (if relevant). Choose Description. A view showing the task description is displayed. Settings Screen The Settings screen has access from the Login screen and from the first screen. The Settings screen has two connection options: SAP NetWeaver Gateway and SUP. To use the SAP NetWeaver Gateway connection, the user must configure the Gateway URL and Gateway client. To use the SUP connection, the user must configure the SUP settings (Host, Port, Application ID, security configuration and Farm ID).

8.2.1.2

Extending the Generated Basic Application

Use the generated basic application to develop your own application using the Java library API to call SAP NetWeaver Gateway. The following is an example of how to use the generated basic application. First, determine the business scenario for your application. For example, your application will do the following: Enable users to search for flights from one location to another. Users should be able to get details about a flight, such as, city of origin, destination city, departure date, and arrival date.

The following is an example code that calls the OData Java library to consume the OData service, RMTSAMPLEFLIGHT in an SAP NetWeaver Gateway server: Creating the request URL. String requestUrl = "/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/CarrierCollection (carrid='" + carrid + "')";

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

113

Defining Gateway connection settings. IServerConnectionParameters gateway = new ServerConnectionParameters ("<host>", "<port>","<client_id>", <useSSL>);

Create the authentication object. The example below shows basic authentication implementation. IAuthentication credentials = new UsernamePasswordCredentials("<user>","<password>");

Note
You must replace <user>, <password> with the appropriate values. You can add your own interceptors and authentication implementation. Initializing the REST client based on the connection details. The following are the option for setting the representation: ATOM, or JSON. IRestClient restClient = RestClientFactory.createInstance(gateway, credentials, Representation.ATOM); Executing the request. IRestRequest request = new RestRequest(requestUrl); IRestResponse response = restClient.execute(request); return response.getBody(); Example code for parsing returned response. Parsing the response string XML into an ODataEntry object. ODataEntry carrierEntry = ODataParserFactory.createInstance(Representation.ATOM).parseODataEntry(response); Getting the carrier properties and printing to the standard output. ODataProperty[] properties = entry.getProperties(); for (ODataProperty oDataProperty : properties) { System.out.println(oDataProperty.getName() + ": " + oDataProperty.getValue()); } . Example code for using a function import: GetAvailableFlights Create the request URL. String requestUrl = "/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/GetAvailableFlights? cityfrom=" + cityFrom + "&cityto=" + cityTo + "&fromdate=" + fromDate + "&todate=" + toDate; Defining Gateway connection details. IServerConnectionParameters gateway = new ServerConnectionParameters ("<host>", "<port>","<client_id>", <useSSL>); Initializing the REST client based on the connection settings. IRestClient restClient = RestClientFactory.createInstance(gateway, credentials,Representation.ATOM); IAuthentication credentials = new UsernamePasswordCredentials("<user>","<password>");

114

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

Calling the SAP NetWeaver Gateway server. IRestRequest request = new RestRequest(requestUrl); IRestResponse response = restClient.execute(request); return response.getBody(); }

8.2.2

Generating a Proxy for an Android Application

You can create a proxy for an Android application to consume OData services through your SAP NetWeaver Gateway server. The proxy provides the implementation interfaces for the OData service you choose to use. You must create your own application to interface with the generated proxy. Requirements Make sure that the project into which you generate the proxy is an Android project.

Note
You get a warning message when you attempt to generate code for an environment that is different from that of the target environment of the selected project To create your proxy: 1. 2. 3. From the File menu, choose New wizard dialog displays. New Other OData Development , and then select Service Proxy. The

From Create new proxy for, selected Android. Select an existing Android project for the toolkit for which you want to create the proxy.

Note
Depending on the properties of the environment for the selected toolkit, you can generate the code into a project or a folder in the file system. 4. 5. 6. 7. Specify the Package name. Choose Next. The page for specifying the OData service you want your application to call displays. Select Remote location, to connect to your SAP NetWeaver Gateway server within the network. Click Catalog to search for the specific OData service. The exploration dialog opens for you to search for the service. When you click Catalog, without providing a specific URL, the specified default SAP NetWeaver Gateway is automatically selected. If you have not saved the password of the default SAP NetWeaver Gateway, a popup displays requesting the password. Alternatively, select File system, and click Browse to specify the paths to both the service metadata document for the specific service, and the service document in your file system. Click Validate to verify that the service documents are properly formed XML files for OData compliant services.

Note

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

115

If the specified URL of the service metadata comes from the Service Catalog, the Validate button is not available, as both the connection and the metadata document is verified. The Validate button is available only if you have manually entered the URL, or selected the metadata file from the file system 8. Choose Finish.

The proxy wizard generates code into the specified Android project. In addition, it automatically creates class files for the selected OData service regardless of the specified target environment. The number of files created depends on the number of entities in the selected OData service.

Note
Do not locate different proxy contents for the same service into the same project folder, as Eclipse overwrites the files with similar names in a project. The generated proxy consists of the following: SRC folder This folder contains the proxy classes for the selected OData service in the following packages: com.sap.example This is the package you created for the Android project. It contains the main activity class which is created automatically. com.sap.example.android This is the package you created for use in the Android extension. The service class is created. com.sap.example.android.complextypes This package contains the Java classes of complex types for the extension. com.sap.example.android.entitytypes This package contains the Java classes for entity types. com.sap.example.android.helpers This package contains the Java classes of helper methods for the runtime of the Android application, such as, connectivity to SAP NetWeaver Gateway. Referenced Libraries Contains the libraries (Android OData SDK) of the SAP OData Mobile Client SDK. Res This folder contains the service metedata document and the service document XML as well as the file, service.properties, that holds the connectivity details for SAP NetWeaver Gateway.

Example
You can call the generated proxy classes from your application to interface with the selected OData service through the specified SAP NetWeaver Gateway server. Note that, you have to create your own user interface for rendering your application. The following is an example of a class with a main method that calls the generated classes and methods for the OData service, RMTSAMPLEFLIGHTService. Each line in the example has comments to help you understand the expected process: public class ProxyTestActivity extends Activity implements ISDMNetListener {

116

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

SDMLogger logger; RMTSAMPLEFLIGHTService service; SDMConnectivityHelper connection; Called when the activity is first created. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { logger = new SDMLogger(); Creates the service, RMTSAMPLEFLIGHTService. service = new RMTSAMPLEFLIGHTService(this.getApplicationContext()); Creates the query, FlightCollection, for SAP NetWeaver Gateway. ODataQuery flightCollectionQuery = service.getFlightCollectionQuery(); Creates the connection details to the SAP NetWeaver Gateway connection = new SDMConnectivityHelper("<username>", "<password>", this.getApplicationContext()); Executes the request to Gateway connection.executeBasicAsyncRequest(flightCollectionQuery, this); } catch (SDMPreferencesException e) { e.printStackTrace(); } catch (SDMParserException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } } Error handling method. @Override public void onError(ISDMRequest arg0, HttpResponse arg1, ISDMRequestStateElement arg2) { logger.i("TAG", "IOException", "onERROR()"); } Success response method. @Override public void onSuccess(ISDMRequest aRequest, HttpResponse aResponse) { Gets the response from Gateway. final HttpResponse response = aResponse; logger.i("TAG", "Successfully got the response.", "onSuccess()");

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

117

final Context context = this.getApplicationContext(); new Thread() { public void run() { String respBody = ""; try { Getting the entity set as a String final String entityString = EntityUtils.toString(response.getEntity()); List<Flight> flightCollection = service.getFlightCollection(entityString); Gets the first flight in the collection Flight flight = flightCollection.get(0); Gets the query for the flight's bookings (navigation property query) ODataQuery flightBookings = flight.flightBookingsQuery(); Execute the request for the above query connection.executeBasicAsyncRequest(flightBookings,new RequestDeligate(context)); Gets the response in RequestDeligate class } catch (IOException e) { logger.e("TAG", "IOException", e, "onSuccess()"); } catch (SDMParserException e) { e.printStackTrace(); } } } .start(); } } Sample of RequestDeligate class: The navigation property response handler public class RequestDeligate implements ISDMNetListener { SDMLogger logger; RMTSAMPLEFLIGHTService service; SDMConnectivityHelper connection; Context context; public RequestDeligate(Context context) { this.context = context; } @Override public void onError(ISDMRequest arg0, HttpResponse arg1, ISDMRequestStateElement arg2) { logger.e("TAG", "IOException", "onError()"); } @Override public void onSuccess(ISDMRequest arg0, HttpResponse arg1)

118

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

{ // Note: we are not in the UI thread final HttpResponse response = arg1; logger.i("TAG", "Successfully got the response.", "onSuccess()"); new Thread() { public void run() { String respBody = ""; Response from the navigation property try { final String entityString = EntityUtils.toString(response .getEntity()); service = new RMTSAMPLEFLIGHTService(context); Booking flightbooking = Flight.flightbooking(entityString); Writing the agency number for example to the log Log.i("TAG", flightbooking.getAGENCYNUM()); Executing another request to Gateway connection.executeBasicAsyncRequest(service.GetFlightDetailsQuery( flightbookin g.getcarrid(), flightbooking.getconnid()), new FIRequestDeligate(context)); Getting the response in FIRequestDeligate class } catch (IOException e) { logger.e("TAG", "IOException", e, "onSuccess()"); } catch (SDMParserException e) { e.printStackTrace(); } catch (SDMPreferencesException e) { e.printStackTrace(); } } } .start(); } } Sample of FIRequestDeligate class: Function import response handler public class FIRequestDeligate implements ISDMNetListener { SDMLogger logger; RMTSAMPLEFLIGHTService service; SDMConnectivityHelper connection; Context context; public FIRequestDeligate(Context context) { this.context = context; } @Override public void onError(ISDMRequest arg0, HttpResponse arg1,

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

119

ISDMRequestStateElement arg2) { logger.i("TAG", "IOException", "onERROR()"); } @Override public void onSuccess(ISDMRequest arg0, HttpResponse arg1) { // Note: we are not in the UI thread! final HttpResponse response = arg1; logger.i("TAG", "Successfully got the response.", "onSuccess()"); new Thread() { public void run() { String respBody = ""; try { final String entityString = EntityUtils.toString(response.getEntity()); service = new RMTSAMPLEFLIGHTService(context); FlightDetails getFlightDetails = service.GetFlightDetails(entityString); Writing to the log, the airport the flight came from Log.i("TAG", getFlightDetails.getairportFrom()); } catch (IOException e) { logger.e("TAG", "IOException", e, "onSuccess()"); } catch (SDMParserException e) { e.printStackTrace(); } catch (SDMPreferencesException e) { e.printStackTrace(); } } } .start(); } } Create: initialization of the service service = new RMTSAMPLEFLIGHTService(this.getApplicationContext()); Retrieval of the Query object for the bookingCollection ODataQuery bookingCollectionQuery = s.getBookingCollectionQuery(); Date fldate = m_ISO8601Local.parse("2013-06-13T00:00:00"); Initialization of the Booking object Booking booking = new Booking("AA", "0017", fldate, "00001111"); booking.setCUSTOMID("00004617"); booking.setCOUNTER("00000000"); booking.setAGENCYNUM("00000001"); booking.setPASSNAME("Gal Rot"); booking.setPASSFORM("1234567"); booking.setCUSTTYPE("p"); booking.setWUNIT("KG"); booking.setCLASS("Y"); booking.setFORCURAM(new BigDecimal(879.82)); booking.setFORCURKEY("USD"); booking.setLOCCURAM(new BigDecimal(879.82));

120

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

booking.setLOCCURKEY("USD"); booking.setPASSBIRTH( m_ISO8601Local.parse("1990-10-10T00:00:00")); Initialization of the ConnectivityHelper object con = new SDMConnectivityHelper("username", "passord",this.getApplicationContext()); Execution of the create command against the collection URL using, bookingCollectionQuery. The booking.getStringPayload() returns the payload of the entry. con.executeAsyncCreateRequest(bookingCollectionQuery, booking.getStringPayload(), new CreateDeligate(this.getApplicationContext())); Update: changing the Passengers name in the booking object bookingCollectionEntry.setPASSNAME("G I JOE"); Execution of the update command (against the URL of the booking entry using bookingCollectionEntry.getEntitysQuery() that would return the entry URL ) The booking.getStringPayload() returns the payload of the entry. con.executeAsyncUpdateRequest(bookingCollectionEntry.getEntitysQuery(), bookingCollectionEntry.getStringPayload(), new CreateDeligate(context)) ; Delete: the booking object is the same as the update method. Execution of the delete command (against the URL of the booking entry using bookingCollectionEntry.getEntitysQuery() that would return the entry URL. The booking.getStringPayload() returns the payload of the entry. con.executeAsyncDeleteRequest(bookingCollectionEntry.getEntitysQuery(), bookingCollectionEntry.getStringPayload(), new CreateDeligate(context));

8.2.3

Running your Android Application

You can run the Android application immediately or edit the code in the generated class, and perform various tests for it. Run and test the generated Android application in the Android-provided simulator in Eclipse.

Runtime Look and Feel of your Starter Android Application


The runtime of your starter application is based on the default user interface (UI) provided by the design time template for rendering pages. You can move from a Details page to another page by selecting the title of the page. In addition, you can activate the following media elements, only if the element had been defined in the service document defintion to contain the attribute sap:semantics:

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

121

TEL Where the service document used at design time contains a property with the attribute sap:semantics=tel, the runtime of the application will contain a telephone icon, and choosing the telephone number activates the call. EMAIL Where the service document used at design time contains a property with the attribute sap:semantics=email, the runtime of the application will contain a envelope icon, and choosing the email activates the defined email client. If no email client is defined, you receive the relevant message.

URL Where the service document used at design time contains a property with the attribute sap:semantics=URL, the runtime of the application will contain a circular icon, and choosing the URL activates the Web browser to open the specific URL address.

8.2.4

Securing Your Android Application

The generated Android application supports basic authentication that uses the browser pop-up dialog for user credentials. You can use basic authentication over SSL.

Secure Android Application


Make sure that you have an SSL server certificate (Base64 encoded X.509 (.CER)) from a certificate authority. For your production environment, verify that, the certificate matches that of the SAP NetWeaver Gateway production landscape. To use basic authentication over SSL, add the following to the constructor section in the file, SDMConnectivityHelper.java: Read the certificate. InputStream is; is = resources.openRawResource(com.sup.test.R.raw.sslcer); CertificateFactory certFact; certFact = CertificateFactory.getInstance("X509"); X509Certificate cert = (X509Certificate) certFact.generateCertificate(is); is.close(); Add the certificate to the SDMPreferences. mParameters.setServerCertificate(cert);

Note
Note that the server certificate referenced in the code, sslcer, must be located in the folder: .../res/raw.

122

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

8.2.5

Working with the Sybase Unwired Platform Server

Sybase Unwired Platform (SUP) server is a middleware which you can install and locate between SAP NetWeaver Gateway and your generated Android application. It is used in a productive landscape where you want to make your generated Android application (both starter application and proxy) available to a large number of people. Currently, the Toolkit for Android (GWPA) provides APIs that enable you to directly connect to the SAP NetWeaver Gateway environment in order to test and evaluate your generated Android application. Use the information in this section to connect to an SUP server in your SAP NetWeaver Gateway landscape.

Prerequisites
Make sure that you have the following: Installed SUP server. A user with permissions to work in both the SUP Server and the SAP NetWeaver Gateway. Information about the SUP server: The host name and the port number of the SUP server. The Application ID, the name of the registered application. The Farm ID, the default value is 0. The name of the Application Security Configuration.

You can obtain the above information from the administrator of the SUP server (Sybase Control Center). The following is an overview of the tasks to perform to enable your Android application to use the SUP server: 1. 2. 3. Generate your Android application using the Toolkit for Android (GWPA). Add the SUP libraries to your Android project. Manually switch the connection to the SUP server.

8.2.5.1 Project

Adding the SUP Server Libraries to your Android

You can enable your generated Android application to connect to SAP NetWeaver Gateway through the SUP server, using the appropriate SUP server libraries and their dependencies. You must add the libraries and their dependencies into the Android project you want to generate. Find the following files of the SUP server libraries in your file system in the folder, for example, <SUPUnwiredPlatform_InstallDir>\MobileSDK\OData\Android\libraries\: ClientLib.jar sup-json.jar SUPProxyClient-2.1.2.jar

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

123

To add the SUP server libraries: 1. 2. 3. 4. Right click your Android project, and choose Build Path > Configure Build Path. Click the tab, Libraries, choose Add External JARS..., and the select the JAR files in the client libs folder. Select the tab, Order and Export, and export the SUP server libraries specified above. Click OK.

8.2.5.2

Manually Switching to the SUP Server

After adding the SUP server libraries and their dependencies to the Android project, you configure the SUP server connectivity. You have an Android starter application or the proxy for the OData service. To manually switch to the SUP server, uncomment the following sections in the file, LoginActivity.java class: The SUP helper class and Properties variable: private SupHelper supHelper; private Properties properties; try { this.isUsingSupServer = true; Extract the SUP server and application details from the properties file: InputStream rawResource = getApplicationContext().getResources().openRawResource(p.p.R.raw. salesorderservice); this.properties = new Properties(); this.properties.load(rawResource); The ID of your application: String applicationId = properties.getProperty("applicationId"); The host name of the SUP server: String supHost = properties.getProperty("supHost"); The port number of the SUP server: int supPort = Integer.parseInt(properties.getProperty("supPort")); Farm id: String farmId = properties.getProperty("farmId"); Create an instance of the SupHelper class: supHelper = new SupHelper (getApplicationContext(), supHost, supPort, farmId, applicationId); Check if the user's device is already registered: if (supHelper.getManager().isRegistered()) { //If so, the user name and password are currently empty, and we call "handleActivity": handleActivity("", "");

124

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

} } catch (SDMPreferencesException e) { SALESORDERApplication.LOGGER.e(SALESORDERApplication.TAG, e.getMessage()); } catch (IOException e) { SALESORDERApplication.LOGGER.e(SALESORDERApplication.TAG, e.getMessage()); } catch (MessagingClientException e) { SALESORDERApplication.LOGGER.e(SALESORDERApplication.TAG, e.getMessage()); } The last "catch" block in "onClick" method: catch (MessagingClientException e) { SALESORDERApplication.LOGGER.e(SALESORDERApplication.TAG, e.getMessage()); } The last exception thrown in "handleActivity" method's signature: private void handleActivity(String userName, String password) throws SDMPreferencesException, IOException, MessagingClientException The following lines in "handleActivity" method: vaultPassword: Password of the secure store provided by SDK. securityConfig: The security configuration of the application. String vaultPassword = this.properties.getProperty("vaultPassword"); String securityConfig = this.properties.getProperty("securityConfig"); Overwrites the (key, value) pair in the ISDMPreferences interface, with the matching data for use in the SUP server mode: sdmConnectivityHelper.getmPreferences().setStringPreference(ISDMPreferences.SDM_C ONNECTIVITY_HANDLER_CLASS_NAME, "com.sybase.mobile.lib.client.IMOConnectionHandler"); On accessing the application for the first time, the device is registered in the SUP server. Else, perform an unlock action and continue working: supHelper.registerOrUnlock(userName, password, vaultPassword, securityConfig); Gets the application's end point from the SUP server and sets it as the URL in the service. supHelper.setServiceUrl(); From the Android project into which you generated your application, open the automatically generated package called helpers, then open the file, SupHelper.java and remove all the comments (uncomment). The SUPHELPER class methods: Registers the device for the user in the SUP server. This method will initialize the SUP client with the appropriate data regarding the SUP server. It takes the following: username passwordsecurityConfig: The security configuration of the application. In case of an error, it throws messages from MessagingClientException. public void registerUser(String username, String password, String securityConfig) throws MessagingClientException {

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

125

if (!liteUserManager.isRegistered())

Registers the specific device once, notice the order of the parameters: liteUserManager.registerUser(username, securityConfig, password); } } Registers the user's device in the SUP server, with vault password. This method will initialize the SUP client with the appropriate data regarding the SUP server. With the option to save the credentials in a secured storage (vault). It takes the following: usernamepasswordsecurityConfig: The security configuration of the application. vaultPassword: Password of the secure store provided by SDK In case of an error, it throws messages from MessagingClientException. public void registerUser(String username, String password, String securityConfig, String vaultPassword) throws MessagingClientException { if (!liteUserManager.isRegistered()) { Registers the specific device once, notice the order of the parameters: liteUserManager.registerUser(username, securityConfig, password, vaultPassword); } } Unregisters the user's device from the SUP server: public void unregisterSUPUser(LiteUserManager liteUserManager) { if (liteUserManager.isRegistered()) { liteUserManager.deleteUser(); } } On accessing the application for the first time, the device is registered in the SUP server using this method. Else, unlock the vault and continue working. It takes the following: userString passwordString vaultPassword: Password of the secure store provided by SDK securityConfig: The security configuration of the application. public void registerOrUnlock(String userString, String passwordString, String vaultPassword, String securityConfig) throws SDMPreferencesException, MessagingClientException { Check if the given user name and password are not empty, meaning they came from the UI: if ((userString.length() > 0) && (passwordString.length() > 0)) { Registers the user's device: registerUser(userString, passwordString, securityConfig, vaultPassword); } else { Extract the user name and password from the vault: manager.unlockVault(vaultPassword);

126

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

Start the client: LiteMessagingClient.initInstance(context, appId); LiteMessagingClient lm = LiteMessagingClient.getInstance(); lm.startClient(); } } Gets the application's end point from the SUP server and sets it as the URL in the service: public void setServiceUrl() throws MessagingClientException { LiteAppSettings appSettings = new LiteAppSettings() ; Get the URL from the server: String url = appSettings.getApplicationEndPoint(); Set it in the service: SALESORDERService.setUrl(url); } Perform Organize imports ( CTRL+SHIFT+O ) on the entire code before compiling due to compilation errors in the code. After uncommenting the code, you need to enter information about the SUP server in the file, <service_name>.properties, located in the folder, \res\ raw folder: The host name and the port number of the SUP server.The Application ID, the name of the registered application. The Farm ID, the default value is 0.The name of the Application Security Configuration. vaultPassword=<myVaultPassword> farmId=<myFarmId> supPort=<myPort> securityConfig=<mySecurityConfiguration> supHost=<myHost> applicationId=<myApplicationId> You can obtain the above information from the administrator of the SUP server (Sybase Control Center)

8.2.5.3

Android Starter Application on SUP Server

Where your application uses Data Vault or requires the SDK to store the credentials, add the file, SybaseDataProvider.apk (this file is part of the SUP Android OData SDK, AndroidODPSDK*.zip) to the folder ...\Data\APP

Uncommenting the Generated Code


Make sure that you have added the SUP libraries. In addition, do the following: Uncomment the content of the entire file, SupHelper.java, in the helpers package. In the class file, LoginActivity.java, remove the comment characters// (uncomment) in the following sections: //private SupHelper supHelper; //private Properties properties;

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

127

//try //{ //this.isUsingSupServer = true; //// extract the sup server and application details from the properties file //InputStream rawResource = getApplicationContext().getResources().openRawResource(p.p.R.raw.salesorderservice); //this.properties = new Properties(); //this.properties.load(rawResource); //// the id of your application //String applicationId = properties.getProperty("applicationId"); //// the host name of the sup server //String supHost = properties.getProperty("supHost"); //// the port number of the sup server //int supPort = Integer.parseInt(properties.getProperty("supPort")); //// farm id //String farmId = properties.getProperty("farmId"); // supHelper = new SupHelper(getApplicationContext(), supHost, supPort, farmId, applicationId); // //// check if the user's device is already registered //if (supHelper.getManager().isRegistered()) //{ //// if so, the username and password are currently empty //handleActivity("", ""); //} //} //catch (SDMPreferencesException e) //{ //SALESORDERApplication.LOGGER.e(SALESORDERApplication.TAG, e.getMessage()); //} //catch (IOException e) //{ //SALESORDERApplication.LOGGER.e(SALESORDERApplication.TAG, e.getMessage()); //} //catch (MessagingClientException e) //{ //SALESORDERApplication.LOGGER.e(SALESORDERApplication.TAG, e.getMessage()); //} //catch (MessagingClientException e) //{ //SALESORDERApplication.LOGGER.e(SALESORDERApplication.TAG, e.getMessage()); //} //private void handleActivity(String userName, String password) throws SDMPreferencesException, IOException //, MessagingClientException //the vault password //String vaultPassword = this.properties.getProperty("vaultPassword"); // the security configuration of the application //String securityConfig = this.properties.getProperty("securityConfig"); //SDMPreferences mPreferences = new //SDMPreferences(getApplicationContext(), //SALESORDERApplication.LOGGER); // mPreferences.setStringPreference(ISDMPreferences.SDM_CONNECTIVITY_HANDLER_CLASS_NAME ,"com.sybase.mobile.lib.client.IMOConnectionHandler"); // supHelper.registerOrUnlock(userName, password, vaultPassword, securityConfig); //supHelper.setServiceUrl(); // supHelper.registerOrUnlock(userName, password, vaultPassword, securityConfig); //supHelper.setServiceUrl();

8.2.5.4

Runtime of the Generated Android Application

You enable your generated Android starter application or the proxy at runtime to use the SUP server as follows:

128

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

Open the file, <service_name>.properties, in the folder, /res/raw, and enter the following: vaultPassword=<myVaultPassword> farmId=<myFarmId> supPort=<myPort> securityConfig=<mySecurityConfiguration> supHost=<myHost> applicationId=<myApplicationId>

Open the file, LoginActivity.java, and initialize the SupHelper: supHelper = new SupHelper (getApplicationContext(), supHost, supPort, farmId, applicationId);

Check if the user's device is already registered: if (supHelper.getManager().isRegistered()) { If so, the user name and password are currently empty, and we call for handleActivity: handleActivity("", ""); }LoginActivity handleActivity method. Enter the following values: String vaultPassword = this.properties.getProperty("vaultPassword"); String securityConfig = this.properties.getProperty("securityConfig");

Overwrites the (key, value) pair in the ISDMPreferences interface, with the matching data for use in the SUP server mode: sdmConnectivityHelper.getmPreferences().setStringPreference(ISDMPreferences.SDM_C ONNECTIVITY_HANDLER_CLASS_NAME,"com.sybase.mobile.lib.client. IMOConnectionHandler");

On accessing the application for the first time, the device is registered in the SUP server. Else, perform an unlock action and continue working: supHelper.registerOrUnlock(userName, password, vaultPassword, securityConfig);

Gets the application's end point from the SUP server and sets it as the URL in the service: supHelper.setServiceUrl();

Create an instance of SDMConnectivityHelper and set it in the application: sdmConnectivityHelper = new SDMConnectivityHelper(userName, password, getApplicationContext()); application.setConnectivityHelper(sdmConnectivityHelper);

Create a query to be executed, for example CurrencyCollection: ODataQuery query = application.getService().get Currency CollectionQuery();

Create an Intent for the next page, for example ListCurrencyActivity: Intent intent = new Intent(getApplicationContext(), ListCurrencyActivity.class);

Add the data to the Intent: intent.putExtra(SALESORDERApplication.NAVIGATION_URL, query.getUrl());

Start the activity and go to the next page: startActivity(intent);

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

129

In the next page's "OnCreate()" method extract the URL of the query from the intent: String url = getIntent().getStringExtra(SALESORDERApplication.NAVIGATION_URL);

Create a new query with the URL: ODataQuery query = new ODataQuery(url);

Execute the request: application.getConnectivityHelper().executeBasicAsyncRequest(query,this);

Get the response in "OnSuccess()" method: public void onSuccess(ISDMRequest aRequest, HttpResponse aResponse) { final String data = EntityUtils.toString(response.getEntity());

Parse the data into a list of Currency entries: entries = SALESORDERService.getCurrencyCollection(data); }

If an error occurs, the response is received in the method, "OnError()": public void onError(ISDMRequest request, HttpResponse response, ISDMRequestStateElement arg2) { //TODO: Perform error handling. } } );

8.2.6

Creating Your Own Custom Android Template

You can create a new Android template for use in the SAP NetWeaver Gateway Productivity Accelerator framework. The new template is based on the appropriate pattern and environment of the Toolkit for Android (GWPA) in the framework.

Example Code
Make sure that you have: Added the correct plug-in dependency for the Toolkit for Android (GWPA), com.sap.iw.gw.oc.eclipse.environment.android Specified the correct environment identifier attribute for the Toolkit for Android (GWPA), com.sap.iw.gw.oc.eclipse.environment.android You can extend the Android template which receives the environment from the framework .

Example

130

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

The following is an example for extending the template: Proxy template for an Android application setDependencies() @Override public void setDependencies(Environment environment, Pattern pattern) { // this method is deprecated } Android Starter Application template onFinish(). @Override public void onFinish(IProgressMonitor monitor) throws TemplateException { try { monitor.beginTask(Messages.AndroidList_0, 3); Create a new Android project. this.listPattern = (ListPattern) this.context.get(TemplateConstants.PATTERN); this.androidEnvironment = (IAndroidEnvironment); this.context.get(TemplateConstants.ENVIRONMENT); androidEnvironment.createNewProject(new SubProgressMonitor(monitor, 1)); monitor.worked(1); Generate an Android list application into the project. Generate proxy AndroidProxy androidProxy = new AndroidProxy(); androidProxy.setDependencies(this.environment, this.listPattern); androidProxy.onFinish(new SubProgressMonitor(monitor, 1)); monitor.worked(1); Create an Android list application. listPattern.getListModel(); monitor.worked(1); } catch (EnvironmentException e) { throw new TemplateException(e); } finally { monitor.done(); } }

8.2.7

Troubleshooting for the Toolkit for Android (GWPA)

The following are some of the known issues when using the Toolkit for Android (GWPA). The solutions provided will help you to resolve these issues. Generated Proxy Configuration for External Network Connectivity

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

131

Issue: At runtime, when you attempt to connect to an external network other than your local network, you get the exception, UnknownHostException message Solution: In Eclipse, open the file, SDMConnectivityHelper.java class in the helpers package of the generated service proxy, add the following, and then redeploy the application: this.mPreferences.setStringPreference(ISDMPreferences.SDM_CONNECTIVITY_PROXY_HOST, "<your proxy host>"); this.mPreferences.setIntPreference(ISDMPreferences.SDM_CONNECTIVITY_PROXY_PORT, <your proxy port>); Starter Application Timed Out Error at RUntime Issue In some cases, you may get the following error at runtime: java.io.IOException: JSON: expected character; found EOF. This error occurred because the SUP server timed out (60 seconds). Solution From the generated package, open the file, LoginActivity.java, and add the $top parameter to the query request in order to restrict the number of items retrieved. For example: ODataQuery query = application.getService().getBookingCollectionQuery(); query.addParameter("top", "10"); File Out of Sync Error Issue When running the Toolkit for Android (GWPA) in versions of Eclipse that are higher than Eclipse 3.7.0, you may get the following error when you generate the application: File out of synch. Or, at runtime, in the emulator, the following error displays: ActivityManager: Error type 3, ActivityManager: Error: Activity class {xx.xx/xx.xx.SplashScreen} does not exist Solution Open Window > Preferences > General > Workspace , and select Refresh on access, before you regenerate the project.

8.2.8

Generated Application Flow

The generated applications by default support direct SAP NetWeaver Gateway access using basic authentication (with the option of HTTPS). In addition, the applications support Single Sign-On (SSO) by saving the user credentials entered in the first application run, and using them whenever they are required. The applications also support other authentication methods. For more information, see the Configuring the User Authentication in an iOS Starter-Kit Application section. The following objects are used to handle user authentication (in any of the supported methods) and to perform service operations using the provided credentials: App Delegate This is the main entry point for the application. It launches the Login screen as the root view controller. It then validates if user credentials are already saved on the device. If so, it displays the login screen in an operation mode that performs the login process using the saved credentials instead of requesting them from the user.

132

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

After the authentication process is complete, it replaces the Login screen with the view controller of the first screen in the application. In addition, the App Delegate defines which authentication method must be used and its related parmeters. (By default, Basic authentication is used). It also defines whether service versioning negotiation should be used (as part of the login process). Login Screen Responsible for validating the user credentials by calling the login method of the Request Handler. It allows users to enter their credentials according to the authentication method required for SAP NetWeaver Gateway access. Request Handler A singleton object responsible for making the HTTP calls to the SAP NetWeaver Gateway and for notifying the appropriate view once the opertaions are completed. The Request Handler performs the login process with the user credentials provided in the login screen. This process includes service versioning negotiation (if enabled), user authentication, and service proxy object initiation (using runtime or local metadata). The Request Handler is also used by the application views to perform the service requests needed for getting the relevant data for the view. Authenticating A protocol which makes HTTP requests with the user credentials for user authentication, according to the required authentication method. The requests are performed using the SAP OData Mobile SDK. The Authenticating protocol implementations save, load or delete the user credentials from the device as necessary. Connectivity Helper A helper class which makes HTTP requests (without user credentials) using the SAP OData Mobile SDK. This class is used by the Request Handler for all the service requests of the application, except for the first one (that requires the user credentials).

These objects may be also used for handling user authentication for accessing the SAP NetWeaver Gateway through the SUP server. For more information, see Configuring a Starter Kit Application to Work with SUP. Related Links

Configuring the User Authentication in an iOS Starter-Kit Application [page 236] All the generated applications use Basic authentication by default.

8.3

Toolkit for HTML5 (GWPA)

Introduction to the Toolkit for HTML5 (GWPA), which is a toolkit for service consumption. The Toolkit for HTML5 (GWPA) is a collection of environments, patterns, and templates, suitable for developing SAP solutions for use in any browser environment that supports HTML5 protocol (SAPUI5 and JQuery) including browsers on mobile devices. In addition, you can use the extensible tools of the framework to create your custom templates. Target Audience The Toolkit for HTML5 (GWPA) is targeted for developers. This document describes how to consume SAP NetWeaver Gateway services to generate an HTML5 Eclipse project.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

133

To use the Toolkit for HTML5 (GWPA), you must install the feature Toolkit for HTML5 (GWPA)t for SAP NetWeaver Gateway Productivity Accelerator. Related Links

https://help.hana.ondemand.com/gateway_gwpa/pdf/ SAP_NetWeaver_Gateway_Productivity_Accelerator_Inst_Guide_en.pdf

8.3.1

Running the Toolkit for HTML5 (GWPA)

Steps required to run the toolkit. To run the toolkit: 1. 2. From the Eclipse menu bar, select File New Other . The Select a Wizard page is displayed.

Expand the OData Development node and select Starter Application Project. The Proxy Generation is irrelevant for HTML5.

8.3.1.1

Running the SAPUI5 Application

Before you can run the generated SAPUI5 application, you must edit the index.html file to set the location of the SAPUI5 libraries. To set the location of the SAPUI5 libraries: 1. 2. 3. Open the the index.html file located in the WebContent directory. Search for the following line in the Script tag:src="./sapui5-static/resources/sap-ui-core.js" Replace the text in quotation marks by a link to the location where the files for SAPUI5 are located. If you download the SAPUI5 library and deploy it with your application, the location should indicate the relative path of the library in your application. Alternatively, you can set this location with the URL of a remote location hosting this libraries. The generated SAPUI5 application targets desktops. For deploying the application, run it on a dedicated web server and navigate to it from a web browser. Make sure to configure the web server as a reverse proxy for the SAP NetWeaver Gateway server to prevent the browser from blocking your requests due to Cross-Origin Resource Sharing. In addition, make sure to appropriately edit the domain of the service URL defined in the application. For more information, see the Configure the Generated Application to Use a Reverse Proxy section. Related Links

http://en.wikipedia.org/wiki/Cross-origin_resource_sharing Configuration of the Generated Application to Use a Reverse Proxy [page 148] Explanation of the necessary configuration to use a reverse proxy.

134

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

8.3.2

Creating an HTML5 Starter Application Project

You can create List/Details starter applications for HTML5 to call SAP services in SAP NetWeaver. Gateway: You can create one of the following starter applications for HTML5 to call SAP services in SAP NetWeaver Gateway: List/Details Application (jQuery Mobile) Generate an HTML5 List/DeCreating an tails starter application based on jQuery Mobile for displaying SAP data in list and details screens. List/Details Application (SAPUI5) Generate an HTML5 List/Details starter application based on SAPUI5 for displaying SAP data in list and details screens.

To create your HTML5 starter application: 1. 2. From the Eclipse menu bar, select File > New > Other. The Select a Wizard page is displayed. Expand the OData Development node and select Starter Application Project.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

135

3.

Choose Next. The New Starter Application Project page is displayed.

4. 5.

In the Project name field, enter a name for your project. From the Create new project for drop-down list, select HTML5.

136

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

6.

Choose Next. The Starter Application Templates for HTML5 page is displayed.

7.

Select the desired template. List/Details Application (jQuery Mobile) List/Details Application (SAPUI5)

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

137

8.

Choose Next. The Location of OData Service page is displayed.

9.

Select the desired SAP NetWeaver Gateway service in one of the following ways: In the Service URL field, enter the desired services URL, and then choose Go. Choose Catalog and select the desired SAP service using the Service Catalog dialog. Select the File system radio button and browse for the relevant service metadata and service document.

When the service is validated, its details are displayed. 10. Choose Next to continue with the wizard to configure the application based on the selected application type. For the List/Details jQuery Mobile template, continue with the wizard as described in the Defining the jQuery Mobile List/Details Page Layout section. For the List/Details SAPUI5 template, continue with the wizard as described in the Defining the SAPUI5 List/Details View Layout section.

11. Choose Finish. An Eclipse project with the application code is created in your workspace. Related Links

Defining the jQueryMobile List/Details Page Layout [page 139] The jQuery Mobile List/Details application is created by selecting a service and defining its pages. The generated application is an HTML5 mobile application based on the jQuery Mobile library, that contains code for each page you have specified. Defining the SAPUI5 List/Details Page Layout [page 140] Explains how to define the application for List/Details.

138

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

8.3.2.1

Defining the jQueryMobile List/Details Page Layout

The jQuery Mobile List/Details application is created by selecting a service and defining its pages. The generated application is an HTML5 mobile application based on the jQuery Mobile library, that contains code for each page you have specified. To configure the pages in a List/Details application based on jQuery Mobile: 1. If you have not done so already, define the application details as described on the Creating a Starter Application Project section (steps 1-9). The Page Layout page is displayed.

2. 3. 4.

In the Page Title field, enter the name of the first page. From the Page Type drop-down list, the List page option is automatically selected. From the Entity Set Navigation drop-down list, select the desired collection.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

139

5.

Choose Add (+) to see the fields available for the selected entity set. The Add Fields page is displayed.

6. 7. 8. 9.

Select the checkboxes of the desired fields for the page. We recommend that you not have more than 3-4 fields in a list. Choose OK. If needed, select a field and click Remove (-) to delete it. Use the Up and Down arrows to change the positioning of the fields in the view. The field positioned first in the list will appear bold in the relevant generated applications list page.

10. Under the Pages section, choose Add (+) to add another page. 11. Repeat this procedure to configure the additional pages.

8.3.2.2

Defining the SAPUI5 List/Details Page Layout

Explains how to define the application for List/Details. The List/Details application is created by selecting a service and defining its views. For each view, you must select one of the following types: List The UI generated from this type of view is a table displaying information obtained from an entity set. For the chosen entity set, you are required to choose the fields you would like to display which will then become the table column headers. For example, the Customer entity set will have fields such as Customer Name, Country, Street, Telephone Number, and so on. In addition, you can add the generated list view the option of creating new items into the chosen entity set, or of deleting existing items. Details The UI generated from this type of view is a 2-columned table displaying information obtained from an entity set. For the chosen entity set, you are required to choose the fields you would like to display which will then become the table row headers. The first column displays the entity set field and the second column displays the field value.

140

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

In addition, you can add the generated details view the option of editing the information obtained from an entity set. The relationship between the views is based on the association between the entity sets. After youve selected an entity set for the first view (for example, Customers), in the second view you can only select an entity set that is associated to it (for example, Banks) or you can choose to display the details of the entity set you selected for the first view (for example, Customers). To configure the views in a List/Details application, proceed as follows: 1. 2. 3. 4. In the View Title field, enter the name of the first view. From the View Type drop-down list, the List view option is automatically selected. From the Entity Set Navigation drop-down list, select the desired entity set. Select additional operations you would like to support from the view. For views of type List the following options are available: Select the Add Create Option checkbox if you would like to add this list view the option of creating new items. Select the Add Edit Option checkbox if you would like to add this list view the option of deleting displayed items. For views of type Details, select the Add Edit Option checkbox if you would like to add this details view the option of editing the displayed item.

You can choose to add the view an option to perform an operation that is described above (creation, deletion or editing of the entity set items), only if this operation is supported by the selected entity set. 5. 6. 7. 8. 9. Choose Add (+) to see the fields available for the selected entity set. The Add Fields page is displayed. Select the checkboxes of the desired fields for the view. It is recommended not to include more than three or four fields in a list. Click OK. If needed, select a field and click Remove (-) to delete it. Use the Up and Down arrows to change the positioning of the fields in the view. The field positioned first in the list will appear bold in the relevant generated applications list view.

10. In the Views section, choose to Add (+) another view. 11. Repeat this procedure to configure the additional views.

8.3.3

Working with the Generated HTML5 Starter Application

Examples of generated projects for the HTML5 applications, and a description of possible customizations and extensions. The generated project is an Eclipse Web project, which references the required resources to help in writing HTML and JavaScript code. This also includes a reference to the JavaScript library that enables Eclipse to detect syntax errors and to provide intellisense. The main folder of the generated project is the WebContent folder. This folder contains all the HTML, JavaScript, and CSS files required to run the Web application. The generated files and code depend on the selected template and the pages you defined in the wizard. You can modify and extend the generated code for the HTML5 starter application to suit your needs.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

141

The Generated JQuery Mobile Application


The generated project consists of the following elements: index.html lib scripts images

The index.html File The index.html file is the main entry point to the Web application. The <head> element in the file includes references to all the style sheet (CSS) and JavaScript (JS) files needed to run the application. The <body> element renders all the pages of the application. Each page is a <div> element with the data-role attribute set to page. You can add <div> elements to create additional pages or edit existing ones. The lib Folder The lib folder contains all the external third party libraries and their dependencies. jQuery (jquery-1.6.4.js) jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript. jQuery Mobile (jquery.mobile-1.0.1.js) Touch-Optimized Web Framework for Smartphones & Tablets. A unified, HTML5-based user interface system for all popular mobile device platforms, built on the rock-solid jQuery and jQuery UI foundation. Its lightweight code is built with progressive enhancement, and has a flexible, easily themeable design. jQuery Mobile also includes the following CSS files:

142

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

jquery.mobile-1.0.1.css jquery.mobile.structure-1.0.1.css

images The images subfolder contains the images required by the jQuery Mobile library.

Note
Do not remove files from this folder. datajs-1.0.2.js This is an external third party library. It is a cross-browser JavaScript library that enables data-centric Web applications by leveraging modern protocols, such as, JSON, OData, and HTML5-enabled browser features. It is designed to be small, fast and easy to use. To update the libraries: It is possible to update the above libraries by downloading new versions from their respective sites and replacing the files in the project. Note that you have to update all dependencies (jQuery Mobile is dependent on jQuery) and all references to these libraries in the index.html. The scripts Folder The scripts folder contains all of the JavaScript files generated by the toolkit that are required to run the application. app.js Contains functions used to handle navigation between pages in the index.html file. In addition, it contains global functions for formatting data. This file makes the code in the index.html file cleaner and more concise. Modify this file if you want to change or add functionality. connectivity.js Contains the functions that handle HTTP calls to the SAP NetWeaver Gateway service by using the dataJS library, and handles request errors that might occur. This file also contains the definition of the service URL and SAP client.

Note
Make sure to change this file if the service URL or SAP client changes. service_labels.js Contains the sap-labels for the properties for all the entities defined in the chosen service metadata. This is used in the index.html file to display the labels to the user. The images Folder The images folder contains SAP logos that are used only on iOS devices when a shortcut is created for the web application. Replace these icon files with your own company icons to customize the generated application. Styling and Themes

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

143

The application uses the jQuery Mobile CSS file for runtime user interface styling. The themes of the header, content, and filter of each application page are defined in the mobileinit event handler of the document object, defined at the <head> section of the index.html file: $.mobile.page.prototype.options.headerTheme = "a"; $.mobile.page.prototype.options.contentTheme = "c"; $.mobile.listview.prototype.options.filterTheme = "c";

You can modify the selected themes as needed.

The Generated SAPUI5 Application


The generated project consists of the following elements: index.html resources images

144

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

The index.html File The index.html file is the main entry point to the Web application. The <head> element in the file includes a reference to the styelsheet (CSS) file used in the application, and a definition of the SAPUI5 library location and preferences. In addition, this element includes a script for displaying the first application view. The <body> element includes a single <div> element for displaying the application content.

Note
Make sure to set the location of the SAPUI5 library appropriately in this file, as described in the Running the SAPUI5 Application section. The resources Folder

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

145

The resources folder contains all of the JavaScript files generated by the toolkit that are required to run the application. View and Controller files The view and controller files contain the code of the application views. The files are designed according to the Model-View-Controller architecture concept. Each file may represent one or two application views, according to the application internal logic. utils/connectivity.js Contains the definition of the service URL. The URL may also include a SAP client definition using the sapclient query parameter.

Note
Make sure to change this file if the service URL or SAP client changes. utils/utility.js Contains utility functions to handle localization, error handling and date formatting. globalization/i18n.properties Contains all the application strings, including the sap-labels for the properties for all the entities defined in the chosen service metadata. The file is used to support the application localization. The images Folder The images folder contains SAP logos that are used on the generated application. Replace these icon files with your own company icons to customize the generated application. Styling and Themes The application uses the styles.css file supplied with the generated application, and the themes supplied with the referenced SAPUI5 library. The selected theme of the application UI controls created by the SAPUI5 library is defined at the <head> section of the index.html file: data-sap-ui-theme="sap_goldreflection" You can modify the selected theme as needed. Related Links

http://jquery.com/ http://jquerymobile.com/ http://datajs.codeplex.com/ http://jquerymobile.com/test/docs/api/themes.html Running the SAPUI5 Application [page 134] Before you can run the generated SAPUI5 application, you must edit the index.html file to set the location of the SAPUI5 libraries.

8.3.4

JQuery Mobile Application Deployment

Options for deploying a web application to mobile devices The generated JQuery mobile application targets mobile devices. There are several options for deploying a web application to mobile devices:

146

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

Run the application on a dedicated web server and navigate to the server from a web browser on the device. Run the application on a dedicated web server and build a native device specific application that wraps a web browser control. Run the application locally on the mobile device by building a native device specific application that wraps a web browser control, but also contains all the html, css, and js files required to run the application locally on the device.

If you choose to implement one of the first 2 options, make sure to configure the web server as a reverse proxy for the SAP NetWeaver Gateway server to prevent the browser from blocking your requests due to Cross-Origin Resource Sharing. In addition, make sure to appropriately edit the domain of the service URL defined in the application. For more information, see the Configure the Generated Application to Use a Reverse Proxy section. For the second and third options, there are 3rd party solutions which help produce the native wrapper application such as: PhoneGap Titanium Corona

Related Links

http://en.wikipedia.org/wiki/Cross-origin_resource_sharing http://phonegap.com/ http://www.appcelerator.com/ http://www.anscamobile.com/ Configuration of the Generated Application to Use a Reverse Proxy [page 148] Explanation of the necessary configuration to use a reverse proxy.

8.3.5

Running the SAPUI5 Application

Before you can run the generated SAPUI5 application, you must edit the index.html file to set the location of the SAPUI5 libraries. To set the location of the SAPUI5 libraries: 1. 2. 3. Open the the index.html file located in the WebContent directory. Search for the following line in the Script tag:src="./sapui5-static/resources/sap-ui-core.js" Replace the text in quotation marks by a link to the location where the files for SAPUI5 are located. If you download the SAPUI5 library and deploy it with your application, the location should indicate the relative path of the library in your application. Alternatively, you can set this location with the URL of a remote location hosting this libraries. The generated SAPUI5 application targets desktops. For deploying the application, run it on a dedicated web server and navigate to it from a web browser. Make sure to configure the web server as a reverse proxy for the SAP NetWeaver Gateway server to prevent the browser from blocking your requests due to Cross-Origin Resource Sharing. In addition, make sure to appropriately edit the domain of the service URL defined in the application. For more information, see the Configure the Generated Application to Use a Reverse Proxy section. Related Links

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

147

http://en.wikipedia.org/wiki/Cross-origin_resource_sharing Configuration of the Generated Application to Use a Reverse Proxy [page 148] Explanation of the necessary configuration to use a reverse proxy.

8.3.6 Configuration of the Generated Application to Use a Reverse Proxy


Explanation of the necessary configuration to use a reverse proxy. Due to security reasons, the browser only allows the JavaScript code to access the server from which the page/ script originated. In our case, the HTML page/script (including the SAPUI5 library code - in the relevant applications) is provided by the web server, but the OData feed is provided by the SAP NetWeaver Gateway server. The URLs used for calling SAP NetWeaver Gateway services from the JavaScript code must use the domain of the reverse proxy (host, port, and protocol). The reverse proxy identifies the Gateway path in the request URL (for example: /sap/opu/odata/) and sends the request to the SAP NetWeaver Gateway server. This server then sends the response directly to the client. To use the domain of the reverse proxy in the application's outgoing requests, open the connectivity.js file and change the serviceUrl variable to point to the web server hosting the application (configured to use the reverse proxy for incoming requests) instead of the SAP NetWeaver Gateway server. For example, lets assume that the web server URL is: http://webserver1:1234/myjqmobileapp and the SAP NetWeaver Gateway service URL is: http://gatewayserver:50028/sap/opu/odata/iwfnd/mygwservice In this example, you should replace the following code line: var serviceUrl = "http://gatewayserver:50028/sap/opu/odata/iwfnd/mygwservice/"; With this: var serviceUrl = "http://webserver1:1234/sap/opu/odata/iwfnd/mygwservice/";

8.3.7

Security of the Generated HTML5 Applications

The generated applications support basic authentication that uses the browser pop-up dialog for user credentials.

148

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

8.3.8

Troubleshooting for the Toolkit for HTML5 (GWPA)

Troubleshooting suggestions. JSON Parse Exception in IE9 Issue When running the generated application using IE9 RC1 with an SAP NetWeaver Gateway service supporting JSON, the following error is displayed: "Unable to get value of the property 'parse': object is null or undefined". Solution Disable displaying sites in compatibility view in your IE9 web browser by selecting Settings and unchecking the option Display internet sites in Compatibility View. Page Compatibility View

Language Support in generated code Issue Generated code text in languages other than English is not displayed properly. Solution To enable all characters to be displayed, follow the instructions in the Supporting Lauguages other than English section of the Installation Guide and regenerate the code. Related Links

Supporting Languages other than English https://help.hana.ondemand.com/gateway_gwpa/pdf/ SAP_NetWeaver_Gateway_Productivity_Accelerator_Inst_Guide_en.pdf

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

149

8.4

Toolkit for iOS (GWPA)

Toolkit for service consumption for iOS platform. If you want to use the Toolkit for iOS (GWPA), you must install the feature Toolkit for iOS (GWPA). Related Links

https://help.hana.ondemand.com/gateway_gwpa/pdf/ SAP_NetWeaver_Gateway_Productivity_Accelerator_Inst_Guide_en.pdf

8.4.1

Creating a Starter Application Project for iOS

Explains how to create a starter application for iOS to consume the data published by an OData service in SAP NetWeaver Gateway. You can create one of the following starter applications for iOS. All these applications support iPhone and iPad. Basic Starter Application Generates a starter application for consuming the SAP NetWeaver Gateway service. The generated application has a sample UI view, and contains a semantic proxy and a Request Handler that is responsible for the Gateway connectivity and parsing of the service data. Form Starter Application Generates a starter application which displays a form for creating SAP data in the SAP business system. List/Details Starter Application Generates a starter application for utilizing SAP data in list and details screens. Workflow Starter Application Generates a starter application which displays the Workflow task information and allows the user to make a decision on the task.

The generated application is an Xcode project, which also contains a proxy for the service selected in the wizard. To create your iOS starter application, proceed as follows: 1. From menu bar, select File New Other . The New wizard dialog is displayed.

150

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2. 3.

Expand the OData Development node and select Starter Application Project. Choose Next. The New Starter Application Project page is displayed.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

151

4. 5. 6. 7. 8. 9.

In the Project name field, enter a new name for your project. From the Create a new project for drop-down list, select iOS. Choose Browse to navigate to the location where you want to create the Xcode project. Choose Open. The selected location is displayed in the Folder path field. Choose Next. Select the desired template. The wizard provides different options depending on the template you select.

152

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

10. Choose Next. The Location of OData Service page is displayed.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

153

11. Select the desired SAP NetWeaver Gateway service in one of the following ways: In the Service URL field, enter the desired services URL and then choose Go to validate the servie metadata. Choose Catalog and select the desired SAP service using the Service Catalog dialog. Select the File system radio button and browse for the relevant service metadata and service document.

12. Configure the application based on the selected application type. For the List/Details template, click Next to continue with the wizard as described in Defining the List/ Details Page Layout topic. For the Form template, click Next to continue with the wizard as described in the Defining the Form Layout topic. The Workflow and the Basic templates do not require further configuration.

13. Choose Finish. The created projects folder is displayed in the location you previously specified.

154

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

14. Double click on the Xcode project file to open it. You can now build and run the application.

Note
If your service URL is secured by SSL and you need a certificate to validate it, make sure the certificate is installed on the device before running the application.

Note
It is recommended to change the product name or bundle identifier unique name after the generation is complete as described in the Changing the Bundle Identifier and the Changing the Product Name sections for productizing the application. Related Links

Defining the SAPUI5 List/Details Page Layout [page 140] Explains how to define the application for List/Details. Defining the Form Layout in the Toolkit for iOS (GWPA) [page 158] Explains how to define the Form application for consuming the data published by your OData service in SAP NetWeaver Gateway. Defining the List/Details Page Layout for the Toolkit for iOS (GWPA) [page 156] The List/Details application is created by selecting a service and defining its views. Defining the Form Layout in the Toolkit for iOS (GWPA) [page 158] Explains how to define the Form application for consuming the data published by your OData service in SAP NetWeaver Gateway. Changing the Bundle Identifier [page 160] Explains how to change the bundle identifier in the generated application.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

155

8.4.1.1 Defining the List/Details Page Layout for the Toolkit for iOS (GWPA)
The List/Details application is created by selecting a service and defining its views. For each view, you must select one of the following types: List The UI generated from this type of view is a table displaying information obtained from an entity set. For the chosen entity set, you are required to choose the fields you would like to display which will then become the table column headers. For example, the Customer entity set will have fields such as Customer Name, Country, Street, Telephone Number, and so on. In addition, you can add to the generated list view the option of creating new items into the chosen entity set, or of deleting existing items. Details The UI generated from this type of view is a 2-columned table displaying information obtained from an entity set item. For the chosen entity set, you are required to choose the fields you would like to display which will then become the table row values. The first column displays the entity set field name and the second column displays the field value. In addition, you can add the generated details view the option of editing the data obtained from an entity set item.

The relationship between the views is based on the association between the entity sets. After youve selected an entity set for the first view (for example, Customers), in the second view you can only select an entity set that is associated to it (for example, Banks) or you can choose to display the details of the entity set you selected for the first view (for example, Customers). To configure the views in a List/Details application: After defining the application details as described on the Creating a Starter Application Project (steps 1-12), the View Layout page is displayed.

156

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

1. 2. 3. 4.

In the View Title field, enter the title for the first view. From the View Type drop-down list, the List view option is automatically selected. From the Entity Set Navigation drop-down list, select the desired entity set. Select additional operations you would like to support from the view. For views of type List the following options are available: Select the Add Create Option checkbox to add the option of creating new items. Select the Add Delete Option checkbox to add the option of deleting items.

For views of type Details, the following option is available: Select the Add Edit Option checkbox to add the option of editing the displayed item.

Note
You can choose the operations described above only if they are supported by the selected entity set. 5. Choose Add (+) to see the fields available for the selected entity set. The Add Fields page is displayed.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

157

6. 7. 8. 9.

Select the checkboxes of the desired fields for the view. For usability reasons, it is recommended not to include more than three or four fields in a list. Click OK. If needed, select a field and click Remove (-) to delete it. Use the Up and Down arrows to change the positioning of the fields in the view. The field positioned first in the list will appear bold in the relevant generated applications list view.

10. In the Views section, choose to Add (+) another view. 11. Repeat this procedure to configure the additional views. Related Links

Creating a Starter Application Project for iOS [page 150] Explains how to create a starter application for iOS to consume the data published by an OData service in SAP NetWeaver Gateway.

8.4.1.2 Defining the Form Layout in the Toolkit for iOS (GWPA)
Explains how to define the Form application for consuming the data published by your OData service in SAP NetWeaver Gateway. To create the Form application, you select an OData service and define the entity set and properties to be used. To configure the Form layout: 1. Define the application details as described on the Creating a Starter Application Project for iOS section. At the end of this procedure, the Form Template Layout page is displayed.

158

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2. 3.

In the Form Title field, enter a title for the form. From the Entity Set drop-down list, select the desired entity set. The generated Form application will enable creating enties for this entity set.

Note
Only entity sets to which you can add new entries (as defined in the service metadata) are displayed.

Note
Entity sets that are not directly accessible at runtime (as defined in the service metadata) can be selected but the generated applications code must be edited to access those entity sets appropriately. For more information, see the Modifing the Generated Form Application to Create an Entity in a Non-Addressable Collection section.

The required fields for the selected entity set are displayed in the fields table and can be identified by the icon.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

159

4.

Choose Add (+) to see the fields available for the selected entity set. The Add Fields page is displayed.

Note
Only properties of supported types are displayed (currently, properties of type Edm.Binary are not supported in the generated form applications).

5. 6. 7.

Select the checkboxes of the fields you want to add to the form view. Click OK. If needed, select a field (or multiple fields) and click Remove (-) to delete.

Note
Required fields cannot be removed. 8. Use the Up and Down arrows to change the positioning of the fields in the form view.

Related Links

Creating a Starter Application Project for iOS [page 150] Explains how to create a starter application for iOS to consume the data published by an OData service in SAP NetWeaver Gateway. Modifing the Generated Form Application to Create an Entity in a Non-Addressable Collection [page 231] Some collections may be creatable, but they are not addressable, meaning they can only be accessed from a navigation property. For example, when a user has several communication methods (email, telephone, etc.), creating a new communication method to a specific user by using a navigation property from the user to his/her communication methods, is a valid scenario. However, adding a communication method to a list of all communication methods is not possible.

8.4.1.3

Changing the Bundle Identifier

Explains how to change the bundle identifier in the generated application.

160

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

To change the bundle identifier: 1. 2. In the Xcode Project Navigator, select Supporting Files [Your Project Name]-info.plist .

In the table displayed, search for the Bundle identifier field and edit it as needed.

Example

8.4.1.4

Changing the Product Name

Explains how to change to the product name in the generated application. To change the product name: 1. 2. 3. 4. 5. In the Xcode Project Navigator, select your project. Under Targets, select the target for which you want to change the product name. Select the Build Settings tab. Search for the Product Name property. Edit the product name as needed.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

161

8.4.2

Creating Proxies for an iOS Application

Explains how to generate a proxy to enable an iOS application to consume OData services using SAP NetWeaver Gateway. You can create a proxy for an iOS application to consume SAP services through your SAP NetWeaver Gateway server. The proxy provides the implementation interfaces for the SAP service you choose to use. You must create your own application to interface with the generated proxy. To create your proxy: 1. From the menu bar, select File New Other . The New wizard dialog is displayed.

162

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2. 3.

Expand the OData Development node and select Service Proxy. Choose Next. The Create New Proxy page is displayed.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

163

4. 5.

From the Create a new proxy for drop-down list, select iOS. Choose Browse to navigate to the location where you want to create the proxy.

Note
If you want to add (or overwrite) a service proxy to an application that already contains a generated proxy code (for example, a generated starter-kit application), make sure you select the folder directly containing the existing application code files and particularly the GeneratedProxy sub-folder as your generation target. 6. 7. Choose Open. The selected location is displayed in the Folder path field. Choose Next. The Location of OData Service page is displayed..

164

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

8.

Select the desired SAP NetWeaver Gateway service in one of the following ways: In the Service URL field, enter the desired services URL and then choose Go. Choose Catalog... and select the desired SAP service using the Service Catalog dialog.. Select the File system radio button and browse for the relevant service metadata and service document.

When the service is validated, its details are displayed. 9. Choose Finish. The created proxy folder is displayed in the location you previously specified.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

165

Once you have generated the proxy, your target folder will contain a GeneratedProxy folder with the following: An SDMLibs folder containing the SAP OData Mobile Client SDK libraries and header files. A Services folder containing the following: A Framework folder containing the proxys base classes and helper classes. A Resources folder containing the service document and metadata XMLs for the selected service. The proxy classes .h and .m files for the selected service.

Note
The proxy file names and the classes defined in them contain the technical service version of the selected service. A [Service Name]ServiceDeclarations.h file containing aliases for all the proxy class names, to allow referring them without using the technical service version. A [Service Name]RequestHandler class .h and .m files which uses the proxy into semantic objects and the framework classes for sending the service requests, parse the service response, and post the appropriate notification once the response was received. For more information, see the About the Service Request Handler Class section.

Note
The [Service Name]RequestHandler class is based on the OData service and not based on version. Related Links

About the Service Request Handler Class [page 189] The generated proxy also includes a Request Handler class for the selected service. The Request Handler is a singleton class that uses the proxy and the framework classes to send the service requests, parse the service response, and post the appropriate notification once the response was received.

8.4.2.1

Adding a Proxy to an Existing Xcode Project

Explains how to add the proxy you have generated to an Xcode project. To add the proxy to your existing Xcode project:: 1. In Xcode, from the File menu, open your project.

Note
The project that the generated proxy files are added to must use Automatic Reference Counting (ARC). If your project was not created using ARC, you must change it to ARC before it can be compiled: 1. 2. 3. Select your project. Select the project target. On the Build Settings tab, set the Objective-C++ Automatic Reference Counting to Yes.

166

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

4.

On the Build Settings tab, set the Objective-C Automatic Reference Counting to Yes.

2.

Drag the Services folder into your project.

Note

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

167

If your application already contains a generated proxy code for a different service, or for the same service in a different technical service version (for example, a generated starter-kit application), drag only the following files from the Services folder into the Services group of your project: The [Service Name]RequestHandler.h and [Service Name]RequestHandler.m files which contain the request handler class based on the selected generated service. (Only if these files are not already included in your project.) The [Service Name]ServiceDeclarations.h file which contains the aliases of the proxy class names for the selected service. (Only if this file is not already included in your project.) The [Service Name]Service[Version].h and [Service Name]Service[Version].m files which contain the proxy classes for the selected service. The service document and metadata XMLs for the selected service: Resources/[Service Name]ServiceMetadata[Version].xml and Resources/[Service Name]ServiceDocument[Version].xml files (make sure to drag these files to the Services/ Resources group of your project). 3. Drag the folder containing the SAP OData Mobile Client SDK client libraries and header files into your project.

4.

Check that the libraries were added. 1. 2. 3. 4. Select your project. Under Targets, select your target. Select the Build Phases tab. Open the Link binaries with libraries section and make sure it contains the following files: libSDMConnectivity, libSDMParser and libSDMSupportability.

168

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

5.

Link the following iOS frameworks/libraries to your project: CFNetwork.framework MessageUI.framework MobileCoreServices.framework SystemConfiguration.framework Libz.1.2.5.dylib

6.

Add the required linker flags. 1. 2. 3. 4. Select the Build Settings tab. Open the Linking section and select Other Linker Flags. Add the -ObjC and all_load parameters. Click Done.

7.

Verify that the service document and metadata files are included in the bundle resources. 1. 2. 3. Select the Build Phases tab. Open the Copy Bundle Resources section. Verify that the service document and metadata files are included. If not, add them from the /Services/ Resources group.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

169

Related Links

Further information on SAP OData Mobile SDK configuration

8.4.2.2

Creating Proxies with Multiple Backend Support

Explains how to enable proxies to communicate between an SAP NetWeaver Gateway system and more than one SAP Business Suite backend system. SAP NetWeaverGateway supports multiple destinations, which means one SAP NetWeaver Gateway system with multiple backends. To ensure that an entitys backend system can be identified, an additional key field (SAP__ORIGIN) is added to each entity and filled with the corresponding system alias. This must be triggered explicitly by the client. This is done by setting the segment parameter ;mo (Multiple Origin), indicating that the service in its MOC version is being called. To generate proxies that support multiple backend systems: 1. Open your web browser to download the service document and metadata XMLs from SAP NetWeaver Gateway with the additional multiple origin segment parameter. For example; http://<host name>:<port>/sap/opu/odata/iwfnd/RMTSAMPLEFLIGHT;mo/ http://<host name>:<port>/sap/opu/odata/iwfnd/RMTSAMPLEFLIGHT;mo/$metadata Create a proxy as described in section Creating Proxies for an iOS Application [page 162] On the Service Selection page, choose the File System option. Browse and select your local service document and metadata files. Click Validate to validate the selected files. Choose Finish to generate the proxy.

2. 3. 4. 5. 6.

8.4.2.3 Creating Proxies that Support Multiple Service Versions


Explains how to generate proxies to support more than one OData service version. Different versions of an OData service can often exist. To generate proxies that support multiple service versions:

170

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

1.

Generate a proxy or Starter Kit application using the service of your choice (for example, RMTSAMPLEFLIGHT service of version 1). Under the GeneratedProxy/Services folder, the service proxy classes, metadata, and service documents files, are displayed with a suffix that includes the service version. For example, RMTSAMPLEFLIGHTServiceV1.h RMTSAMPLEFLIGHTServiceV1.m RMTSAMPLEFLIGHTServiceDocumnetV1.xml RMTSAMPLEFLIGHTServiceMetadataV1.xml The RMTSAMPLEFLIGHTServiceDeclarations.h file contains aliases to all the entities and complex types defined in the proxy file, which allows you to refer them in the application without using the technical service version. The RMTSAMPLEFLIGHTRequestHandler class uses the aliases declared in the declarations file above, and therefore is version independent.

2.

Generate a proxy for a different version of the service selected in step 1 (for example, version 2). Make sure to select the folder that directly contains the GeneratedProxy folder generated in step 1 as the generation target. (For example, if you generated a starter-kit application named FlightsApp in step 1, select the FlightsApp/ FlightsApp folder as the second proxy generation target). Under the GeneratedProxy /Services folder, the newly created service proxy classes, metadata, and service documents files, are displayed with a suffix that indicates this is a different version (for example, version 2). For example, RMTSAMPLEFLIGHTServiceV2.h, RMTSAMPLEFLIGHTServiceV21.m, RMTSAMPLEFLIGHTServiceDocumnetV2.xml, RMTSAMPLEFLIGHTServiceMetadataV2.xml. In the RMTSAMPLEFLIGHTServiceDeclartions.h file, the import statement is updated with RMTSAMPLEFLIGHTServiceV2 and the aliases of the entities and complex types defined in the proxy file are updated to RMTSAMPLEFLIGHTServiceV2. In this way, the application code uses the last generated service version code. This affects also the RMTSAMPLEFLIGHTRequestHandler which uses the aliases, that are now points to the objects of RMTSAMPLEFLIGHTServiceV2.

3.

Once the OData service is generated with the new version, add the new files to your project and update the service URL default value (in the settings bundle) to the service URL of the new version. In addition, update the minimum and maximum service versions supported by the application by setting the appropriate values for the TechnicalServiceVersionMin and TechnicalServiceVersionMax constants located in the [Service Name]RequestHandler.m file.

8.4.3

Using the Proxy in your iOS Application

This section provides code snippets showing how to use the generated proxy in your application. The examples show proxy classes generated from the RMTSAMPLEFLIGHT service. For further information, you can use the comments included in the Framework and generated proxy header files.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

171

8.4.3.1

Importing the Service Proxy Classes

Explains details of what to consider when importing service proxy classes. The service proxy files include the service proxy object and classes representing all the service entities and complex types. To support proxies of multiple service versions, all the service classes include a suffix with the service technical version (if the version is unknown, V0 is used as a suffix). Nevertheless, you can keep the application code independent of a specific service version where it is not necessary. In this case, use the declerations header file generated with the service proxy, including the aliases for all the service class names. It is recommended to import the service declarations header file and use the class name aliases without specifying a specific version to use the service proxy classes. #import "RMTSAMPLEFLIGHTServiceDeclarations.h"

Note
If a version specific code is required, you must use the exact class name (including the version suffix) and import the service proxy file of the required version. #import "RMTSAMPLEFLIGHTServiceV1.h"

8.4.3.2

Initiating the Service Proxy Object

Explains how to initiate the service proxy object. The service class contains methods that allow you to obtain collections and specific items within these collections for all the entity sets in the service. The service class also contains all the function import methods that the service exposes. 1. To initiate the service proxy object, use the following command: RMTSAMPLEFLIGHTService *service = [[RMTSAMPLEFLIGHTService alloc] init];. The service init method expects the service document and metadata XMLs to be present in the </Services/Resources> folder. 2. There is also an option to retrieve the service document and metadata NSData during the runtime of the application and use them to initiate the service proxy object using the following command: RMTSAMPLEFLIGHTService *service = [[RMTSAMPLEFLIGHTService alloc] initWithServiceDocument:serviceDocResponse andMetadata:serviceMetadataResponse];. 3. The service URL used for calculating the service queries is taken from the service document data used to initiate the service proxy object. You can set this URL using the service's setServiceDocumentUrl: (NSString *)baseUrl method. You must verify the service proxy object was initiated successfully before using it. if (service) { // work with the semantic proxy as needed }

Note
You must iniate the service proxy object in your application before initiating an entity class or using the entity class methods.

172

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

8.4.3.3 Executing Requests Using the Connectivity Helper Class and Authenticating Protocol
Explains how to use the connectivity helper class and authenticating protocol to execute requests. The SDMConnectivityHelper is a helper class for creating and executing HTTP requests using the SAP OData Mobile Client SDK connectivity library. 1. 2. To iniate the SDMConnectivityHelper object, use the following command: SDMConnectivityHelper *connectivityHelper = [[SDMConnectivityHelper alloc] init]; To add user authentication information to send requests: The SDMConnectivityHelper helper class does not add any user authentication information to the requests sent using its methods. To get a reference to the HTTP request object before sending it to the server, and to set the user credentials in the request object, you can implement the SDMConnectivityHelperDelegate protocol and register as the helper class delegate. { (void)onBeforeSend:(id<SDMRequesting>)request request.username = @"<user>"; request.password = @"<password>"; self;

} connectivityHelper.delegate =

Another option for performing user authentication, is to use the Authenticating protocol. The protocol provides a method for sending a synchronous HTTP GET request with the user authentication information provided when the class implementing the protocol is initiated. The generated proxy provides the following Authenticating protocol implementations: UsernamePasswordAuthenticator for Basic and Integrated/NTLM user authentication (with the SAP NetWeaver Gateway server, or with the Identity Provider server when using SAML2 protocol), which requires user name, password, and domain (the latter is optional). It is also used for SUP authentication, passing the user name and password according to the specified authentication protocol (X.509, Portal SSO, and Basic) in the SUP server. For example, for the X.509 authentication protocol, the user name is the subject of the client certificate and the password is the base64 encoding of the certificate. PortalAuthenticator for user authentication using SAP Portal (and forwarding the received SAP Logon Ticket). CertificateAuthenticator for user authentication using the X.509 client certificate.

Once the request is successfully sent using the Authenticating object and a session cookie is returned from the server, the next requests do not require user authentication information. It is recommeded to configure the SAP NetWeaver Gateway to support this behavior.

Note
This is not relevant if you are using certificate authentication. Therefore, it is recommended to perform the authenticated request using the Authenticating object one time in the user login process of the application, and then use the SDMConnectivityHelper object without adding the user credentials for each of the following requests using the SDMConnectivityHelperDelegate protocol implementation.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

173

Moreover, the supplied UsernamePasswordAuthenticator and PortalAuthenticator implementations save the received user credentials on the device, and uses the saved credentials if no user credentials are provided when the authenticator object is initiated. If the authentication fails, the authenticator deletes the saved credentials. This behavior can be used for implementing Single Sign-On (SSO) in your application.

Note
You can check if there are user credentials already saved on the device using the isCredentialsSaved method of the KeychainHelper class. An example of using the UsernamePasswordAuthenticator object for user authentication: id<Authenticating> authenticator; if ([KeychainHelper isCredentialsSaved]) { authenticator = [[UsernamePasswordAuthenticator alloc] init]; // Use the saved credentials } else { authenticator = [[UsernamePasswordAuthenticator alloc] initWithUsername:@"domain\user" andPassword:@"password"]; } RMTSAMPLEFLIGHTService *service = [[RMTSAMPLEFLIGHTService alloc] init]; // Execute the first request using the authenticator class for user authentication NSData* serviceDocData = [authenticator authenticateWithODataQuery:service.ServiceDocumentQuery error:nil]; if (serviceDocData) { NSLog(@"User authenticated successfully"); } When using the certificate authentication method, the certificate must be sent on each consecutive call. Therefore, when the application loads, it reads the certificate file from the file bundle named "client_certificate.pfx", adds it to the Keychain if it doesn't exist, and later on loads in from the keychain and sends it in each request. Related Links

http://help.sap.com/saphelp_gateway20sp06/helpdata/en/89/ea6a0543dc4e13b20b3462f57d7404/ frameset.htm

8.4.3.4

Getting a Collection

Explains how to retrieve a collection query. To get a collection, proceed as follows: 1. 2. Get the collection query from the service objects <Collection Name>Query property. Execute an HTTP GET request to get the FlightCollection. For example, use the executeBasicSyncRequestWithQuery:(ODataQuery *)aQuery method for executing a simple synchronous request. id<SDMRequesting> request = [connectivityHelper executeBasicSyncRequestWithQuery: service.FlightCollectionQuery];

174

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

3.

Get the response data and pass it to the services getFlightCollectionWithData:(NSData *)aData error:(NSError **)error method. NSData *itemsResponseData = request.responseData; NSError* error = nil; NSMutableArray *flights = [service getFlightCollectionWithData:itemsResponseData error:&error];

The method returns an array of Flight objects. if (!error) { // work with the Flight semantic object as expected for (Flight *flight in flights) { NSLog(@"carrid = %@",flight.carrid); NSLog(@"connid = %@",flight.connid); NSLog(@"airportFrom = %@",flight.flightDetails.airportFrom); } }

8.4.3.5

Service Query Parameters

Introduces concept of service query parameters. You use the ODataQuery object to add OData or custom query parameters to your query. ODataQuery *query = service.FlightCollectionQuery; [query addParameterWithKey:@"$top" andValue:@"10"]; The ODataQuery object also contains dedicated method for the $expand, $filter, $orderby and $select query parameters: (void)expand:(NSString *)expandStringValue; (void)filter:(NSString *)filterStringValue; (void)orderBy:(NSString *)orderByStringValue; (void)select:(NSString *)selectStringValue;

8.4.3.6 Object

Getting the Collection Entry Using an Existing Entity

Explains one of two possible scenarios for getting a specific collection entry. This scenario explains how to use an existing entity object to get the collection. In this scenario, you already have the entry object (for example, after performing a call to get a collection entries), but you need to perform another service call for this specific entry to get the values for all entity properties (or all navigation properties using expand). For example, when this entry was selected in the UI and should be displayed in the next application view. The additional call is required because, to reduce the response payload volume, some services do not return values for all entity properties when the entry is part of a collection response. To get the entry, proceed as follows: 1. 2. Create the query for the desired Carrier entity using the baseUrl property of the entity object.ODataQuery * carrierQuery = [[ODataQuery alloc] initWithURL:aCarrier.baseUrl]; Execute an HTTP GET request to get the entry data. For example, use the executeBasicSyncRequestWithQuery:(ODataQuery *)aQuery method for executing a simple

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

175

synchronous request. id<SDMRequesting> request = [connectivityHelper executeBasicSyncRequestWithQuery:carrierQuery]; 3. Get the response data and pass it to the services getCarrierCollectionEntryWithData:(NSData *)aData error:(NSError **)error method. NSData *itemResponseData = request.responseData; NSError* error = nil; Carrier *carrier = [service getCarrierCollectionEntryWithData:itemResponseData error:&error]; The method returns a Carrier object. (Make sure you use only this new updated entity object to represent this Carrier entity in your application). if (!error) { // work with the Carrier semantic object as expected NSLog(@"CARRNAME = %@", carrier.CARRNAME); NSLog(@"URL = %@", carrier.URL); }

Note
There is also an option to parse a Carrier entry data into a Carrier object using the parseCarrierEntryWithData:(NSData *)aData error:(NSError **)error method of the Carrier class. Carrier *carrier = [Carrier parseCarrierEntryWithData:itemResponseData error:&error]; To use entity class's parse<Entity Name>EntryWithData:(NSData *)aData error:(NSError **)error or parse<Entity Name>EntriesWithData:(NSData *)aData error:(NSError **)error methods, you must first initiate the service object or call the loadEntitySchema: (SDMODataServiceDocument *)aService class method.

8.4.3.7 Getting the Collection Entry Using Values for Key Properties
Explains one of two possible scenarios for getting a specific collection entry. This scenario explains how to use values for key properties to get the collection. In this scenario, you do not have the entry object from a previous service call. Instead, you have the values of the key properties for the desired entity (for example, as input parameters from the UI). To get the entry, proceed as follows: Get the query for the desired CarrierCollection entry from the service proxy object: Using typed parameters holding the values for the key properties. ODataQuery *carrierQuery = [service getCarrierCollectionEntryQueryTypedWithCarrid:@"AA"]; Pass only the values of the key properties and the method takes care of converting them to the appropriate URI format.

Note

176

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

This option is available only for OData-compliant services. Using generic parameters holding the values for the key properties as they will appear in the query URL. ODataQuery *carrierQuery = [service getCarrierCollectionEntryQueryWithCarrid:@"'AA'"]; You must provide the values for the key properties to the service method above, exactly as they will appear in the query URL, in the correct format, according to the property types (as defined in the OData protocol: Abstract Type System For example: the carrid key property of the Carrier entity is of type Edm.String, and therefore its value should be provided within single quotation marks, for example: 'AA'. Related Links

Getting the Collection Entry Using an Existing Entity Object [page 175] Explains one of two possible scenarios for getting a specific collection entry. This scenario explains how to use an existing entity object to get the collection.

8.4.3.8

Performing a Navigation Query

Explains how to perform a navigation query. To perform a navigation query, proceed as follows: 1. 2. 3. Get the navigation query from the entity objects <Navigation Name>Query property. Execute an HTTP request using the query and get the response data.id<SDMRequesting> request = [connectivityHelper executeBasicSyncRequestWithQuery: aFlight.FlightCarrierQuery]; Use the entity objects load<Navigation Name>WithData:(NSData *)aData error:(NSError **)error method to load the response data into the entity object.NSData *carrierItemResponseData = request.responseData; NSError* error = nil; [aFlight loadFlightCarrierWithData:carrierItemResponseData error:&error]; Carrier *firstCarrier = [aFlight.FlightCarrier objectAtIndex:0]; This feature is available only for entity objects retreived from the server that were not initiated using the basic init method (with no parameters).

8.4.3.9

Performing an Expand Query

Explains how to perform an expand query ($expand). To perform an $expand query, proceed as follows: 1. Use the expand: method in the ODataQuery object to set the expand parameters.ODataQuery *query = [[ODataQuery alloc] initWithURL:aCarrier.baseUrl]; [query expand:@"carrierFlights"]; Execute an HTTP request using the above query. id<SDMRequesting> request = [connectivityHelper executeBasicSyncRequestWithQuery:query]; Use the parseExpanded<Entity name>EntryWithData: method to parse the response data. Carrier *item = [Carrier parseExpandedCarrierEntryWithData:request.responseData

2. 3.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

177

andServiceDocument:service.sdmServiceDocument error:&error]; Flight *aflight = (Flight*)[item.carrierFlights objectAtIndex:0];

8.4.3.10 SAP Labels


Each entity or complex type class has a class method to get the SAP labels of the objects properties. You must first initiate the service object or call the loadLabels:(SDMODataServiceDocument *)aService class method. RMTSAMPLEFLIGHTService *service = [[RMTSAMPLEFLIGHTService alloc] init]; NSLog(@"Flight Label for carrid = %@",[Flight getLabelForProperty:@"carrid"]); NSLog(@"FlightDetails (complex type) Label for airportFrom = %@",[FlightDetails getLabelForProperty:@"airportFrom"]);

8.4.3.11

Performing Service Operations

This section describes how to perform a service operation (Function Import): 1. Get the service operation query from the service proxy object. There are two possible options for getting the query: Using typed objects holding the values for the service operation parameters. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd"]; [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]]; NSDate *dateFrom = [dateFormatter dateFromString:@"2011-01-05"]; NSDate *dateTo = [dateFormatter dateFromString:@"2011-07-28"]; ODataQuery *functionQuery = [service getGetAvailableFlightsQueryTypedWithFromdate:dateFrom andTodate:dateTo andCityfrom:@"NEW YORK" andCityto:@"SAN FRANCISCO"]; Pass only the values of the service operation parameters and the method takes care of converting them to the appropriate URI format.

Note
This option is available only for OData-compliant services. Using a generic dictionary holding the service operation parameter names and values as NSString objects, as they will appear in the service operation query URL. NSMutableDictionary *parameters = [NSMutableDictionary dictionary]; [parameters setValue:@"datetime'2011-01-05T00:00:00'" forKey:@"fromdate"]; [parameters setValue:@"datetime'2011-07-28T00:00:00'" forKey:@"todate"]; [parameters setValue:@"'NEW YORK'" forKey:@"cityfrom"]; [parameters setValue:@"'SAN FRANCISCO'" forKey:@"cityto"]; ODataQuery *functionQuery = [service getGetAvailableFlightsQueryWithParameters:parameters];

178

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

You must provide the values for the operation parameters in a dictionary exactly as they will appear in the query URL, in the correct format, according to the parameter types (as defined in the OData protocol). For example, the cityTo parameter of the GetAvailableFlights service operation is of type Edm.String, and therefore its value should be provided within single quotation marks, for example: 'SAN FRANCISCO'. 2. Execute an HTTP request using the query and get the response data. For example, use the executeBasicSyncRequestWithQuery:(ODataQuery *)aQuery method for executing a simple synchronous request. id<SDMRequesting> request = [connectivityHelper executeBasicSyncRequestWithQuery: functionQuery];

Note
The request must be executed using the HTTP method specified for this service operation in the service metadata (see also the code documentation of the appropriate service method used for getting the query in the previous step). If the service operation is executed using an HTTP method other than GET (for example, POST or PUT methods), an X-CSRF token must be attached to the request. For more information, see the Cross Site Request Forgery (CSRF) Protection section. 3. Use the service proxy objects get<Function Import Name>ResultWithData:(NSData *)aData error:(NSError **)error method to parse the response data into the appropriate object (according to the operation result type). NSData *flightsResponseData = request.responseData; NSError *error = nil; NSMutableArray *availableFlights = [service getGetAvailableFlightsResultWithData: flightsResponseData error:&error]; if (!error) { // work with the Flight semantic object as expected for (Flight *flight in availableFlights) { NSLog(@"carrid = %@",flight.carrid); NSLog(@"connid = %@",flight.connid); NSLog(@"airportFrom = %@",flight.flightDetails.airportFrom); } } Related Links

http://www.odata.org/documentation/overview#AbstractTypeSystem Cross Site Request Forgery (CSRF) Protection [page 185] Most OData compliant SAP services are protected against Cross-Site Request Forgery (CSRF) attacks. This protection mechanism appends challenge tokens to each request and associates them with each users session. Each token is unique per user session.

8.4.3.12 Performing Entity CUD Operations


All CUD calls must include an X-CSRF token in the request. To do this, you can use the SDMConnectivityHelper class and its getCSRFData and AddCSRFDataToRequest helper methods.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

179

8.4.3.12.1

Performing Create or Update Operations

To perform Create or Update: 1. Initiate a new entity item instance and set its properties (or update the values of an existing item). Before initiating a new entity item instance you must initiate the service object or call the loadEntitySchema:(SDMODataServiceDocument *)aService entity's class method.

Note
You can also set the entity items navigation properties to perform a deep insert operation. 2. 3. 4. 5. Get the item XML representation using the service objects getXMLForCreateRequest or getXMLForUpdateRequest methods. For Update, get the Etag parameter from the item. The Etag parameter represents the time interval of the item modification. Use the required SDMConnectivityHelper method: executeCreate[Sync/Async]RequestWithQuery, or executeUpdate[Sync/Async]RequestWithQuery. Use the entity class' parse<Entity Name>EntryWithData:(NSData *)aData error:(NSError **)error method to parse the response data into a new updated entity object. Booking *newBooking = [[Booking alloc] init]; newBooking.carrid = @"<carrier_ID>"; newBooking.PASSNAME = @"<passenger_name>"; Flight *associatedFlight = [[Flight alloc] init]; associatedFlight.connid = @"<flight_number>"; associatedFlight.carrid = @"<carrier_ID>"; newBooking.bookedFlight = [NSMutableArray arrayWithObject:associatedFlight]; NSError *error = nil; NSString *xml = [service getXMLForCreateRequest:newBooking error:&error]; CSRFData *csrf = [connectivityHelper getCSRFDataForServiceQuery:service.serviceDocumentQuery]; if (csrf) { id<SDMRequesting> request = [connectivityHelper executeCreateSyncRequestWithQuery: service.bookingCollectionQuery andBody:xml andCSRFData:csrf]; newBooking = [Booking parseBookingEntryWithData:request.responseData error:&error]; } To create a new item in a collection to which you can navigate using the navigation property of the parent item, use the parent navigation property query as the request query (instead of the collection query used in the Create request), as follows: NSError *error = nil; NSString *xml = [service getXMLForCreateRequest:newBooking error:&error]; CSRFData *csrf = [connectivityHelper getCSRFDataForServiceQuery:service.serviceDocumentQuery]; if (csrf) { id<SDMRequesting> request = [connectivityHelper executeCreateAsyncRequestWithQuery: aFlight.flightBookingsQuery andBody:xml andCSRFData:csrfData:csrf]; newBooking = [Booking parseBookingEntryWithData:request.responseData

180

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

error:&error]; }

Note
For an Update request, use the entry URL as the request query (instead of the collection query used in the Create request). NSError *error = nil; NSString *xml = [service getXMLForUpdateRequest:booking error:&error]; CSRFData *csrf = [connectivityHelper getCSRFDataForServiceQuery:service.serviceDocumentQuery]; if (csrf) { ODataQuery *query = [[ODataQuery alloc] initWithURL:booking.baseUrl]; id<SDMRequesting> request = [connectivityHelper executeUpdateSyncRequestWithQuery: query andBody:xml andCSRFData:csrf andEtag: booking.etag]; booking = [Booking parseBookingEntryWithData:request.responseData error:&error]; } Related Links

Cross Site Request Forgery (CSRF) Protection [page 185] Most OData compliant SAP services are protected against Cross-Site Request Forgery (CSRF) attacks. This protection mechanism appends challenge tokens to each request and associates them with each users session. Each token is unique per user session.

8.4.3.12.2 Performing a Delete Operation


To perform Delete: 1. 2. 3. 4. Get the baseUrl property value from the specific entity item instance you want to delete. Initiate a new ODataQuery object. Get the Etag parameter from the item. The Etag parameter represents the time interval of the item modification Use the SDMConnectivityHelpers executeDelete[Sync/Async]RequestWithQuery method. ODataQuery *query = [[ODataQuery alloc] initWithURL:flight.baseUrl]; [connectivityHelper executeDeleteSyncRequestWithQuery:query andCSRFData:csrf andEtag: flight.etag];

8.4.3.13 Media Link Queries


Entities that support media links have two additional properties in their entity class: mediaLinkRead Represents the information needed for reading the media link associated with the entity object. mediaLinkEdit Represents the information needed for editing (updating or deleting) the media link associated with the entity object.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

181

These properties of type MediaLink, include the query and the content type needed for reading or editing the media resource of the entity.

Note
This feature is available only for entity objects retreived from the server that were not initiated using the basic init method (with no parameters). The MediaLink class can be also used for providing the required information for creating a media link associated with an existing entry. The SDMConnectivityHelper class provides methods for performing all the media link CRUD operations (Read, Create, Update and Delete), synchronously or asynchronously, using the MediaLink objects.

Note
All CUD calls must include an X-CSRF token in the request. To do this, you can use the SDMConnectivityHelper class and its getCSRFData and AddCSRFDataToRequest helper methods.

8.4.3.13.1

Performing a Read Media Link Query

To perform a Read Media Link query: 1. 2. 3. Get the entity object associated with the media link. For more information, see Getting the Collection Using an Existing Entity Object. Get the Read media link query from the entity objects mediaLinkRead property. Execute an HTTP request using the query and get the response data. id<SDMRequesting> request = [connectivityHelper executeBasicSyncRequestWithQuery: aCarrier.mediaLinkRead.mediaLinkQuery]; 4. Use the response data to display the media resource, according to the media link content type. if ([aCarrier.mediaLinkRead.contentType isEqualToString:@"image/jpeg"]) { UIImage *image = [UIImage imageWithData: request.responseData]; mediaLinkImgView.image = image; //Display the image using a UIImageView control } Related Links

Cross Site Request Forgery (CSRF) Protection [page 185] Most OData compliant SAP services are protected against Cross-Site Request Forgery (CSRF) attacks. This protection mechanism appends challenge tokens to each request and associates them with each users session. Each token is unique per user session. Getting the Collection Entry Using an Existing Entity Object [page 175] Explains one of two possible scenarios for getting a specific collection entry. This scenario explains how to use an existing entity object to get the collection.

182

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

8.4.3.13.2 Performing an Update Media Link Query


To perform an Update Media Link query: 1. 2. Get the entity object associated with the media link. For more information, see Getting the Collection Using an Existing Entity Object. Get the edit media link from the entity objects mediaLinkEdit property, and set the content-type of the new media resource. aCarrier.mediaLinkEdit.contentType = @"image/jpeg"; 3. Set the data of the new media resource (for example, get its content from a URL). NSMutableData *body = [NSMutableData dataWithContentsOfURL:[NSURL URLWithString:@"<URL_For_Media_Content>"]]; 4. Execute an HTTP request using the SDMConnectivityHelpers executeUpdateMediaLink[Sync/ Async]Request method. CSRFData *csrf = [connectivityHelper getCSRFDataForServiceQuery: service.serviceDocumentQuery]; if (csrf) { id <SDMRequesting> request = [connectivityHelper executeUpdateMediaLinkSyncRequest: aCarrier.mediaLinkEdit andBody:body andCSRFData:csrf]; NSString *result = [request responseStatusMessage]; NSLog(@"Result: %@", result); } 5. Get the updated entity object associated with the updated media link. This new object should be used for reading the updated media link later.

Related Links

Getting the Collection Entry Using an Existing Entity Object [page 175] Explains one of two possible scenarios for getting a specific collection entry. This scenario explains how to use an existing entity object to get the collection.

8.4.3.13.3 Performing a Delete Media Link Query


To perform a Delete Media Link query: 1. 2. 3. Get the entity object associated with the media link. For more information, see Getting the Collection Using an Existing Entity Object. Get the edit media link from the entity objects mediaLinkEdit property. Execute an HTTP request using the SDMConnectivityHelpers executeDeleteMediaLink[Sync/ Async]Request method. CSRFData *csrf = [connectivityHelper getCSRFDataForServiceQuery: service.serviceDocumentQuery]; if (csrf) { id <SDMRequesting> request = [connectivityHelper executeDeleteMediaLinkSyncRequest: aCarrier.mediaLinkEdit andCSRFData:csrf]; NSString *result = [request responseStatusMessage];

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

183

NSLog(@"Result: %@", result); } 4. Get the updated entity object after the media link deletion.

Related Links

Getting the Collection Entry Using an Existing Entity Object [page 175] Explains one of two possible scenarios for getting a specific collection entry. This scenario explains how to use an existing entity object to get the collection.

8.4.3.13.4 Performing a Create Media Link Query


To perform a Create Media Link query: 1. Initiate a new media link instance including the query, content-type, and slug information the service needs for creating a media link for the desired entry.

Note
The query and slug information depend on the specific service implementation and are different from service to service. The following example uses the entity collection query. The slug request header is used for specifying the ID of the entry that will be associated with the media resource. MediaLink *mediaLink = [[MediaLink alloc] initWithQuery: service.CarrierCollectionQuery andContentType:@"image/jpeg" andSlug:aCarrier.carrid]; 2. Set the data of the new media resource (for example, get its content from a URL). NSMutableData *body = [NSMutableData dataWithContentsOfURL:[NSURL URLWithString:@"<URL_For_Media_Content>"]]; 3. Execute an HTTP request using the SDMConnectivityHelpers executeCreateMediaLink[Sync/ Async]Request method. CSRFData *csrf = [connectivityHelper getCSRFDataForServiceQuery: service.serviceDocumentQuery]; if (csrf) { id <SDMRequesting> request = [connectivityHelper executeCreateMediaLinkSyncRequest:mediaLink andBody:body andCSRFData:csrf]; NSString *result = [request responseStatusMessage]; NSLog(@"Result: %@", result); }

Note
In some services, the entry associated with the media resource must exist before creating the media link. For more information about creating an entity, see Performing Create or Update Operations. 4. Get the updated entity object associated with the created media link. This new object should be used for reading the created media link later.

184

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

Related Links

Getting the Collection Entry Using an Existing Entity Object [page 175] Explains one of two possible scenarios for getting a specific collection entry. This scenario explains how to use an existing entity object to get the collection. Performing Create or Update Operations [page 180] To perform Create or Update:

8.4.3.14 Cross Site Request Forgery (CSRF) Protection


Most OData compliant SAP services are protected against Cross-Site Request Forgery (CSRF) attacks. This protection mechanism appends challenge tokens to each request and associates them with each users session. Each token is unique per user session. All SAP services that are compatible with OData library version 1.0 are protected and require X-CSRF tokens. Some services that are compatible with OData library 0.2 also require these tokens. In such services, requests sent using HTTP methods other than GET (such as: POST, PUT and DELETE) require XCSRF tokens. This includes all Create, Update, and Delete (CUD) operations, as well as some service operations (Function-Imports). To handle this, you can use the SDMConnectivityHelper class and its getCSRFData and AddCSRFDataToRequest helper methods: The getCSRFDataForServiceQuery method uses the given service document query to retrieve the required X-CSRF data (token and cookie) from the SAP NetWeaver Gateway host. The returned CSRFData object should be saved in the application code, and passed to the appropriate execute method of the SDMConnectivityHelper.

Note
If the required X-CSRF data was not all retrieved properly, nil value is returned. Therefore it is recommended to verify the returned CSRFData object is not nil before using it. The AddCSRFDataToRequest method uses the given service document query to retrieve the required X-CSRF data (token and cookie) from the SAP NetWeaver Gateway host, and then adds them to the given request object (representing an HTTP POST, PUT, or DELETE request). This method may be used in the implementation of the onBeforeSend method, of the SDMConnectivityHelperDelegate protocol, for retrieving and attaching the X-CSRF data to requests before they are sent. The following is an example of handling CSRF protection while calling the applyDecision service operation of the WFSERVICE service (synchronously): - (ApplyDecisionOutput *)executeApplyDecisionWithWorkitem_id:(NSString *) workitem_id andDec_key:(NSString *) dec_key andComments:(NSString *)comments error:(NSError * __autoreleasing *)error { ODataQuery *query = [service getApplyDecisionQueryTypedWithWorkitem_id:workitem_id andDec_key: dec_key andComments: comments]; if (!csrfData) { csrfData = [connectivityHelper getCSRFDataForServiceQuery:service.serviceDocumentQuery]; }

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

185

id <SDMRequesting> response = [connectivityHelper executeBasicSyncRequestWithQuery:query andBody:nil andMethod:@"POST" andCSRFData:csrfData]; //Handle response int statusCode = [response responseStatusCode]; if (statusCode == 200) { return [service getApplyDecisionResultWithData:[response responseData] error:error]; } else { if (statusCode == 401) { [self authenticationNeededForRequest:(SDMHttpRequest *)[response mainRequest]]; } else { NSString *errorMessage; if (statusCode == 403){ errorMessage = [response responseString]; NSString *csrfToken = [[response responseHeaders] objectForKey:@"x-csrf-token"]; if (csrfToken.length > 0 && [csrfToken isEqualToString:@"Required"]) { csrfData = nil; errorMessage = [NSString stringWithFormat:@"%@. Try again to get a new token.", errorMessage]; } } else { errorMessage = response.error ? [response.error localizedDescription] : [response responseStatusMessage]; } if (error) { *error = [[NSError alloc] initWithDomain:ERROR_DOMAIN code: APPLY_DECISION_ERROR_CODE userInfo:[NSDictionary dictionaryWithObject:errorMessage forKey:NSLocalizedDescriptionKey]]; } NSLog(@"Request Error: %@", errorMessage); } } return nil; }

8.4.3.15 About Service Negotiation


SAP NetWeaver Gateway Service Catalog provides a function that returns the service that best matches the application requirements given a service name and version. The function import metadata is defined as follows: <FunctionImport Name="BestMatchingService" ReturnType="CatalogService.Service" EntitySet="ServiceCollection" m:HttpMethod="GET"> <Parameter Name="TechnicalServiceVersionMin" Type="Edm.Int16" Mode="In" Nullable="false"/> <Parameter Name="TechnicalServiceName" Type="Edm.String" Mode="In" Nullable="false"/> <Parameter Name="TechnicalServiceVersionMax" Type="Edm.Int16" Mode="In" Nullable="false"/> </FunctionImport>

186

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

The function import takes 3 parameters: The service name. The minimum version supported by the application. The maximum version supported by the application.

It then returns the service from the catalog that best matches the requirements. The generated proxy provides a simple API (called the Service Negotiation API) to call this function from the catalog service, and retrieves the best matching service URL and version. To use the Service Negotiation API: 1. Initialize a ServiceNegotiator class. The init method takes 2 parameters: The URL of the SAP NetWeaver Gateway service you wish to use. A relative URL to the SAP NetWeaver Gateway catalog service.

For example: ServiceNegotiator *serviceNegotiator = [[ServiceNegotiator alloc] initWithServiceUrl:@"http://host:port/sap/opu/odata/iwcnt/WFODCPROCESSING/" andCatalogRelativeUrl:@"/sap/opu/ODATA/iwfnd/CatalogService/"]; 2. Add the function import parameters as properties to the service negotiator: serviceNegotiator.technicalServiceName = @"/IWCNT/SG_ODC_RMT_WORKFLOW"; serviceNegotiator.technicalServiceVersionMin = 1; serviceNegotiator.technicalServiceVersionMax = 3; 3. Use the getBestMatchingServiceQuery method to get the function import query, and execute the request. id <SDMRequesting> serviceNegotiationRequest = [connectivityHelper executeBasicSyncRequestWithQuery:[serviceNegotiator getBestMatchingServiceQuery]];

Note
If no request with user authentication was performed before this call, execute the reuqest using the appropriate Authenticating protocol implementation to add the user credentials. NSData *serviceNegotiationResponseData = [authenticator authenticateWithQuery: [serviceNegotiator getBestMatchingServiceQuery] error:nil]; 4. Use the service negotiator to parse the data returned in the response: BOOL parseResult = [serviceNegotiator parseBestMatchingServiceResultWithData:serviceNegotiationRequest.responseData]; 5. If the parsing completed successfully, get the service URL and service version from the service negotiator: if (parseResult) { NSLog(@"%@", serviceNegotiator.bestMatchingServiceUrl); NSLog(@"%@", serviceNegotiator.bestMatchingServiceVersion); }

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

187

6.

Once you have retrieved the best matching service URL, you can use it to make all your service calls. [service setServiceDocumentUrl:serviceNegotiator.bestMatchingServiceUrl];

8.4.3.16 Making Asynchronous Calls


You can use an SAP OData Mobile Client SDK connectivity API to make asynchronous HTTP calls or use the SDMConnectivityHelper Async methods. The SDMConnectivityHelper has asynchronous methods to execute simple GET requests or more complex CUD calls. To make asynchronous calls: 1. Implement the desired SDMHttpRequestDelegate methods. The following example shows how to implement the requestFinished method for handling a specific flight response. - (void)requestFinished:(SDMHttpRequest *)request { NSLog(@"Completed async call..."); NSData *flightResultData = request.responseData; NSError *error = nil; Flight *myFlight = [m_service getFlightCollectionEntryWithData:flightResultData error:nil]; if (error) { NSLog(@"Error getting specific flight. Message: %@", error.localizedDescription); } else { NSLog(@"Specific flight carrId = %@", myFlight.carrid); } } 2. Implement the SDMConnectivityHelperDelegate protocol to make modifications in the request before it is sent, and set the delegate property of the connectivity helper object . - (void)onBeforeSend:(id<SDMRequesting>)request { //Using SDMConnectivityHelperDelegate to set some custom properties for the request before it's executed by the helper } connectivityHelper.delegate = self; //Set the SDMConnectivityHelperDelegate instance 3. Use the SDMConnectivityHelper Async methods to trigger the call, with the appropriate object implementing the SDMHttpRequestDelegate delegate. For example, use the executeBasicAsyncRequestWithQuery method for executing a simple asynchronous request. //Get specific flight asynchronously ODataQuery *flightQuery = [m_service getFlightCollectionEntryQueryWithCarrid:@"'AA'" andConnid:@"'0017'" andFldate:@"datetime'2011-04-20T00:00:00'"]; [connectivityHelper executeBasicAsyncRequestWithQuery:flightQuery andRequestDelegate:self];

188

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

8.4.3.17 About the Service Request Handler Class


The generated proxy also includes a Request Handler class for the selected service. The Request Handler is a singleton class that uses the proxy and the framework classes to send the service requests, parse the service response, and post the appropriate notification once the response was received. The Request Handler includes the methods that can be performed for each service collection. The generated methods enable the following actions: Read all collection items Read a single collection item Read related collection items using navigations Create, update, and delete a collection item Execute function imports Get, create, update, and delete media resources using media links

A method is generated only if its operation is supported by the service, according to the values of the SAP annotations defined for each collection in the service metadata (sap:addressable, sap:creatable, sap:updateable, sap:deletable). The request handler considers the service URL and the SAP Client set in the serviceDocumentURL and client properties for making the requests. The service calls are made asynchronously, and an appropriate notification is posted when the data is received. The notification includes the response parsed data (ready for display) or the response error (if such occurred). The request handler also includes methods for the user login and a method for service versioning negotiation. In addition, it handles a CSRF token, includes proper error handling, and supports simple configuration to work with SUP server. For correct usage of the class, when executing service requests, make sure to call either the executeLoginWithUsername:andPassword:andVaultPassword:error: or the executeLoginWithCertificateAndVaultPassword:error: method in your application (for example, from a login screen) before using other methods of the request handler. For more information, see the User Authentication and Login Process section. See also the Adding a Service Call section of the generated starter-kit application for code examples showing how to use the request handler functionality. Note that the service Request Handler is a helper class and therefore does not include all the service functionality that is supplied with the service proxy classes. You can change or add to the service Request Handler code to suit your needs. You can also use the service proxy semantic classes directly in your application, as demonstrated in the sections above. Related Links

User Authentication and Login Process [page 190] The service Request Handler includes methods for performing user login. Adding a Service Call [page 239] You can use the Request Handler generated with the application to add asynchronous service calls to the application views (the generated views or your own views).

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

189

8.4.3.17.1

User Authentication and Login Process

The service Request Handler includes methods for performing user login. The login includes the service versioning negotiation (if not disabled), the user authentication, and the service proxy object initiation (using runtime or local metadata). The method must be called in your application (for example, from a login screen) before using other methods of the request handler for executing service requests. The login method considers the authentication method returned from the authenticationType method of the proxy framework's ConnectivitySettings class for performing the user authentication. The user authentication itself is performed by the Authenticating protocol implementation. For more information, see the Executing Requests Using the Connectivity Helper Class and the Authenticating Protocol section. To perform Login with User Credentials: The service Request Handler includes the executeLoginWithUsername:andPassword:andVaultPassword:error: method for executing the login process using the supplied user credentials (in case a domain is also required, the user name parameter value should be in the format [user-domain]\[user-name]). When working in SUP mode, make sure to pass to vault password to this login method. To perform Login with an X.509 Client Certificate: The service Request Handler also includes the executeLoginWithCertificateAndVaultPassword:error: method for executing the login process when using the X.509 client certificate flow. When working in SUP mode, the application bundle must contain the client certificate file. Also, the kCertificateFlieName, kCertificateFileExtension, and kCertificatePassword must be configured correctly in the RequestHandlerConstants.m file (under Services/Framework). In addition, make sure to pass to vault password to the executeLoginWithCertificateAndVaultPassword:error: login method. When working in non-SUP mode, the method assumes the certificate has already been stored in the Keychain using the KeyChainHelper saveIdentityToKeychain:error: method. To set the method used for user authentication: Call the setAuthenticationType method of the ConnectivitySettings class, with the required AuthenticationType enum value. Currently the following authentication types are supported: UsernamePasswordAuthenticationType denotes Basic or Integrated/NTLM authentication type that requires user name, password, and domain (the latter is optional). The actual authentication method (Basic / NTLM) will be decided at runtime according to the authentication challenge returned from the server. PortalAuthenticationType denotes SAP Portal SSO authentication. CertificateAuthenticationType denotes X.509 client certificate authentication.

Note that if SAML2 protocol is used for authentication, the authentication type value should indicate the authentication type used by the Identity Provider server. In addition, make sure to configure other authentication related settings (for example, the Portal URL) by using the ConnectivitySettigns class methods.

190

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

An example of using the login method from a login screen is described in the Adding a Login Screen for User Authentication section of the generated Basic starter-kit application. Related Links

Adding a Login Screen for User Authentication

8.4.3.17.2 About Single Sign-On (SSO) for User Authentication


The service Request Handler's executeLoginWithUsername:andPassword:andVaultPassword:error: method, saves on the device the user credentials passed as parameters. If no user credentials are provided as the method parameters, it uses the previously saved credentials. If the login fails due to an authentication error, the saved user credentials are deleted. In case of client certificate authentication, the method assumes the certificate has already been stored in the Keychain using the KeychainHelper saveIdentityToKeychain:error: method. When calling the executeLoginWithCertificateAndVaultPassword:error: method for login with client certificate in SUP mode, it extracts the certificate credentials from the certificate file and passes them on to the executeLoginWithUsername:andPassword:andVaultPassword:error: method that then saves them as decribed above. This behavior can be used for implementing Single Sign On (SSO) in your application: The first time the application is run (and therefore there are no credentials saved on the device), or if a previous login call failed, prompt the user to enter the credentials and use them as parameters to the login method. On next application runs (when user credentials are already saved), do not prompt the user for credentials. Instead, pass empty credentials to the login method so that the saved credentials will be used.

Note
You can check if there are user credentials already saved on the device using the isCredentialsSaved method of the KeychainHelper class. To share the saved user credentials among multiple applications: It is possible to allow the saved user credentials to be shared among multiple applications that were signed using the same Provisioning Profile and belong to the same Keychain Access Group. To do so, configure the keychain access group value used by the generated code to load and save the user credentials on the device by calling the setAccessGroup method of the KeychainHelper class.

Note
The access group value prefix must be the Application Identifier prefix contained in the Provisioning Profile that is used for signing all the applications that share the user credentials. In addition, make sure to add a keychain-access-groups entitlement to the application and, in the entitlement property list file, specify an array of keychain access groups to which the application belongs. For more information, see the discussion for the SecItemAdd method at Apple's Keychain Services Reference.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

191

Related Links

https://developer.apple.com/library/mac/#documentation/security/Reference/keychainservices/Reference/ reference.html

8.4.3.17.3 Using the Device Language Settings for Runtime Data


To display the SAP data and the field labels in the device language, the generated service Request Handler sends the appropriate language code according to the device language settings with any service request. This language code is sent as the value of the sap-langauge HTTP header. You can also configure the Request Handler to get all the service reponse data (including runtime data and metadata) in the language of the application user (as configured in SAP systems), instead of in the device language. To configure the application to use the user language settings for runtime data: 1. 2. Open the [Service Name]RequestHandler.m file. Remove or comment the following line from the OnBeforeSend method implementation: //Define the request language as the device language settings [request addRequestHeader:@"sap-language" value:deviceLanguage]; In addition, when calling the Request Handlers login method, it retrieves the service document and metadata in runtime. It is also possible to get the service document and metadata from the local files that were used for generating the proxy or the starter kit application by the tool (see the Configuring the Request Handler to Work with Local Service Document and Metadata section). Note that in this case, the field labels are displayed in the language of the local files and they cannot be translated. Related Links

Configuring the Request Handler to Work with Local Service Document and Metadata [page 192] When a user logs in and the login method of the service Request Handler is called, the Request Handler retrieves the service document and metadata in runtime, and uses them to initiate the proxy object.

8.4.3.17.4 Configuring the Request Handler to Work with Local Service Document and Metadata
When a user logs in and the login method of the service Request Handler is called, the Request Handler retrieves the service document and metadata in runtime, and uses them to initiate the proxy object. This allows parsing the service reponse data against the most updated service document and metadata (as opposed to the local service document and metadata files that were used for generating the application by the tool). Another benefit of this feature is displaying the field labels in the device language or in the application user language (for more information, see Using the Device Language Settings for Runtime Data section), and not as constant strings, as defined in the local files.

192

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

You can also configure the service Request Handler to work with the local service document and metadata files that were used by the tool to generate the service proxy or the starter-kit application. The files are located at the / Services/Resources folder.

Note
When working with the local service document and metadata, the service versioning negotiation feature is disabled. To configure the application to work with the local files: Set the value of the Request Handler instances useLocalMetadata property to YES. Related Links

Using the Device Language Settings for Runtime Data [page 192] To display the SAP data and the field labels in the device language, the generated service Request Handler sends the appropriate language code according to the device language settings with any service request. This language code is sent as the value of the sap-langauge HTTP header.

8.4.3.17.5 Service Versioning Negotiation


The service negotiation method of the service Request Handler is called from the login method as part of the login process. The Request Handler calls the proxy framework's ServiceNegotiator class to perform the negotiation process with the following information: The service URL defined in serviceDocumentURL property of the Request Handler. The catalog service URL (defined as the Request Handler constants), relative to the service host and port that are defined in the service URL. The service technical name and the minimal and maximal service versions supported (defined as the Request Handler constants). // Service Negotiation constants (used for the service negotiation process): static NSString * const CatalogServiceUrl = @"/sap/opu/odata/iwfnd/ CatalogService/"; static NSString * const TechnicalServiceName = @"/IWFND/SG_SAMPLE_RMT_SFLIGHT"; static NSInteger const TechnicalServiceVersionMin = 1; static NSInteger const TechnicalServiceVersionMax = 1; The Service Negotiator performs the negotiation process and returns the service URL according to the appropriate version. For more information, see the Service Negotiation section. The Request Handler uses this URL to set the service URL of the proxy object. Note that negotiation failure does not fail the login process.

Note
When using service negotiation and working with SUP, make sure the service catalog URL is whitelisted in the SUP server, and that the CatalogServiceUrl constant value contains this URL exactly as it is configured on the SUP server (case sensitive). To change the values of the minimal and maximal service versions supported by the application:

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

193

Set the desired values for the TechnicalServiceVersionMin and TechnicalServiceVersionMax constants defined in the Request Handler class implementation. To disable the service versioning negotiation feature: Set the value of the useServiceNegotiation property of the Request Handler instance to NO.

Note
When working with the local service document and metadata, the service versioning negotiation feature is disabled, even if the property value is set to YES.

8.4.3.18 Working with the SUP Server Using the Generated Proxy
This section describes the different ways to work with the SUP server using the generated proxy.

8.4.3.18.1 Prerequistes for Working with the SUP Server Using the Generated Proxy
Before you upgrade your application to work with the SUP server, you must do the following: Prepare the Xcode project

Follow the steps described in the link below to add the SUP libraries and their dependencies to your existing project: http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc01708.0213/doc/html/

nkr1337745641724.html
Before you start working with the generated proxy, your SUP Server administrator needs to provide the following details related to your application which are configured through the Sybase Control Center: The host and Port of the related SUP Server. The Application ID. The Farm ID (default = 0). The name of the Security Configuration.

Before you start working with the generated proxy, your SUP Server administrator needs to make sure the service catalog URL is whitelisted in the SUP Server (if service versioning negotiation is required), and to make the appropriate configurations according the Security method used for connecting the service.

8.4.3.18.2 Enabling the Proxy to Support SUP Connectivity


This section explains how to enable the generated proxy to support SUP connectivity. Open the Connectivity/SUPHelper.m file and uncomment the following sections:

194

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

The Import declaration of the required SUP header files. /** * TODO: Uncomment the following lines for SUP Server connectivity support. * Make sure to uncomment the additional required methods implementation under "Methods for * SUP Server connectivity" pragma mark. * In addition, make sure to reference in the project the ODP client libraries and headers required for * SUP connectivity. */ //#import "LiteSUPUserManager.h" //#import "LiteSUPAppSettings.h" //#import "LiteSUPCertificateStore.h"

The commented code lines in all method implementations included in the Methods for SUP Server connectivity pragma. #pragma mark - Methods for SUP Server connectivity

/** * TODO: Uncomment the following methods implementation for SUP Server connectivity support */

8.4.3.18.3 Consuming the Service with SUP Using a Proxy


You can work with the generated methods for executing service requests at runtime using the SUP server in 2 different ways: Using the generated service Request Handler. In this option, you use a more high-level API and the Request Handler performs most of the required operations. If you choose this option, you must use the Request Handler class for performing the service requests in your application. You can change or add to the Request Handler code to suit your needs. Using the classes of the Connectivity and Authenticators groups directly. In this option, you use the proxy Framework classes (as the SDMConnectivityHelper class and the Authenticating protocol) directly for executing service requests. Use this option if you want to use only the generated semantic proxy classes and do not intend to use the generated service Request Handler.

Using the Request Handler for SUP Connectivity


To use the Request Handler for SUP connectivity at runtime, use the generated methods as follows: 1. Activate the proxy to work with SUP and configure the SUP application settings (as configured in the SUP server) using the ConnectivitySettings class. [ConnectivitySettings setSUPMode:YES]; [ConnectivitySettings [ConnectivitySettings [ConnectivitySettings [ConnectivitySettings [ConnectivitySettings security configutaion setSUPAppID:@"[Your Application ID]"]; setSUPHost:@"[Your SUP Server host address]"]; setSUPPort:[Your SUP Server port number]]; setSUPFarmID:@"[Your SUP Farm ID]"]; setSUPSecurityConfiguration:@"[Your application ID name"];

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

195

2.

Create a new instance of the Authenticating protocol with the Vault Password (defined by you or received from the user) and the credentials of the user that is authorized to work with SUP Server and Gateway. id <Authenticating> authenticator = [[UsernamePasswordAuthenticator alloc] initWithUsername: @"[SUP Server end-user username]" andPassword:@"[SUP Server end-user password]" andSUPVaultPassword:@"[Your Vault Password]"]; For X.509 client certificate authentication, use the SUPHelper class getCerdentialsFromCertificateFile:withCertificatePassword:error: method to extract the credentials needed for the authenticator: NSString *certificateFilePath = [[NSBundle mainBundle] pathForResource:kCertificateFileName ofType:kCertificateFileExtention]; CredentialsData *credentialsData = [SUPHelper getCredentialsFromCertificateFile:certificateFilePath withCertificatePassword:kCertificatePassword error:error]; [self executeLoginWithUsername:credentialsData.username andPassword:credentialsData.password andVaultPassword:aVaultPassword error:error];

Note
The Authenticating protocol implementations take care of registering the user to the SUP server, or using the credentials of an already registered user on the device. Therefore you can check if user credentials were passed in a previous application run and, if so, pass only the Vault Password (without asking the user to enter his Gateway credentials).

if ([SUPHelper isSUPUserRegisteredForAppID: [ConnectivitySettings SUPAppID]]) { id <Authenticating> authenticator = [[UsernamePasswordAuthenticator alloc] initWithUsername:nil andPassword:nil andSUPVaultPassword:@"[Your Vault Password]"]; } 3. Create a new instance of the semantic proxy service class (in this example we use the RMTSAMPLEFLIGHT Gateway demo service): RMTSAMPLEFLIGHTService *service = [[RMTSAMPLEFLIGHTService alloc] init]; 4. Set the End Point as configured in the SUP Control Center. [service setServiceDocumentUrl:[ SUPHelper getSUPApplicationEndPoint]]; 5. Execute the first service request using the Authenticating protocol to authenticate the user at the Gateway server. The request is sent using the SUP server. NSData* serviceDocData = [authenticator authenticateWithODataQuery:service.ServiceDocumentQuery error:nil]; if (serviceDocData) { NSLog(@"User authenticated successfully"); }

Note
You can use any GET service query to perform the authenticated request. Make sure to verify that the authentication succeeded (the nil value was not returned), and use the response data as required.

196

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

6.

Create a new instance of SDMConnectivityHelper. SDMConnectivityHelper *supConn = [[SDMConnectivityHelper alloc] init];

7.

Continue working with the proxy directly and execute the requests using the SDMConnectivityHelper instance. The user is authenticated using the session cookie received from Gateway at the first request, and the requests are sent using the SUP server. NSMutableArray *flights = [service getFlightCollectionWithData:[[supConn executeBasicSyncRequestWithQuery:service.FlightCollectionQuery] responseData] error:nil]; Flight *firstFlight = [flights objectAtIndex:0]; NSLog(@"carrier id = %@", firstFlight.carrid);

8.4.3.19 Supported OData Capabilities


The following OData capabilities are supported by the generated proxy: Read collections and specific entries Service Operations (Function Import) Navigation Properties Query String Options: Filter, Order By, Expand, Select, Top, and Skip Media Links: Read, Create, Update, and Delete Deep Insert Parse entries receieved using the Expand query Create, Update, and Delete of entries Complex Types OData URI Primitive Type Representation Concurrency control (HTTP ETags)

8.4.3.19.1

Generated iOS Application Structure

The iOS starter application files based on the selected template are created and located in a specified folder. The generated project is an Xcode iOS project. All the generated application projects have a similar structure, and are composed of the following sections: Authentication Contains the classes used to authenticate the user (not provided with the generated Basic application). Services Contains the service proxy classes and the semantic proxy framework files. In addition, it contains the service Request Handler class which is responsible for executing all the service calls needed for the applications that use the proxy classes. Root App folder - Contains the code of the views generated by the tool. Each view has its own ViewController class file (.h and .m files) and a UI description file (.xib file). Settings.bundle - Contains the files necessary for configuring the application settings, including the service URL and SAP client.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

197

You can run and test the generated application immediately. For more information, see Running the Generated Application. All the generated application projects have common code components that are responsible for performing the service operations and provide the functionality needed for applications consuming SAP data.

Service Proxy
The generated service proxy includes the semantic proxy classes which use the SAP OData Mobile Client SDK and the semantic proxy framework classes. It also includes the generated service Request Handler that uses the semantic proxy and the framework classes to send the service requests, parse the service response, and notify the appropriate view controller once the response was received. These files are located under the Services group of the generated project.

Login Screen
The login screen handles the user authentication with the SAP NetWeaver Gateway service (according to the authentication method selected in the application settings). The user must enter user name and password in the designated fields. If domain is also required it should be included in the user name text field in the following format: [user-domain]\[user-name].

Settings Bundle
The Settings Bundle is responsible for defining the application settings including:

198

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

The connection mode (through SUP server or directly to SAP NetWeaver Gateway). The authentication method, the selected service details, and the SAP Portal details (if required) used in Gateway Connection Mode. The SUP server details used in SUP Connection Mode.

The default values of some of these settings (as the service details and application ID for SUP connection) are those of the service selected for generating the application and of the selected projects name. The developer may change the settings default values in the property list files of the Settings.bundle folder. The application user may change these values at any time from the device Settings. The values of the application settings defined by the user at runtime are used within the application using the SettingsUtilities class, which enables reading the settings values at runtime. Settings for Gateway Connection Mode The settings for the Gateway Connection Mode are: The Authentication Method used for connecting to the Gateway server. The supported methods are: Gateway Defined Use this option for the user authentication method that is provided in the authentication challenge sent by the SAP NetWeaver Gateway server in runtime. If this option is selected, users are required to enter their credentials (user name, password, and optionally a domain). The supported authentication challenge types are Basic and Integrated/NTLM. Client Certificate Use this option for user authentication by X.509 Client Certificate. If this option is selected, the users certificate must be saved on the device. SAP Portal Use this option for user authentication by SAP Portal SSO. If this option is selected, the users are required to enter their SAP Portal credentials (user name, password and optionally a domain).

For more information, see the Configuring the User Authentication in a Starter-Kit Application section. The selected Service Details including: The selected services URL. The SAP client (may be empty for using the default client).

The URL of the SAP Portal service used for user authentication, if SAP Portal is selected as the Authentication Method.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

199

Settings for SUP Connection Mode The settings required for SUP Connection Mode including: The SUP server host and port. The Farm ID as defined on the SUP server. The name of the Security Configuration of the SUP server to be used for authenticating the application users. An indication whether the application should send an X.509 Client Certificate to the SUP server for user authentication. The Application ID as defined on the SUP server.

The relevant values for these settigns for your application should be provided by your SUP Server administrator. They must be identical to those configured through the Sybase Control Center.

200

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

Application Delegate Class


In the generated applications, the Application Delegate class is responsible for setting required parameters for the application. These parameters include the SUP Server connectivity settings (if relevant), the authentication type to be used, and other authentication-related parameters defined in the application settings bundle. It is also responsible for settings the service Request Handler properties with the URL and SAP Client values defined in the application settings bundle, and for defining whether features such as service versioning negotiation should be enabled. In generated applications that include a login screen, the application delegate class is also responsible for displaying the login screen as the first application view and whenever an authentication challenge is received during the application lifecycle.

Application Utilities
The application Utilities class provides useful methods needed for the generated applications, such as displaying error alerts which provide the option of viewing and sending the application logs. Related Links

Configuring the User Authentication in an iOS Starter-Kit Application [page 236] All the generated applications use Basic authentication by default.

8.4.4

Generated Application Flow

The generated applications by default support direct SAP NetWeaver Gateway access using basic authentication (with the option of HTTPS). In addition, the applications support Single Sign-On (SSO) by saving the user credentials entered in the first application run, and using them whenever they are required. The applications also support other authentication methods. For more information, see the Configuring the User Authentication in an iOS Starter-Kit Application section. The following objects are used to handle user authentication (in any of the supported methods) and to perform service operations using the provided credentials: App Delegate This is the main entry point for the application. It launches the Login screen as the root view controller. It then validates if user credentials are already saved on the device. If so, it displays the login screen in an operation mode that performs the login process using the saved credentials instead of requesting them from the user. After the authentication process is complete, it replaces the Login screen with the view controller of the first screen in the application. In addition, the App Delegate defines which authentication method must be used and its related parmeters. (By default, Basic authentication is used). It also defines whether service versioning negotiation should be used (as part of the login process). Login Screen Responsible for validating the user credentials by calling the login method of the Request Handler. It allows users to enter their credentials according to the authentication method required for SAP NetWeaver Gateway access.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

201

Request Handler A singleton object responsible for making the HTTP calls to the SAP NetWeaver Gateway and for notifying the appropriate view once the opertaions are completed. The Request Handler performs the login process with the user credentials provided in the login screen. This process includes service versioning negotiation (if enabled), user authentication, and service proxy object initiation (using runtime or local metadata). The Request Handler is also used by the application views to perform the service requests needed for getting the relevant data for the view. Authenticating A protocol which makes HTTP requests with the user credentials for user authentication, according to the required authentication method. The requests are performed using the SAP OData Mobile SDK. The Authenticating protocol implementations save, load or delete the user credentials from the device as necessary. Connectivity Helper A helper class which makes HTTP requests (without user credentials) using the SAP OData Mobile SDK. This class is used by the Request Handler for all the service requests of the application, except for the first one (that requires the user credentials).

These objects may be also used for handling user authentication for accessing the SAP NetWeaver Gateway through the SUP server. For more information, see Configuring a Starter Kit Application to Work with SUP. Related Links

Configuring the User Authentication in an iOS Starter-Kit Application [page 236] All the generated applications use Basic authentication by default.

8.4.5

About the Basic Generated Application

The generated Basic iOS application is a starter point for developing an iOS application consuming an SAP NetWeaver Gateway service. It is generated as a Universal application which can run on both iPhone and iPad devices.

202

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

The generated applications project is composed of the common components for all generated applications (Service Proxy, Request Handler and Settings Bundle), and also contains a Sample UI View. The generated sample UI view displays the items of the services first addressable collection. The purpose of this view is to demonstrate how to work with the Request Handler methods and notifications.

8.4.5.1

Extending the Generated Basic Application

You can extend the generated application in any way you want. This section describes some of the most common extensions. The examples provided in this section are based on a Basic application generated from the RMTSAMPLEFLIGHT service. For additional extensions which are relevant for all the generated applications, see the Extending the Generated iOS Starter Application section.

Changing the Collection Displayed in the Sample View


1.

Note
The sample code used in this procedure, shows how to display the FlightCollection items in the sample view instead of the first addressable collection.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

203

In the viewDidLoad method of the sample view controller, replace the current Request Handler's load<collection_name>Collection method called with the method that retreives the items of the desired collection. [[RTMSAMPLEFLIGHTRequestHandler uniqueInstance] loadFlightCollection];

Note
Make sure you have set the appropriate user credentials in the login method that is called before the method. above. 2. In the initWithNibName method of the sample view controller, sign up for the kLoad<collection_name>CollectionCompletedNotification notification that is posted when the service response with the desired collection items is received or an error is returned. For information on the appropriate notifications, open the Request Handlers header file and see the documentation of the method called in step 1. When signing up for the notification, define the view controller method that will be called when the notification is posted. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadFlightCollectionCompleted:) name:kLoadFlightCollectionCompletedNotification object:nil]; 3. Implement the view controller method defined in step 2 to display the desired collection items, or handle an error if such occured.. - (void) loadFlightCollectionCompleted:(NSNotification *)notification { // Handle FlightCollection response data and display the collection items in the view NSDictionary *userInfoDict = [notification userInfo]; NSError *error = [userInfoDict objectForKey:kServerResponseError] ? [userInfoDict objectForKey:kServerResponseError] : [userInfoDict objectForKey:kParsingError]; if (error) { // Handle server response error or response parsing error [Utilities showErrorDialogWithError:error]; } else { // Display the collection items NSMutableArray *responseItems = [userInfoDict objectForKey:kResponseItems]; items = responseItems; NSString *flights = @""; for (Flight *flight in items) { // Display the Flight item key properties NSString *currentFlight = @""; currentFlight = [currentFlight stringByAppendingFormat:@"carrid: %@\n", flight.carrid]; currentFlight = [currentFlight stringByAppendingFormat:@"connid: %@\n", flight.connid]; currentFlight = [currentFlight stringByAppendingFormat:@"fldate: %@\n", flight.fldate]; flights = [flights stringByAppendingFormat:@"%@\n", currentFlight]; } self.content.text = flights; } }

204

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

To get the service response data that was parsed into Flight objects, the method extracts the userInfo dictionary from the notification object and then uses the kResponseItems key to extract the Flight objects from the dictionary.

Adding a Login Screen for User Authentication


1. Create a login view to get the user name and password and then display it as the first application screen. If you are working with client certificate authentication, there is no need to get crendentials from the user. Instead, you must call the login method as described in step 2. For Single Sign-On (SSO), ask the user to enter the credentials only if there are no credentials already saved on the device. If such credentials are already saved, you can use empty values for calling the login method. No user input should be received. if ([KeychainHelper isCredentialsSaved]) { // Don't display credentials input text box in login screen. }

Note
If you are working with the SUP server, use the isUserRegistered method of the LiteSUPUserManager class to check if there is a registered user. If a user is already registered, there is no need to ask for new credentials, but you still need to call the login method. (The user name and password parameters may be nil, but the Vault passoword must be passed.) if ([SUPHelper isSUPUserRegisteredForAppID:[ConnectivitySettings SUPAppID] ]) { // Don't display credentials input text box in login screen. } In addition, follow the instructions described in the Configuring a Starter Kit Application to Work with SUP section for performing the login operation using the SUP server. 2. In the login view controller, use either the Request Handler's executeLoginWithUsername:andPassword:andVaultPassword:error: method or the executeLoginWithCertificateAndVaultPassword:error: method to perform the login operation. Use the method's returned value to check if the login succeeded and handle the view appropriately. Use the error object passed to the login method to identify the type of error that occured (using the error codes defined in the Error Handling header file that is supplied with the proxy framework) and to extract the error message. - (void) handleSignIn { NSError *error = nil; /** TODO: Make sure to set this value as desired, or get it from the user - if SUP sever is used. */ NSString *vaultPassowrd = @"MyVaultPassword"; // This value is ignored if not in SUP mode. BOOL result = NO; if ([ConnectivitySettings authenticationType] == CertificateAuthenticationType) { result = [[RTMSAMPLEFLIGHTRequestHandler uniqueInstance] executeLoginWithCertificateAndVaultPassword:vaultPassowrd error:&error]; } else {

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

205

result = [[RTMSAMPLEFLIGHTRequestHandler uniqueInstance] executeLoginWithUsername:[userNameTextField text] andPassword:[passwordTextField text] andVaultPassword:vaultPassowrd error:&error]; } if (result) { // Authentication succeeded: // Notify delegate, to navigate to the next view. No need to set username or password for // later requests, since the session cookie will be attached // (until it is expired, and this view will be displayed again). [self performSelectorOnMainThread:@selector(notifyDelegate) withObject:nil waitUntilDone:NO]; } else { if ([error code] == SERVICE_URL_EMPTY_ERROR_CODE) { [self performSelectorOnMainThread:@selector(showInfoBar:) withObject:[error localizedDescription] waitUntilDone:NO]; } else if ([error code] == SERVICE_METADATA_PARSE_ERROR_CODE) { [self performSelectorOnMainThread:@selector(showInfoBar:) withObject:[error localizedDescription] waitUntilDone:NO]; } else if ([error code] == CERTIFICATE_HANDLING_ ERROR_CODE) { [self performSelectorOnMainThread:@selector(showInfoBar:) withObject: NSLocalizedString(@"Failed to read certificate.", @" Failed to read certificate.") waitUntilDone:NO]; } else if ([error code] == LOGIN_ERROR_CODE) { //Authentication failed [self performSelectorOnMainThread:@selector(showInfoBar:) withObject:NSLocalizedString(@"Login failed. Try Again.", @"Login failed. Try Again.") waitUntilDone:NO]; } } } If your login view supports an operation mode where the login method is called without asking users to enter their credentials first (for example, SSO or when working with SUP server), you must allow the users to reenter their credentials if the login failed with the error code value LOGIN_ERROR_CODE. The deletion of the previously saved credentials is handled by the login method. There is no need to delete them manually.

Note
The service versioning negotiation feature is enabled by default as part of the login process (with that, a failure in the negotiation process does not fail the login process). For more information including instructions for disabling this feature, see the Using iOS Service Versioning Negotiation section. 3. Sign up for the Request Handlers kAuthenticationNeededNotification notification which is posted any time the user authentication is required (for example, when performing a service call using the Request Handler after the session expires). When signing up for the notification (for example, from the

206

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

application:didFinishLaunchingWithOptions: method of the app delegate), define the method that will handle it and implement this method to display the login view. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(authenticationNeeded) name:kAuthenticationNeededNotification object:nil]; - (void)authenticationNeeded { self.window.rootViewController = loginViewController; } 4. Remove any call to the Request Handler's login method from the application views (for example, the Sample View Controller).

Related Links

Configuring a Starter Kit Application to Work with SUP [page 233] Before configuring a starter kit application to work with SUP, make sure you have completed the prerequisites described in the Prerequistes for Working with the SUP Server Using the Generated Proxy section Using iOS Service Versioning Negotiation

8.4.6

About the Generated List/Details iOS Application

How to work with the generated list/details aiOS application. The generated List/Details iOS application is used for displaying SAP data in list and details screens, as well as for creating, deleting and editing the SAP data, using the services exposed via SAP NetWeaver Gateway. The relationship between the views is based on the association between the entity sets. The application is generated as a Universal application which can run on both iPhone and iPad devices. The application project is composed of views generated by the tool using the wizard, and the proxy classes of the selected service, which use the SAP OData Mobile Client SDK and the semantic proxy framework classes. The project also includes the Form UI Utilities folder that contains the UI components and utilities used by the generated form views of creating or editing SAP data. In addition, the List/Details application project includes the components that are common to all the generated applications. For more information, see the Generated Application Structure section.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

207

Application List and Details Screens


The application List views allow the user to view SAP data as a list of items. On an iPad device, these views are displayed in the Master part of the iPad Split View (on the left side of the screen). As selected in the wizard, the List views may also include a plus button that allows the user to create new SAP Data that will be displayed as new

208

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

list items. In addition, the List views support deleting SAP Data displayed on the list, by swiping the appropriate list item and pressing Delete. The application Details views allow the user to view SAP data as key-value properties of a single item. On an iPad device, these views are displayed in the Detail part of the iPad Split View (on the right side of the screen). If some of the SAP data of the item is aggregated into an OData Complex Type structure, it will be displayed in a separate view representing the OData Complex Type, and the Details view displaying the item will contain a navigation to this Complex Type view. As selected in the wizard, the Details views may also include an Edit button that allows the user to edit the SAP Data of the item displayed in the view, or to delete the whole item. When selecting an item from a List view or navigating from an items Details view, the application performs an asynchronous request to the service to get the data associated with this item that will be displayed in the next view. The data is obtained using a navigation property or a request for the specific entry details. The retrieved data is displayed in the next view according to the type of data: collections of OData entries are displayed in a List view, while a single OData entry is displayed in a Details view. Since the application is a universal application, it has two UI description files (.xib files) for each view one for displaying on an iPad device, and one for displaying on an iPhone device. To load the relevant UI description file according to the device in use, the view controller classes use the isRunningOnIPad method of the app delegate class, that indicates on which device the application is currently running.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

209

Application Form Screens


The application may also include form views for creating new SAP data or for editing the displayed SAP data. The Create Form views are displayed when pressing the + button from the related list view, and are used for creating new items and adding them to the list. The Edit Form views are displayed when choosing Edit from the related details view, and are used for editing the displayed item details or deleting the whole item. The form views are organized as a table where each of the cells represent a single property of the related entity, and the user can enter the desired property value. The views contain a Submit button for sending the service request to create or update the entity with the values entered in the form. The Edit Form views also contain a Delete button for sending the service request to delete the displayed entity. On successful operations, the form views are dismissed. The property values are displayed and edited in the form views according to their OData type, in the exact same way as in the form screen of the generated Form Application. For more information, see the About the Form Generated Application and About the Form Generated Application UI Utilities sections of the generated Form Application.

210

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

211

Related Links

Generated iOS Application Structure [page 197] The iOS starter application files based on the selected template are created and located in a specified folder. The generated project is an Xcode iOS project. About the Form Generated Application UI Utilities [page 225] The Form UI Utilities folder contains the UI components and utilities for displaying and editing the form property values of different OData types. These components and utilities are used in the generated form views, and can be also used for extending the generated application. About the Form Generated Application [page 226] The generated Form iOS application is a starting point for developing an iOS application that allows the creation of SAP Data using the services exposed via SAP NetWeaver Gateway.

8.4.6.1

iOS List/Details Application Limitations

iOS List/Details application limitations. The iOS List/Details application has the following limitations: The application is compatible only with iOS version 6.0 and higher. The Form UI Utilties and the generated form views for creating and editing items do not support OData properties of type Edm.Binary (that are represented as NSData objects).

8.4.7

About the Workflow Generated iOS Application

The generated Workflow iOS application enables the user to view and manage its Workflow tasks using the Workflow services exposed via SAP NetWeaver Gateway.

Note
The supported Workflow services are: Generic OData Channel Workflow service Workflow Task Service: Central Hub Deployment with IW_BEP Backend Installation Workflow Task Service: Central Hub Deployment with IW_BEP Hub Installation New customer services which are based on them.

These services are available in SAP NetWeaver Gateway 2.0 SP02 or higher only. The application is generated as a Universal application which can run on both iPhone and iPad devices. The application project is composed of the Workflow task list and Workflow task details components, as well as the proxy classes of the selected Workflow service (for example, the WFODCPROCESSING or WFSERVICE services), which use the SAP OData Mobile Client SDK and the semantic proxy framework classes. In addition, the Workflow application project includes the components that are common to all the generated applications. For more information, see the Generated iOS Application Structure section.

212

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

Related Links

Generated iOS Application Structure [page 197] The iOS starter application files based on the selected template are created and located in a specified folder. The generated project is an Xcode iOS project.

8.4.7.1

About the Workflow Task List View

The main screen of the application enables the user to view the Workflow task list and access the details of each task. When the application is run on an iPad, the Workflow task list is displayed on the Master pane of the iPad's SplitView.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

213

Note
The task list isAbout the fetched from SAP NetWeaver Gateway the first time the application is loaded. Currently the only way to refresh it is to restart the application. For each task, the following details are displayed: Subject Creator Creation date Priority

214

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

Task priorities are received from the service as numbers and are mapped to strings using the following mapping:

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

215

1. Highest 2. Very High 3. Higher 4. High 5. Medium

6. Low 7. Lower 8. Very Low 9. Lowest

The task priorities are also marked with colors: high priorities (1-4) in red, medium priority (5) in black, and low priorities (6-9) in grey.

Task Filter
The tasks can be filtered by task name which usually represents the type of the task involved (Leave Request, Purchase Order, etc.). To filter the tasks displayed, choose Filter and select the desired task name, or select All to view all tasks.

The filtered task list displays according to your selection. Choose Cancel to exit the filter view without performing any change in the displayed list.

Task Search
In the task list view, you can search for tasks according to a search string. To perform a search: 1. 2. Click the search field at the top of the view. Type the desired string. The search is performed on all presented properties and the results are displayed while the search string is typed.

Note

216

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

Search is performed only on tasks displayed in the list (which may be filtered).

The application code responsible for the task list is found in the following components of the generated project: TasksListViewController , WorkflowTaskListCell, FilterTypeViewController and FilterTypeDelegate.

8.4.7.2

About the Workflow Task Details View

After selecting a task from the task list, a view opens displaying the task details and enabling the user to make a decision regarding the task. When the application is run on an iPad, the task details are displayed on the Details pane of the iPad's SplitView.

Note
In iPad mode, all navigations from the task details (to see comments, attachments, etc.) are performed in the Details pane of the iPad's SplitView. That way, the Master pane will always display the list of all Workflow tasks and the selected task will be highlighted. The task details displayed include the following: Task subject displayed at the top of the view as the task title Task properties - status, creation date, creator and priority Task extended properties (X-props).

Note
Default extended properties are not displayed. Links to additional related task details, such as: comments, participants and attachments.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

217

218

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

The application code responsible for the task details is found at the TaskDetailsViewController component of the generated project.

8.4.7.2.1

Making a Decision for a Workflow Task

This section describes how to make a decision regarding a Workflow task. To make a decision regarding the task: 1. Choose Make Decision. The list of possible actions received from the service for this task is displayed.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

219

2. 3.

Choose an action to apply it or choose Cancel to return to the task details. After selecting an action, you can add a comment to be sent together with the task. Choose the button with the action name to apply it. Choose Cancel to return to the task details without applying the action.

After applying the action, the Task List view is once more displayed and the completed task no longers appear in the task list. The application code responsible for the decision actions is found in the TaskDetailsViewController and CommentViewController components of the generated project.

8.4.7.2.2

Viewing Task Attachments

The Details view includes a link to the task attachments (if there are any) showing also the number of attachments included.

220

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

To view attachments: 1. Choose Attachments. A view showing the file names of the tasks attachments is displayed.

2.

Choose an attachment. The attachment opens in the appropriate content viewer according to the file type. The application code responsible for the task comments is found in the AttachmentsViewController component of the generated project.

8.4.7.2.3

Viewing Task Participants

The Details view includes a link to the task participants (if there are any) showing also the number of participants included. To view task participants: Choose Participants. A view showing the task participant names and types is displayed.

The application code responsible for the task participants is found in the ParticipantsViewController component of the generated project.

8.4.7.2.4

Viewing Task Comments

The Details view includes a link to the task comments (if there are any) showing also the number of comments included. To view the task comments: Choose Comments. A view showing a list of task comments including each comments creator, creation date, and content is displayed.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

221

The application code responsible for the task comments is found in the CommentsViewController component of the generated project.

8.4.7.2.5

Viewing Task Description

To view the task description: Choose Description. A view showing the task description is displayed.

The application code responsible for the task comments is found in the DescriptionViewController component of the generated project.

222

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

8.4.7.3

About Push Notifiations in iOS

When the generated Workflow application is in SUP mode, it supports SUP and Apple (APNS) Push notifications. To enable the Push notications, the mobile device you must do the following: Register for APNS notifications Register for SUP online notifications Subscribe to the SAP NetWeaver Gateway Workflow service

Before enabling Push, make sure you have configured the the Apple Push in the SUP server. To configure the Apple Push in the SUP server: Follow steps 1 through 3 in the Provisioning an Application for Apple Push Notification Service procedure in the Sybase documentation.

Related Links

Registration to APNS Notifications [page 223] APNS notifications are used mainly to send notifications to the device when the application is in the background or not running. Registration to SUP Online Notifications [page 224] SUP notifications do not involve Apples APNS server. This is a direct communication between the SUP Server and the running application. Subscription to Workflow Service Notifications [page 224] The application creates a new subscription for the Workflow service notifications after registering for APNS and SUP notifications. http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc01708.0213/doc/html/ apr1274302014056.html

8.4.7.3.1

Registration to APNS Notifications

APNS notifications are used mainly to send notifications to the device when the application is in the background or not running. SUP sends a request to Apples APNS server to send the notification to the device. After a successful login, the [SUPHelper registerForAPNSPush]method is called to register the device token with the APNS Server. The following delegate methods handle registration and incoming APNS notifications: application:didRegisterForRemoteNotificationsWithDeviceToken: called on successful APNS registration. Registers the device token with SUP. application:didFailToRegisterForRemoteNotificationsWithError: called on failed APNS registration. Reports failed registration to SUP. application:didReceiveRemoteNotification: called on incoming notifications. Reports APNS notification to SUP. To customize the Apple notifications on your device:

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

223

1. 2.

Select

Settings

Notifications

<app name> .

Perform the desired configurations.

8.4.7.3.2

Registration to SUP Online Notifications

SUP notifications do not involve Apples APNS server. This is a direct communication between the SUP Server and the running application. The WorkflowAppDelegate implements a method called pushNotificationReceived:. To set the WorkflowAppDelegate as the delegate for these incoming notifications, the [SUPHelper setPushDelegate] is called. When the notification is received, the application shows a popup that allows the user to switch to the main task list view and refresh it or dismiss.

8.4.7.3.3

Subscription to Workflow Service Notifications

The application creates a new subscription for the Workflow service notifications after registering for APNS and SUP notifications. The subscription is created on the WorkflowTaskCollection created event type by calling the [requestHandler createSubscriptionForCollection:withChangeType:andFilterQuery:andSelectQuery:] method which means a notification is sent each time a new item is created in the WorkflowTaskCollection. The subscription is only created if no other subscription already exists for this user on the same collection and with the same device.

224

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

8.4.7.4 Additional Components in the iOS Workflow Generated Application


The generated project includes a component called Utilities. This component contains some useful methods used by the application, such as: capitalizeString, formatDate, convertStringToInteger, formatFullDate, sizeFromTextInSystemFont, and methods for mapping task priorities to meaningful descriptions and colors. A developer extending the application can use these methods in the extension code, as needed. In addition, some custom table cells were created to be used in the generated application (for example, ItemWithCounterIndicatorCell).

8.4.7.5

About the Form Generated Application UI Utilities

The Form UI Utilities folder contains the UI components and utilities for displaying and editing the form property values of different OData types. These components and utilities are used in the generated form views, and can be also used for extending the generated application. The folder includes additional views that are used for editing more complex types of property values that should not be simply entered into a text field or selected using a UI switch: The DateTimeViewController is used for editing DateTime and Time property values.

The ValueListViewController can be used for editing a String value by selecting a value from a preconfigured list of values instead of asking to user to enter the correct value into a text field.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

225

The folder also includes the FormUtilities class that contains methods for creating the table custom cells for each type of property (including those that should be edited using additional views), and for openning the additional views (as modal views), for example, when the appropriate cell is selected. In addition, the Form UI Utilties folder includes a custom cell view that is used for creating the different types of the form table cells and some other internal classes that are used by the FormUtilities class methods. For more information, see the documentation of the classes and methods located in the header files at the Form UI Utilities folder.

8.4.8

About the Form Generated Application

The generated Form iOS application is a starting point for developing an iOS application that allows the creation of SAP Data using the services exposed via SAP NetWeaver Gateway. It is generated as a Universal application which can run on both iPhone and iPad devices.

226

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

The application project is composed of the form views generated by the tool using the wizard, and the proxy classes of the selected service, which use the SAP OData Mobile Client SDK and the semantic proxy framework classes. The project also includes the Form UI Utilities folder that contains the UI components and utilities for displaying and editing the form property values of different OData types. In addition, the Form application project includes the components that are common to all the generated applications. For more information, see the Generated iOS Application Structure section. Related Links

Generated iOS Application Structure [page 197] The iOS starter application files based on the selected template are created and located in a specified folder. The generated project is an Xcode iOS project.

8.4.8.1

iOS Form Generated Application Screens

The generated application is displayed as a form in which you can create new entites that will be added to the enitity-set selected in the tool's wizard. The form is organized as a table where each of its cells represents a single entity's property that was selected in the tool's wizard, and the user can enter the desired property value. The form also contains a Submit button for sending the service request for creating the new entity with the values entered in the form. On a successful creation, the form is cleared and is ready for creating another entity.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

227

The user can enter a value for each property in the form's table according to the property type: String, Number and Decimal Number values are entered using a text field located in the table cell. DateTime andnew form Date values are entered by selecting the table cell, choosing the desired value from the displayed picker, and clicking Done. To clear the property value, click Clear in the DateTimeViewController. Boolean values are entered using a UI switch control field located in the table cell. Values of complex type properties are entered in a separate view to which you can navigate by selecting the appropriate table cell of the form.

The entity required properties (that must have a value) are marked in the form using a 'Required' placeholder. The Submit button of the form is disabled until the user enters values for all the required properties. To display the appropriate UI components for each of the form properties as described above, the form view uses the UI components and the utility methods of the Form UI Utilities. For more information, see the About the Form Generated Application UI Utilities section. In addition to the main form view, each of the complex type properties of the entity that is selected in the tool's wizard, is represented by a separate view that is also generated with the application and enables entering values for all the properties of this complex type. These views are similar to the main form view, except that they do not contain a Submit button.

228

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

The complex type form view may also have a 'Required' indicator for the required properties of the complex type (if there are any). Note that if the complex type itself is not marked as 'Required' (as in the previous application screen, where it is possible to navigate to the complex type form view), but contains some required properties, navigating back from the complex type view without filling its required properties will trigger an alert. If these properties are not filled before submitting the form, the submit operation may fail.

Related Links

About the Form Generated Application UI Utilities [page 225] The Form UI Utilities folder contains the UI components and utilities for displaying and editing the form property values of different OData types. These components and utilities are used in the generated form views, and can be also used for extending the generated application.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

229

8.4.8.2

About the Form Generated Application UI Utilities

The Form UI Utilities folder contains the UI components and utilities for displaying and editing the form property values of different OData types. These components and utilities are used in the generated form views, and can be also used for extending the generated application. The folder includes additional views that are used for editing more complex types of property values that should not be simply entered into a text field or selected using a UI switch: The DateTimeViewController is used for editing DateTime and Time property values.

The ValueListViewController can be used for editing a String value by selecting a value from a preconfigured list of values instead of asking to user to enter the correct value into a text field.

The folder also includes the FormUtilities class that contains methods for creating the table custom cells for each type of property (including those that should be edited using additional views), and for openning the additional views (as modal views), for example, when the appropriate cell is selected. In addition, the Form UI Utilties folder includes a custom cell view that is used for creating the different types of the form table cells and some other internal classes that are used by the FormUtilities class methods. For more information, see the documentation of the classes and methods located in the header files at the Form UI Utilities folder.

230

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

8.4.8.3 Modifing the Generated Form Application to Create an Entity in a Non-Addressable Collection
Some collections may be creatable, but they are not addressable, meaning they can only be accessed from a navigation property. For example, when a user has several communication methods (email, telephone, etc.), creating a new communication method to a specific user by using a navigation property from the user to his/her communication methods, is a valid scenario. However, adding a communication method to a list of all communication methods is not possible. When constructing the form application in design time, it is possible to select a non-addressable collection and an application will be generated. The generated application will not work out-of-the-box, it will require manual modifications.

Note
The procedure described below is based on a Form application generated on a service with the following properties: Two collections: UserCollection and CommunicationCollection. There is a navigation property from UserCollection to CommunicationCollection, named Communications. Both collections have one key property named id. The ID of both collections must be the same (user and communication collections).

To modify the application: 1. 2. 3. Open the generated Xcode project. Go to the service folder and open the <service_name>RequestHandler.h file. Add the following signature to the class: - (void)createCommunication:(Communication *)aCommunication withUserId:(NSString *)userId; 4. 5. In the Service folder, open the <service_name>RequestHandler.m file. Add the following method implementation to the class: - (void)createCommunication:(Communication *)aCommunication withUserId:(NSString *)userId { // Use proxy in order to get the query for the specific user we would like to add the communication item to ODataQuery *userQuery = [service getUserCollectionEntryQueryTypedWithId:userId]; // Construct the query to the communication collection of the specific user (using navigation property) NSString *createUserCommunicationURL = [NSString stringWithFormat:@"%@/Communications",[userQuery.URL absoluteString]]; ODataQuery *createUserCommunicationQuery = [[ODataQuery alloc] initWithURL: [NSURL URLWithString:createUserCommunicationURL]]; // Execute the create request using the constructed query if (!csrfData) { csrfData = [connectivityHelper

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

231

getCSRFDataForServiceQuery:service.serviceDocumentQuery]; } NSError *error = nil; NSString *xml = [service getXMLForCreateRequest:aCommunication error:&error]; if (error) { NSMutableDictionary *userInfoDict = [@{} mutableCopy]; userInfoDict[kParsingError] = error; [[NSNotificationCenter defaultCenter] postNotificationName:kCreateCommunicationCompletedNotification object:self userInfo:userInfoDict]; } else { NSDictionary *userInfoDict = @{kResponseParentItem : aCommunication , kRequestUserInfoCompletedNotification : kCreateCommunicationCompletedNotification}; [connectivityHelper executeCreateAsyncRequestWithQuery:createUserCommunicationQuery andBody:xml andCSRFData:csrfData andRequestDelegate:self andDidFinishSelector:@selector(createCommunicationCompleted:) andUserInfo:userInfoDict]; } }

Note
The implementation is almost the same as the already generated method createCommunication: (Communication *)aCommunication. The additional code at the beginning of the method constructs the correct query that contains the user for which you want to create the new communication item. 6. In the Communication Form view controller, edit the submitClicked method as follows to get the user ID from the relevant property of the Communication object and then use the new method you created in steps 3-5 above in the Request Handler: - (void)submitClicked { self.view.userInteractionEnabled = NO; [[<service_name>RequestHandler uniqueInstance] createCommunication:self.communicationItem withUserId: self.communicationItem.id]; }

8.4.8.4

Generated iOS Form Application Limitations

This section describes the limitations of the Generated iOS Form Application The Form application has the following limitations: The application is compatible only with iOS version 6.0 and higher. The generated application and the Form UI Utilties do not support OData properties of type Edm.Binary (that are represented as NSData objects).

8.4.9

Running the Generated iOS Application

This section describes how to run the generated iOS application in the iPhone simulator.

232

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

To run the generated application in the iPhone simulator: 1. 2. 3. Open the generated application project in Xcode. From the Product menu, select Edit Scheme. From the Destination drop-down list, select iPhone 5.0 Simulator.

Note
To run the generated List/Details Universal application on the iPad simulator, select iPad 5.0 Simulator. 4. 5. 6. If you want to debug, from the Build Configuration drop-down list, select Debug. Click OK. In the Xcode toolbar, click Run.

8.4.10 Configuring a Starter Kit Application to Work with SUP


Before configuring a starter kit application to work with SUP, make sure you have completed the prerequisites described in the Prerequistes for Working with the SUP Server Using the Generated Proxy section Before configuring a starter kit application to work with SUP, make sure you have completed the prerequisites described in the Prerequistes for Working with the SUP Server Using the Generated Proxy section 1. 2. Make the changes required for enabling the proxy to support SUP connectivity as described in the Enabling the Proxy to Support SUP Connectivity section. In the Application Settings screen, select SUP as the Connection Mode. In addition, open the SUP Server Details settings and set the appropriate values (as configured in the SUP server) for the following properties: Application ID, SUP server host and port, Farm ID, and security configuration.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

233

3.

If you want to use client certificate authentication when working with the SUP server, open the SUP Server Details settings from the application settings screen, and change the Send Client Certificate option to ON. In addition, make sure you have performed the required operations for client certificate authentication as described in the Configuring the User Authentication in an iOS Starter-Kit Application section. Open the LoginScreenViewController.m file and configure the Vault password appropriately for calling the Request Handler's login method (from the handleSignIn method implementation). You can set the password with your own value or receive it from the user: /** TODO: Make sure to set this value as desired, or get it from the user - if SUP sever is used. */ NSString *vaultPassowrd = @"MyVaultPassword"; // This value is ignored if not in SUP mode.

4.

Note
If you are configuring a Basic application, the Vault password value is configured in the viewDidLoad method implementation of the SampleViewController.m file. Related Links

Prerequistes for Working with the SUP Server Using the Generated Proxy [page 194] Before you upgrade your application to work with the SUP server, you must do the following: Enabling the Proxy to Support SUP Connectivity [page 194] This section explains how to enable the generated proxy to support SUP connectivity. Configuring the User Authentication in an iOS Starter-Kit Application [page 236] All the generated applications use Basic authentication by default.

8.4.11 Translation Enablement in iOS Generated Applications


All the generated applications support translation to multiple languages. The application language-specific resources, such as application strings and UI description files (.xib files), are separated. The device language settings are used in service requests for getting service runtime data and metadata in the appropriate language. Note that the developer is responsible for supplying the translated resources and configuring the appropriate settings in the SAP NetWeaver Gateway and the SAP backend systems.

Enabling Translation of Application Strings


The generated applications follow the Apple guidelines for translating iOS applications. All hard-coded strings in the application are created using the NSLocalizedString function, which enables retrieving the localized string value from the language-specific strings file (according to the device language settings), and provides a fallback to the default string value.

234

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

All application resources are provided in English and are located in the en.lproj folder together with a preliminary Localizable.strings file generated using the genstrings command-line tool during the application generation process. Note that after extending a starter kit application, the developer must reuse this command-line tool to generate the updated strings file. For more information, see the Internationalization Programming Topics guide (from Apple).

Using the Device Language Settings for Runtime Data


The generated applications display the SAP data and the fiels labels in the device language by using the runtime service document and metadata, and by sending the appropriate language code according to the device language settings with any service request. For more information, see the Using the Device Language Settings for Runtime Data section of the Request Handler. If you want to use the local service document and metadata files, follow the instructions described in the Configuring a Starter Kit Application to Work with Local Service Document and Metadata section below. Note that in this case, the field labels are displayed in the language of the local files and they cannot be translated. Related Links

http://developer.apple.com/library/ios/#documentation/MacOSX/Conceptual/BPInternational/ BPInternational.html Using the Device Language Settings for Runtime Data [page 192] To display the SAP data and the field labels in the device language, the generated service Request Handler sends the appropriate language code according to the device language settings with any service request. This language code is sent as the value of the sap-langauge HTTP header.

8.4.12 Configuring an iOS Starter Kit Application to Work with Local Service Document and Metadata
When a user logs in, the generated applications retrieve the service document and metadata in runtime. You can configure the application to work with the local service document and metadata files that were used by the tool to generate the application. For more information, see the Configuring the Request Handler to Work with Local Service Document and Metadata section. Note that when working with the local service document and metadata, the service versioning negotiation feature is disabled. To configure the application to work with the local files: 1. Open the ListDetailsAppDelegate.m, WorkflowAppDelegate.m, and FormAppDelegate.m or BasicAppDelegate.m file.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

235

2.

In the configureRequestHandlerSettings method implementation, set the value of the useServiceNegotiation property of the Request Handler instance to YES. /* Set to 'NO' to disable service negotiation */ requestHandler.useLocalMetadata = YES;

Related Links

Configuring the Request Handler to Work with Local Service Document and Metadata [page 192] When a user logs in and the login method of the service Request Handler is called, the Request Handler retrieves the service document and metadata in runtime, and uses them to initiate the proxy object.

8.4.13 Service Versioning Negotiation


All the generated applications use service versioning negotiation to find the most appropriate service version in runtime, according to the defined minimal and maximal versions that are supported by the application. For more information see the Service Versioning Negotiation section of the Request Handler. To change the values of the minimal and maximal service versions supported by the application: 1. 2. Open the [Service Name]RequestHandler.m file. Set the desired values for the TechnicalServiceVersionMin and TechnicalServiceVersionMax constants. To disable the service versioning negotiation feature: 1. 2. Open the ListDetailsAppDelegate.m, WorkflowAppDelegate.m, FormAppDelegate.m or BasicAppDelegate.m file. In the configureRequestHandlerSettings method implementation, set the value of the useServiceNegotiation property of the Request Handler instance to NO. /* Set to 'NO' to disable service negotiation */ requestHandler.useServiceNegotiation = NO; Related Links

Service Versioning Negotiation [page 193] The service negotiation method of the service Request Handler is called from the login method as part of the login process.

8.4.14 Configuring the User Authentication in an iOS StarterKit Application


All the generated applications use Basic authentication by default. The default authentication type also supports the SAML2 protocol with an Identity Provider server that supports the Basic or Integrated/NTLM authentication method. If a domain is also required, the user can enter a user name in the relevant field on the Login Screen using the following format: [user-domain]\[user-name].

236

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

The generated application can be easily configured to support other authentication methods.

Changing the authentication method used by the application to SAP Portal SSO when the selected Connection Mode is set to Gateway
1. 2. From the Application Settings screen, select SAP Portal as the Gateway Connection Auth Method value. Open the SAP Portal Details settings and set the required SAP Portal Service URL value.

Changing the authentication method used by the application to SAP Portal SSO when the selected Connection Mode is set to SUP
From the Application Settings screen, open the SUP Server Details settings and make sure the Send Client Certificate option is set to OFF.

Note
You should make the required configurations on the SAP NetWeaver Gateway server and the Portal server (and also the SUP server, if relevant) to support the Portal SSO authentication.

Changing the authentication method used by the application to an X.509 Client Certificate
1. 2. 3. 4. 5. 6. Store the X.509 client certificate in a file, and name it client_certificate.pfx. Override the existing client_certificate.pfx that was generated with the application (under Supporting Files) with the file from step #1. If you add a new file make sure it is added to the application bundle. In the RequestHandlerConstants.m file (under Services/Framework), enter the certificate password (the password entered when storing the client certificate to a file) in the kCertificatePassword constant. Make sure the kCertificateFileName and kCertificateExtension values are in accordance to the file added in step #2. If the selected Connection Mode is set to Gateway (working directly with SAP NetWeaver Gateway server): from the application settings screen, select Client Certificate as the Gateway Connection Auth Method value. If the selected Connection Mode is set to SUP (working with SUP server): from the application settings screen, open the SUP Server Details settings and set the Send Client Certificate option to ON.

Note
You should make the required configurations on the SAP NetWeaver Gateway server (and also the SUP server, if relevant) to support the X.509 Client Certificate authentication.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

237

Related Links

User Authentication and Login Process [page 190] The service Request Handler includes methods for performing user login. Generated iOS Application Structure [page 197] The iOS starter application files based on the selected template are created and located in a specified folder. The generated project is an Xcode iOS project.

8.4.15 About the Application Logs


This section describes how to view and send application logs.

8.4.16 Extending the Generated iOS Starter Application


You can extend the generated application in any way you want. This section describes some of the most common extensions.

8.4.16.1 Configuring the Service URL


This section describes how to configure the service URL.

Configuring the Default Service URL


1. 2. 3. 4. Open the application you generated in Xcode. Go to Settings.bundle Gateway.plist . Item 3 DefaultValue .

In the plist file, go to

Preference Items

Click the Value field and change the service default value as necessary.

Configuring the Service URL at Runtime


1. 2. 3. From your iPhone, go to the Settings menu. Select the application you created. Under the Gateway Connection section, open the Service Details settings, and edit the URL as needed.

238

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

8.4.16.2 Adding a Service Call


You can use the Request Handler generated with the application to add asynchronous service calls to the application views (the generated views or your own views).

Note
You can also add your own methods to the Request Handler or modify the generated methods for using any required functionality provided by the generated proxy. (For example, you can add query parameters such as $expand or $top before performing the call). For more information, see the Using the Proxy in your iOS Application section. To add a service call to a view controller: 1. 2. Call the appropriate Request Handler method for executing the desired service request. In the view controllers initWithNibName method, sign up for the notification that is posted when the asynchronous service request (that is executed by the method in step 1) is completed and the service response data is successfully received, or an error is returned. When signing up to the notification, define the view controller method that will be called when the notification is posted. Implement the view controller method defined in step 2 to handle the notification. Optionally, you can use this method to display the response data. For more information regarding the appropirate notification and the information that can be extracted from the notification's userInfo dictionary, open the Request Handlers header file and see the documentation of the method called in step 1. The steps above are relevant for all types of service calls. The code snippets in the Service Call Code Snippets section show how to perform the following service operations: Create, Update, and Delete a collection item. Read navigation items. Call a service Function Import. Read, Create, Update, and Delete an item's media resource.

3.

The examples provided in this section are based on an application generated from the RMTSAMPLEFLIGHT service. Related Links

Using the Proxy in your iOS Application [page 171] This section provides code snippets showing how to use the generated proxy in your application. The examples show proxy classes generated from the RMTSAMPLEFLIGHT service. Service Calls Code Snippets [page 239] This section describes the types of service operations possible for revice calls/

8.4.16.2.1

Service Calls Code Snippets

This section describes the types of service operations possible for revice calls/

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

239

The code snippets below show how to perform the following service operations: Create, Update, and Delete a collection item. Read navigation items. Call a service Function Import. Read, Create, Update, and Delete an item's media resource.

The examples provided in this section are based on an application generated from the RMTSAMPLEFLIGHT service.

Create Example
The following code snippet shows how to create a Travel Agency item. - (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(createTravelagencyCompleted:) name:kCreateTravelagencyCompletedNotification object:nil]; } return self; } - (void) createTravelagencyCompleted:(NSNotification *)notification { // Handle the Create operation response and display it in the view NSDictionary *userInfoDict = [notification userInfo]; NSError *error = [userInfoDict objectForKey:kServerResponseError] ? [userInfoDict objectForKey:kServerResponseError] : [userInfoDict objectForKey:kParsingError]; if (error) { // Handle a server response error or response parsing error [Utilities showErrorDialogWithError:error]; } else { // Display the created item Travelagency *tAgency = [userInfoDict objectForKey:kResponseItem]; if (!tAgency) { // No response data received with the service response // use the object used for calling the Create operation. tAgency = [userInfoDict objectForKey:kResponseParentItem]; } NSString *message = [NSString stringWithFormat:@"Successfully created travel agency (%@).\n", tAgency.agencynum]; self.content.text = [self.content.text stringByAppendingString:message]; } } - (void) createTravelagency { // Execute the Create operation Travelagency *tAgency = [[Travelagency alloc] init]; tAgency.agencynum = @"00000074"; tAgency.NAME = @"Basic Agency"; [[RMTSAMPLEFLIGHTRequestHandler uniqueInstance] createTravelagency:tAgency]; }

240

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

Update Example
The following code snippet shows how to update a Travel Agency item. - (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateTravelagencyCompleted:) name:kUpdateTravelagencyCompletedNotification object:nil]; } return self; } - (void) updateTravelagencyCompleted:(NSNotification *)notification { // Handle the Update operation response and display it in the view NSDictionary *userInfoDict = [notification userInfo]; NSError *error = [userInfoDict objectForKey:kServerResponseError] ? [userInfoDict objectForKey:kServerResponseError] : [userInfoDict objectForKey:kParsingError]; if (error) { // Handle a server response error or response parsing error [Utilities showErrorDialogWithError:error]; } else { // Display the updated item Travelagency *tAgency = [userInfoDict objectForKey:kResponseItem]; if (!tAgency) { // No response data received with the service response // use the object used for calling the Update operation. tAgency = [userInfoDict objectForKey:kResponseParentItem]; } NSString *message = [NSString stringWithFormat:@"Successfully updated travel agency (%@) with name %@.\n", tAgency.agencynum, tAgency.NAME]; self.content.text = [self.content.text stringByAppendingString:message]; } } - (void) updateTravelagency:(Travelagency *) tAgency { // Execute the Update operation tAgency.NAME = @"Basic Agency2"; [[RMTSAMPLEFLIGHTRequestHandler uniqueInstance] updateTravelagency:tAgency]; }

Delete Example
The following code snippet shows how to delete a Travel Agency item. - (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteTravelagencyCompleted:) name:kDeleteTravelagencyCompletedNotification object:nil]; }

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

241

return self; } - (void) deleteTravelagencyCompleted:(NSNotification *)notification { // Handle the Delete operation response and display it in the view NSDictionary *userInfoDict = [notification userInfo]; NSError *error = [userInfoDict objectForKey:kServerResponseError]; if (error) { // Handle a server response error [Utilities showErrorDialogWithError:error]; } else { // Display the deleted item (use the object used for calling the Delete operation) Travelagency *tDeletedAgency = [userInfoDict objectForKey: kResponseParentItem]; NSString *message = [NSString stringWithFormat:@"Successfully deleted travel agency (%@).\n", tAgency.agencynum]; self.content.text = [self.content.text stringByAppendingString:message]; } } - (void) deleteTravelagency:(Travelagency *) tAgency { // Execute the Delete operation [[RMTSAMPLEFLIGHTRequestHandler uniqueInstance] deleteTravelagency:tAgency]; }

Create Navigation Property Example


The following code snippet shows how to create a booking navigation property for a flight item. - (void)createBooking:(Booking *)aBooking forFlight:(Flight *)aFlight { if (!csrfData) { csrfData = [connectivityHelper getCSRFDataForServiceQuery:service.serviceDocumentQuery]; } NSError *error = nil; NSString *xml = [service getXMLForCreateRequest:aBooking error:&error]; if (error) { NSMutableDictionary *userInfoDict = [@{} mutableCopy]; userInfoDict[kParsingError] = error; [[NSNotificationCenter defaultCenter] postNotificationName:kCreateBookingCompletedNotification object:self userInfo:userInfoDict]; } else { NSDictionary *userInfoDict = @{kResponseParentItem : aBooking , kRequestUserInfoCompletedNotification : kCreateBookingCompletedNotification}; [connectivityHelper executeCreateAsyncRequestWithQuery:aFlight.flightBookingsQuery andBody:xml andCSRFData:csrfData andRequestDelegate:self andDidFinishSelector:@selector(createBookingCompleted:) andUserInfo:userInfoDict]; } }

242

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

Read Navigation Example


The following code snippet shows how to read the Booked Flight navigation item related to a selected Booking item. - (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadBookedFlightForBookingCompleted:) name:kLoadBookedFlightForBookingCompletedNotification object:nil]; } return self; } - (void)loadBookedFlightForBookingCompleted:(NSNotification *)notification { // Handle the Read Navigation operation response and display it in the view NSDictionary *userInfoDict = [notification userInfo]; Booking *responseParentItem = [userInfoDict objectForKey:kResponseParentItem]; //Handle notification only if related to the same item selected in the previous view: if ([[responseParentItem.baseUrl absoluteString] isEqualToString: [self.parentBookingItem.baseUrl absoluteString]]) { [self hideLoadingIndicator]; NSError *error = [userInfoDict objectForKey:kServerResponseError] ? [userInfoDict objectForKey:kServerResponseError] : [userInfoDict objectForKey:kParsingError]; if (error) { // Handle a server response error or response parsing error [Utilities showErrorDialogWithError:error]; } else { Flight *responseItem = [userInfoDict objectForKey:kResponseItem]; presentedItem = responseItem; [self.detailTableView reloadData]; } } } - (void) viewDidLoad { [super viewDidLoad]; [self showLoadingIndicator]; // Execute the Read Navigation operation [[RMTSAMPLEFLIGHTRequestHandler uniqueInstance] loadBookedFlightForBooking:self.parentBookingItem]; }

Note
Since the process is asynchronous, there is a validation that the displayed data is related to the Booking item that is currently associated with the view. For example, the Booking item that was selected at the previous view displaying a list of Booking items. This is done to avoid displaying data returned in response to a previous call. This validation is done by comparing the base URL of the Booking object sent with the current handled notification to the one that was set in the parentBookingItem property of the view. For example, this property can be set by the previous view when a Booking item is selected. If the two match, then it is the same

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

243

Booking item and the related Flight information is saved in the presentedItem instance variable of the view. The UI is then reloaded to display the updated data.

Function Import Example


The following code snippet shows how to call the Check Flight Availability service operation. - (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(executeCheckFlightAvailabilityCompleted:) name:kExecuteCheckFlightAvailabilityCompletedNotification object:nil]; } return self; } - (void)executeCheckFlightAvailabilityCompleted:(NSNotification *)notification { // Handle the CheckFlightAvailability operation response and display it in the view NSDictionary *userInfoDict = [notification userInfo]; NSError *error = [userInfoDict objectForKey:kServerResponseError] ? [userInfoDict objectForKey:kServerResponseError] : [userInfoDict objectForKey:kParsingError]; if (error) { // Handle a server response error or response parsing error [Utilities showErrorDialogWithError:error]; } else { // Display the function-import response item FlightAvailability *flightAvailability = [userInfoDict objectForKey:kResponseItem]; NSString *result = [NSString stringWithFormat:@"ECONOFREE: %@",[flightAvailability.ECONOFREE stringValue]]; self.content.text = result; } } - (void)checkFlightAvailability { // Execute the CheckFlightAvailability operation NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *dateComp = [[NSDateComponents alloc] init]; [calendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]]; dateComp.year = 2011; dateComp.month = 12; dateComp.day = 20; [[RMTSAMPLEFLIGHTRequestHandler uniqueInstance] executeCheckFlightAvailabilityWithAirlineid:@"AA" andConnectionid:@"0017" andFlightdate:[calendar dateFromComponents:dateComp]]; }

244

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

Read Media Link Example


The following code snippet shows how to read the media resource of a Carrier item using a Media Link. - (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadMediaLinkCompleted:) name:kLoadCarrierMediaLinkCompletedNotification object:nil]; } return self; } - (void) loadMediaLinkCompleted:(NSNotification *)notification { // Handle the Read Media Link operation response and display it in the view NSDictionary *userInfoDict = [notification userInfo]; NSError *error = [userInfoDict objectForKey:kServerResponseError]; if (error) { // Handle a server response error [Utilities showErrorDialogWithError:error]; } else { // Display the media resource response data NSData *responseData = [userInfoDict objectForKey:kResponseData]; MediaLink *requestMediaLink = [userInfoDict objectForKey:kRequestedMediaLink]; if ([requestMediaLink.contentType isEqualToString:@"image/png"]) { UIImage *image = [UIImage imageWithData responseData]; self.imageView.image = image; } } } - (void) loadMediaLinkForCarrier(Carrier *)aCarrier { // Execute the Read Media Link operation [[RMTSAMPLEFLIGHTRequestHandler uniqueInstance] loadLoadCarrierMediaLink:aCarrier]; }

Create Media Link Example


The following code snippet shows how to create a Carrier item media resource using a Media Link. - (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(createMediaLinkCompleted:) name:kCreateCarrierMediaLinkCompletedNotification object:nil]; } return self; }

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

245

- (void)createMediaLinkCompleted:(NSNotification *)notification { // Handle the Create Media Link operation response and display it in the view NSDictionary *userInfoDict = [notification userInfo]; NSError *error = [userInfoDict objectForKey:kServerResponseError]; if (error) { // Handle a server response error [Utilities showErrorDialogWithError:error]; } else { // Display the created carrier media resource details MediaLink *requestMediaLink = [userInfoDict objectForKey:kRequestedMediaLink]; NSString *message = [NSString stringWithFormat:@"Successfully created carrier media resource of type %@.\n", requestMediaLink.contentType]; self.content.text = [self.content.text stringByAppendingString:message]; } } - (void)createMediaLink:(Carrier *)aCarrier { // Execute the Create Media Link operation NSString *path = [[NSBundle mainBundle] pathForResource:@"icon" ofType:@"png"]; NSMutableData *data = [[NSMutableData alloc] initWithContentsOfFile:path]; NSString *baseURL = [[RMTSAMPLEFLIGHTRequestHandler uniqueInstance] serviceDocumentURL]; NSURL *url = [NSURL URLWithString:[NSString stringWithFormat: @"%@/CarrierCollection",baseURL]]; ODataQuery *query = [[ODataQuery alloc] initWithURL:url]; MediaLink *mediaLink = [[MediaLink alloc] initWithQuery:query andContentType:@"image/png" andSlug:aCarrier.carrid]; [[RMTSAMPLEFLIGHTRequestHandler uniqueInstance] createCarrierMediaLink:mediaLink withData:data]; }

Update Media Link Example


The following code snippet shows how to update a media resource of a Carrier item, using a Media Link. - (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateMediaLinkCompleted:) name:kUpdateCarrierMediaLinkCompletedNotification object:nil]; } return self; } - (void)updateMediaLinkCompleted:(NSNotification *)notification { // Handle the Update Media Link operation response and display it in the view NSDictionary *userInfoDict = [notification userInfo]; NSError *error = [userInfoDict objectForKey:kServerResponseError]; if (error) { // Handle a server response error [Utilities showErrorDialogWithError:error]; } else { // Display the updated carrier media resource details Carrier *aCarrier = [userInfoDict objectForKey:kResponseParentItem];

246

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

MediaLink *requestMediaLink = [userInfoDict objectForKey:kRequestedMediaLink]; NSString *message = [NSString stringWithFormat:@"Successfully created media resource of type %@ for carrier %@.\n", requestMediaLink.contentType, aCarrier.CARRNAME]; self.content.text = [self.content.text stringByAppendingString:message]; } } - (void)updateMediaLink:(Carrier *)aCarrier { NSString *path = [[NSBundle mainBundle] pathForResource:@"icon" ofType:@"png"]; NSMutableData *data = [[NSMutableData alloc] initWithContentsOfFile:path]; [[RMTSAMPLEFLIGHTRequestHandler uniqueInstance] updateCarrierMediaLink:aCarrier withData:data andContentType:@"image/png"]; }

Delete Media Link Example


The following code snippet shows how to delete a media resource of a Carrier item, using a Media Link. - (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteMediaLinkCompleted:) name:kDeleteCarrierMediaLinkCompletedNotification object:nil]; } return self; } - (void)deleteMediaLinkCompleted:(NSNotification *)notification { // Handle the Delete Media Link operation response and display it in the view NSDictionary *userInfoDict = [notification userInfo]; NSError *error = [userInfoDict objectForKey:kServerResponseError]; if (error) { // Handle a server response error [Utilities showErrorDialogWithError:error]; } else { // Display the updated carrier media resource details Carrier *aCarrier = [userInfoDict objectForKey:kResponseParentItem]; NSString *message = [NSString stringWithFormat:@"Successfully deleted media resource for carrier %@.\n", aCarrier.CARRNAME]; self.content.text = [self.content.text stringByAppendingString:message]; } } - (void)deleteMediaLink:(Carrier *)aCarrier { [[RMTSAMPLEFLIGHTRequestHandler uniqueInstance] deleteCarrierMediaLink:aCarrier]; }

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

247

8.4.17 Troubleshooting for the Toolkit for iOS (GWPA)


This section contains the known issues found for the Toolkit for iOS (GWPA). Issue The generated application's UI can only display simple type entity properties. Values of complex type entity properties are not displayed at runtime. Solution You can access values of complex type entity properties programmatically through the generated proxy. Issue To replace binary files in an existing Xcode project (for example, if you want to replace the SDM libraries with a newer version of the libraries), you must erase the Xcode cache before replacing the files in the project folder (otherwise the change does not take effect). Solution Erase the cache: 1. 2. Go to /Users/<your_user_name>/Library/Developer/Xcode/DerivedData. Under the DerivedData folder, delete all the folders containing the desired projects name.

If the change still doesn't take effect, you can also reset the content and settings of the iOS Simulator: 1. 2. Run the iOS Simulator. From the iOS Simulator menu, select Reset Content and Settings.

Issue When a new Gateway connection is installed, the URLs in the metadata are relative URLs and not full URLs. This means that no services are loaded. Solution Implement note 1587789. Issue The sap:label attribute is empty for complex type properties. The sap:label attribute value returns an empty string for complex type properties, this value is not set by the SAP OData Mobile Client SDK. As a fallback, the entity object of the generated proxy returns the complex type property name as the value of its label. Solution No solution is currently available. Issue Some SAP services that are OData compliant may contain entities, complex types, or fields that are similar to Objective-C reserved keywords or include characters that are illegal in Objective-C names, such as, return , case, and abc-dfg .

248

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

When the Proxy Generation wizard comes across these occurrences, it creates proxy files with incorrect content, such as, return as the entity type name and abc-dfg as a property name. Solution After the proxy is generated, manually fix the compilation errors by renaming the generated code to use legal Objective-C names. For example, return1 , case1 , and abc_dfg . Issue Some SAP services that are OData compliant may contain entity types that have the same name in several SAP services. If a proxy is generated for services which have the same entity type names, the generated proxy will not compile. Solution Open the generated service file and manually rename the duplicate names in the source code. We recommended you add a prefix to the class names to prevent compilation errors. Issue Generated code text in languages other than English is not displayed properly. Solution To enable all characters to be displayed, follow the instructions in the Supported Languages other than English section and regenerate the code. Logs To see the logs created by the generated code, go to /Applications/Console. To see the logs created by the tool, use the Eclipse Error Log view. SAP Semantics The SAP semantics supported by this tool are: email, telephone and URL. For more information, see the Supporting Languages other than English in the Installation Guide Related Links

https://help.hana.ondemand.com/gateway_gwpa/pdf/ SAP_NetWeaver_Gateway_Productivity_Accelerator_Inst_Guide_en.pdf

8.5

Toolkit for PHP (GWPA)

Introduction to the Toolkit for PHP (GWPA), a toolkit for service consumption for PHP platform. The SAP NetWeaver Gateway Productivity Accelerator Toolkit for PHP (GWPA) is a collection of environments, patterns, and templates, which are suitable for developing SAP solutions and applications for PHP. In addition, you can use the extensible tools of the framework to create your custom templates. Target Audience The SAP NetWeaver Gateway Productivity Accelerator Toolkit for PHP (GWPA) is targeted for developers. This document describes how to consume SAP NetWeaver Gateway services to generate a PHP Eclipse project, or generate PHP code into an existing project.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

249

If you want to use the Toolkit for PHP (GWPA), you must install the Toolkit for PHP (GWPA) for SAP NetWeaver Gateway Productivity Accelerator. Related Links

https://help.hana.ondemand.com/gateway_gwpa/pdf/ SAP_NetWeaver_Gateway_Productivity_Accelerator_Inst_Guide_en.pdf

8.5.1

Running the Toolkit for PHP (GWPA)

This procedure describes how to open the wizard for using the Toolkit for PHP (GWPA). To run the toolkit: 1. 2. From tohe Eclipse menu bar, select File > New > Other. The Select a Wizard page is displayed. Expand the OData Development node and select Service Proxy or Starter Application Project as desired.

8.5.2

Creating a Starter Application Project for PHP

You can create a List/Details starter application for PHP, to call SAP services in SAP NetWeaver Gateway. To create your PHP starter application: 1. 2. From the Eclipse menu bar, select File > New > Other . The Select a Wizard page is displayed.

Expand the OData Development node and select Starter Application Project.

250

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

3.

Choose Next. The New Starter Application Project page is displayed.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

251

4. 5. 6.

In the Project name field, enter a name for your project. From the Create new project for drop-down list, select PHP. If you have not already configured the Toolkit for PHP (GWPA), click the Configure Toolkit for PHP (GWPA) link.

252

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

7.

For the Folder for PHP executable file field, choose Browse and select the folder containing the PHP execuatable file on your system. For example, C:\Prorgam Files\PHP\.

8.

For the Folder for OData SDK for PHP field, choose Browse and select the OData SDK for PHP folder.

Note
Make sure the OData SDK for PHP is installed and configured on your system exactly as described in its user guide, which is located in the installation folder of the OData SDK at: ..\doc\User_Guide.htm. 9. Choose OK to save your preferences and to exit the window. In workspace: A new folder is created in your Eclipse workspace directory for the PHP application project. In existing folder: Choose Browse to specify an existing folder in which you want to locate the PHP application project (the project will be created in a new subfolder, under the specified location).

10. Specify the location for creating a folder for the new project. You can choose one of the following options:

Note
Specify the appropriate folder in your existing PHP server as your project location to run and test your application. 11. Choose Next. The Starter Application Templates for PHP page is displayed.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

253

12. Select the desired template. The List/Details Application template is the only template available for your PHP application. 13. Choose Next. The Location of OData Service page is displayed.

254

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

14. Select the desired SAP NetWeaver Gateway service in one of the following ways: In the Service URL field, enter the desired services URL and then choose Go. Choose Catalog and select the desired SAP service using the Service Catalog dialog. Select the File system radio button and browse for the relevant service metadata and service document.

When the service is validated, its details are displayed. 15. Choose Next. The Page Layout page is displayed.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

255

16. In the Page Title field, enter the name of the first page. 17. From the Page Type drop-down list, the List page option is automatically selected. 18. From the Entity Set Navigation drop-down list, select the desired collection. 19. Choose to see the fields available for the selected entity set. The Add Fields page is displayed.

256

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

20. Select the checkboxes of the desired fields for the page.

Note
We recommend that you not have more than 3-4 fields in a list. 21. Click OK. 22. If needed, select a field and click to delete it. 23. Use the and arrows to change the positioning of the fields in the view. 24. Under the Pages section, choose to add another page. 25. Repeat this procedure to configure the additional pages. 26. Choose Finish. An Eclipse project with the application code is created in the location you previously specified, and is displayed in your Eclipse workspace.

8.5.3

Creating a Proxy for a PHP Application

You can create a proxy to enable your PHP application to consume SAP services through your SAP NetWeaver Gateway server. The proxy provides the implementation interfaces for the SAP service you choose to use. You must create your own application to interface with the generated proxy. The proxy code is generated by the OData SDK for PHP. To create your proxy: 1. From the menu bar, select File > New > Other . The New wizard page is displayed.

2.

Expand the OData Development node and select Service Proxy.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

257

3. 4. 5. 6. 7.

Choose Next. The New Service Proxy Generation page is displayed. From the Create a new proxy for drop-down list, select PHP. Choose Browse to select the Eclipse project where you want to create the proxy. If you have not already configured the Toolkit for PHP (GWPA), click the Configure Toolkit for PHP (GWPA) link and follow steps 2-4 described in the Configuring the Toolkit for PHP (GWPA) section. Choose Next. The Location of OData Service page is displayed.

258

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

8.

Select the desired SAP NetWeaver Gateway service in one of the following ways: In the Service URL field, enter the desired services URL and then choose Go. Choose Catalog and select the desired SAP service using the Service Catalog dialog. Select the File system radio button and browse for the relevant service metadata and service document.

When the service is validated, its details are displayed. 9. Choose Finish. The PHP proxy files are added to your project.

After generating the proxy, your target project contains a Services folder with the following: A [Service Name].php file containing the PHP proxy classes for the service. This file is generated by the OData SDK for PHP. A [Service Name]_labels.php file containing an array of all the sap-labels of the service properties. A proxy_functions.php file contatining functions for handling Cross-Site Request Forgery (CSRF) protection. For more information, see the PHP Application Support for Cross Site Request Forgery Protection section. You can call the generated proxy files from your PHP application to interface with the selected SAP service through the specified SAP NetWeaver Gateway server.

Note
You must create your own user interface to render your application. You can generate a starter PHP application to see sample code for using the proxy generated for your selected service. Related Links

http://odataphp.codeplex.com/

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

259

8.5.4

Using the Proxy in your PHP Application

The proxy code is generated by the OData SDK for PHP. This section includes code samples for using the PHP proxy. The samples are based on a proxy generated for the RMTSAMPLEFLIGHT service. More examples can be found in the OData SDK for PHP user guide. You can also generate a starter PHP application to see sample code for using the proxy generated for your selected service. To use the proxy: 1. Initialize the service through its URL. <?php require_once "RMTSAMPLEFLIGHT.php"; $proxy = new RMTSAMPLEFLIGHT ('http://<Gateway_Host>:<Gateway_Port>/sap/opu/sdata/IWFND/RMTSAMPLEFLIGHT'); $proxy->Credential = new WindowsCredential('<Username>', '<Password>'); 2. Read example: Get carrier by carrier ID with an authenticated X.509 client certificate. a. Register a callback function to add the client certificate to the request. $proxy->OnBeforeRequest("DoBeforeRequest",null); b. Get carrier by carrier ID, for example, American Airlines. try { $carrier_id = 'AA'; $query = $proxy->CarrierCollection()->filter("carrid eq '$carrier_id'"); $carriers = $query->Execute()->Result; echo "Carrier ID: " . $carriers[0]->carrid . "<br/>"; echo "Carrier Name: " . $carriers[0]->CARRNAME . "<br/>"; echo "Carrier Code: " . $carriers[0]->CURRCODE . "<br/>"; echo "Carrier URL: " . $carriers[0]->URL . "<br/>"; } c. Error handling example. catch(DataServiceRequestException $exception) { echo $exception->Response->getError(); } d. Callback function to add the X.509 client certificate to the request. function DoBeforeRequest($httpRequest) { $refProp = new ReflectionProperty('HttpRequest','_curlHandle'); $refProp->setAccessible(true); $curlReq = $refProp->getValue($httpRequest); curl_setopt($curlReq, CURLOPT_RETURNTRANSFER, true); curl_setopt($curlReq, CURLOPT_FOLLOWLOCATION, true); curl_setopt($curlReq, CURLOPT_SSL_VERIFYHOST, 1); curl_setopt($curlReq, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($curlReq, CURLOPT_CAINFO, '<Gateway_CA_Certificate_Path>.cer'); curl_setopt($curlReq, CURLOPT_SSLCERT, '<Client_Certificate_Path>.pem'); $refProp->setAccessible(false); }

260

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

8.5.5

The Generated PHP Application

The generated project is a PHP Eclipse project that can be presented in any Eclipse perspective. We recommend you use the PHP perspective of the PDT. The project includes PHP proxy files for the selected service and PHP files for the application pages you defined in the wizard. You can run and test the generated application immediately. You can modify and extend the generated code for the PHP starter application to suit your needs. The generated project consists of the following: The application pages (PHP files with the prefix pg_*.php) display the information received from the SAP NetWeaver Gateway service according to the user selections specified in the wizard. index.php: For redirection to the first page of the application. service.php: For initializing the SAP NetWeaver Gateway service proxy class. services folder: Generated proxy class and property labels array for the chosen SAP NetWeaver Gateway service. In addition, there are several utility functions in the proxy_functions.php file. error.php: A page of the application used for displaying error messages. includes folder: Contains the following helper PHP files which are included from the application pages: banner.php: Application name and logo image. footer.php HTML footer. functions.php: A set of PHP functions for authentication, error handling, and entry ID extraction. header.php: HTML header include file. popup_browser_login_dialog.php: Returns 401 and authentication responses to the browser. images folder : Contains images used in the generated application. styles folder: Constains the file, styles.css, a style sheet with user interface styles and themes. js folder: Contains the file, app.js, a JavaScript file for filtering and sorting of HTML table.

Application resources consist of the following folders:

Eclipse project files: .buildpath, .project, and .setting folder.

Related Links

http://www.eclipse.org/projects/project.php?id=tools.pdt Running your PHP Application [page 263] You can run and test the generated PHP application in Eclipse using the PDT plug-in.

8.5.5.1

Runtime User Interface in PHP

This section describes how to setup the runtime user interface for the PHP application. The application maintains a clear separation between the business logic and the runtime user interface themes and styles by using different types of files: PHP, HTML, CSS, and JavaScript. A styelsheet is provided and you can also add your own stylesheet file. The style.css file contains an out-of-thebox theme for your application with predefined colors, images, and positioning for the HTML controls. The banner.php file contains the preset banner area for the application. You can edit the banner as needed. The application pages display the SAP service data using a simple HTML table which you can edit if necessary.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

261

8.5.5.2

HTML Header and Body of the PHP Application Pages

This section describes how to use the HTML header and body of the application pages. The header.php file contains all the necessary elements to construct the HTML page metadata along with the HTML header. In addition, the header.php file includes references to the required JavaScript and CSS files along with the standard <meta> tag for HTML pages. The $title variable is set by each page before including the header.php file. This allows you to set different titles for different pages. The footer.php file contains closing tag element of <body>. You can add your own custom footer if needed.

8.5.5.3
an HTML table.

PHP Client Side Functionality

The app.js Javascript file is responsible for the client-side code that supports filtering and sorting of the list in The app.js Javascript file handles the hovering of each row by: Filtering When the page is loaded, filtering is enabled and all the rows are visible. When you enter a filtering value in the filter textbox, only the rows that match the specified value are displayed in the table. The other rows are not displayed. To display the content of all the rows again, press the ESC key in the filter textbox. The filter method uses the text().search() jQuery method on the row content to find matches and then adds or removes the visible class accordingly Sorting For sorting support, when you click a table column header, the code loops through all the cells of the specific column and then sorts them using the sort() jQuery method. A sort direction is also kept by setting a CSS class accordingly (sorted-asc or sorted-desc). Note that the navigation link to the next page is excluded from filtering and sorting by identifying the column header identifier: <th id="listNavHeader">, and the CSS class for table value: <td class="details"> used in the application list pages. To disable the client-side functionality: Remove (or comment out) the references to the JavaScript files from the header.php file.

8.5.5.4 Service Proxy and Requests Handling for the PHP Application
This section describes the use of the service proxy in the PHP application. The services folder contains a proxy class for the chosen SAP NetWeaver Gateway service, as well as a file containing the labels array of the service property. The proxy code is generated by the OData SDK tool for PHP.

262

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

The service.php file of the generated application is responsible for creating a new instance of this proxy and for passing it the service URL. This file also includes code that adds the credentials which were passed by the browser. For more information, see the Security of the Generated PHP Application section. The code also adds a callback function which is called before any HTTP request is sent by the service proxy. This method adds the request for HTTP headers required by the SAP NetWeaver Gateway server, as SAP client. You can modify the following: The service.php file defines the service URL and SAP client as constants. You can configure the URL address and the SAP client of the SAP service from this file, without modifying the application pages. To use HTTP proxy to access the service, remove the comments in the appropriate code in the service.php file, and define the HTTP proxy server details there. The $proxy variable is used in the generated application pages to access the service data and to fill the tables in the page. You can use the $proxy variable from any application page. Make sure that you include the service.php file in such pages. You can use the proxy for additional service calls. For more information about the OData proxy, refer to the user guide located in the doc folder of the installed OData SDK for PHP.

Related Links

http://www.odataphp.codeplex.com

8.5.6

Running your PHP Application

You can run and test the generated PHP application in Eclipse using the PDT plug-in. To run and test the generated PHP application in Eclipse using the PDT plug-in: Or, Deploy your PHP application project folder to any PHP server and run the application using a web browser (without using the Eclipse). Make sure that the project location (specified in the first page of the wizard) is located in the appropriate folder in the PHP server.

8.5.7

Security of the Generated PHP Application

The generated PHP application supports basic authentication that uses the Browser pop-up dialog for user credentials. Each application page includes the popup_browser_login_dialog.php file, which checks if the request from the browser contains basic authentication credentials (checks for the username). If not, it calls the authenticate method from the functions.php file. The authenticate method tells the browser to open the basic login dialog to allow users to enter their user name and password. The user name and password are not stored in the server. To disable the basic login dialog window:

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

263

Remove (or comment out) the call to the authenticate method, from the popup_browser_login_dialog.php file.

To enable anonymous access to the SAP NetWeaver Gateway service: Remove (or comment out) the call to the proxy credential settings (with the values entered in the login dialog), from the service.php file.

To support X.509 client certificate authentication: Follow the steps described in the PHP Application Support for X.509 Client Certificate Authentication section.

8.5.8 PHP Application Support for Cross Site Request Forgery Protection
Most OData compliant SAP services are protected against Cross-Site Request Forgery (CSRF) attacks. This protection mechanism appends challenge tokens to each request and associates them with each users session. Each token is unique per user session. All SAP services that are compatible with OData library version 1.0 are protected and require X-CSRF tokens. Some services that are compatible with OData library 0.2 also require these tokens. In such services, requests sent using HTTP methods other than GET require X-CSRF tokens. This includes all Create, Update, and Delete (CUD) operations, as well as some service operations (Function-Imports). To handle this, the proxy_functions.php file includes the add_xcsrf_headers and get_xcsrf_data helper functions: The add_xcsrf_headers function adds X-CSRF headers to the given httpRequest object (representing an HTTP POST, PUT, and DELETE request before sending the request. Using the URL passed as an argument, it retrieves the required XCSRF data from the SAP NetWeaver Gateway host. This method creates a new XCSRF header data for each call. The get_xcsrf_data function obtains the X-CSRF data (token and cookie) to set the appropriate X-CSRF headers required for any HTTP POST, PUT, and DELETE request sent to the SAP NetWeaver Gateway host. It uses the URL and user credentials passed as arguments to retrieve the required X-CSRF data from the SAP NetWeaver Gateway host. To support CSRF protection in the generated application: 1. 2. Open the service.php file and locate the addHeadersBeforeRequest function. Uncomment the code for calling the add_xcsrf_headers function: function addHeadersBeforeRequest($httpRequest) { ... /************************************************************************** * For Create/Update/Delete OData requests using X-CSRF token and cookie * (required by ODataLib 1.0 services), uncomment the following code: ****************************************************************************/ //if($httpRequest->getMethod() != HttpVerb::GET) // add_xcsrf_headers(SERVICE_URL, $httpRequest); } Related Links

https://help.sap.com/saphelp_gateway20sp03/helpdata/en/e6/cae27d5e8d4996add4067280c8714e/ frameset.htm

264

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

8.5.8.1 Sending the Service Request with the Client Certificate


This section describes how to send service requests using X.509 client certificate authentication. To send service requests using X.509 client certificate authentication, attach the certificate to any request you send from the service proxy. In addition, enable SSL server validation for all the requests you send. To do so, change the file service.php as follows: 1. 2. Remove the comments before the addClientCertificate method code and the initiate a call to it in the doBeforeRequest method. Replace the <Gateway_CA_Certificate_Path> placeholder in the addClientCertificate method code, with the path of the root CA certificate trusted by the SAP NetWeaver Gateway server saved locally to the PHP application server. Make sure that the certificate is saved in Base64-encoded format. Replace the <Client_Certificate_Path> placeholder in the addClientCertificate method code with the path of the stored X.509 client certificate generated for the user. Make sure the certificate is saved in PEM format. Remove (or comment out) the call to the proxy credential settings (with the values entered in the login dialog). If you need to disable the basic login dialog window used for authentication in the PHP application server, remove(or comment out) the call to the authenticate method in the popup_browser_login_dialog.php file.

3. 4. 5.

8.5.8.2

Generation and Signing of X.509 Client Certificates

How to generate and sign X.509 Client Certificates. You can generate and sign X.509 client certificates dynamically for a specific user using OpenSSL or other APIs that enable creating and signing of certificates in PHP. Related Links

http://www.php.net/manual/en/function.openssl-csr-new.php

8.5.9

Custom PHP Template Creation

You can create a new PHP template to be used in the framework. The new template is based on the appropriate pattern and environment of theToolkit for PHP (GWPA) in the framework. Prerequisites Make sure that you have: A plug-in project in which you will include your new PHP template. Added the correct plug-in dependency for the Toolkit for PHP (GWPA), com.sap.odata.dt.cons.toolkit.php. Followed the Implementing a New Template section in the OData Development Productivity Accelerator guide (GWDTE Framework), to create a new Template class and define an appropriate Starter Application Template extension that your plugin will provide.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

265

Make sure to specify in the extension element the correct environment identifier attribute for the Toolkit for PHP (GWPA): com.sap.odata.dt.environment.php. You should also specify in the extension element, the specific application pattern you want to use. You can use the patterns provided with the framework or create your own. Custom PHP Template Class Implementation The created template class receives the instances of the appropriate Pattern and Environment classes that were defined in the template extension of your plugin from the framework in runtime (using the setContext method). For PHP templates, the received environment class implements the com.sap.iw.gw.oc.eclipse.environment.php.IPHPEnvironment interface. The interfaces methods enable access to the PHP environment parameters that have been defined by the user in the first wizard page (such as the selected project name and location). In addition, the interface provides some methods for creating an empty PHP project, for generating PHP proxy files, and for using the PHP perspective. You can use the IPHPEnvironment interface methods in your custom template class, for performing your custom code generation in the onFinish method implementation. You can also use the received Pattern class methods for accessing the user selections in the wizard pages created by the template. The usage of the Pattern class differs according to the specific Pattern you chose to use in the template extension of your plugin. The following is sample code for implementing the onFinish method for your new template class, and for using the IPHPEnvironment interface methods. The example is based on the assumption that the template extension element defined the Exploration Pattern Identifier com.sap.odata.dt.pattern.exploration as the selected pattern (this pattern adds a page to the Starter Application wizard which enables the user to select a service for the application). The code sample below shows how to generate a new PHP project including proxy files of a selected service, and a reference to the OData for PHP library: @Override public void onFinish(IProgressMonitor monitor) throws TemplateException { monitor.beginTask("Generating Custom Application with PHP proxy ...", 5); IServiceModel serviceModel = (IServiceModel) this.context.get(TemplateConstants.PATTERN); IPHPEnvironment phpEnvironment = (IPHPEnvironment) this.context.get(TemplateConstants.ENVIRONMENT); String projectName = phpEnvironment.getProjectName(); // Create an empty PHP project with the OData for PHP library reference, // in the location specified by the user in the wizard String projectHomePath = null; try { projectHomePath = phpEnvironment.createEmptyPHPProject(); } catch (EnvironmentException e) { throw new TemplateException(e); } monitor.worked(1); // Generate service proxy files and property labels resource files, // and add them to the empty project try { phpEnvironment.generatePHPProxy(serviceModel, projectHomePath);

266

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

} catch (EnvironmentException e) { throw new TemplateException(e); } monitor.worked(2); // Refresh the created project in Eclipse with the added files try { ProjectUtils.refreshProject(projectName); } catch (CoreException e) { throw new TemplateException(e); } monitor.worked(1); // Switch to PHP perspective phpEnvironment.openPHPPerspective(); monitor.worked(1); System.out.println("Successfully generated proxy into project " + projectName); monitor.done();

8.5.10 Troubleshooting for the Toolkit for PHP (GWPA)


This section describes the known issues of the Toolkit for PHP (GWPA). PHP Duplicated Class Error Issue: When running the generated PHP application or any code which uses the generated PHP proxy, a PHP 'Duplicated Class' error is received. This may happen because the name of the specified SAP service is the same as one of its entity types (ignoring case), which causes generation of two PHP classes with the same name. Solution: In the generated PHP proxy file (located at: services/<service_name>.php), rename the service class to a unique name (for example, add '_SERVICE' to the class name). You will also need to update all the references to the service class in the code to this new class name. In the generated PHP application, there is such a reference only in the service.php file (for initializing the proxy).

Note
Renaming the entity type class is not recommended since it may break the generated proxy code. Generated Class Names or Variable Names are Reserved for PHP Issue: The selected SAP service may contain entity, collection, service, or property names that are reserved words in the PHP programming language such as. 'return', or contain illegal characters such as '*. Solution:

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

267

Open the generated class file (PHP proxy file), for example, .../services/<service_name>.php, and rename all the class and variable names which are illegal in PHP. Then, update all the references to such items within the proxy and the application code. Proxy Generation Failed Issue: When generating a PHP application or proxy, the generation fails and the Eclipse Error Log shows a 'Proxy Generation Failed' error message. Solution: Make sure the OData SDK for PHP is installed and configured as instructed in the 'Installation and Configuration' section of its user guide, located at the "doc/User_Guide.htm" file of the downloaded SDK. On Mac machines, also follow the instructions below: 1. 2. In the OData SDK for PHP code, change all the '\' character occurrences to the '/' character in the 'require_once' block of the "Common/ACSUtil.php" file. Make sure the OData SDK for PHP is configured in the php.ini file on your local PHP server as follows: include_path = "<PHP_Libraries_Include_Path>:/<OData_SDK_Path>" ;OData SDK for PHP Library Path ODataphp_path = "/<OData_SDK_Path>" extension=curl.co extension=xsl.co ;Defines the default timezone used by the date functions date.timezone = <Local_Timezone_As_In: http://www.php.net/manual/en/ timezones.php> 3. Regenerate the PHP proxy/starter application.

Generating proxy fails if metadata includes text in languages other than English Issue: When a metadata document includes text in languages that contain non-English characters, the Toolkit for PHP (GWPA) fails to generate the proxy and displays the following error: "Warning: DOMDocument::Load(): Input is not proper UTF-8, indicate encoding !" Solution: Follow the instructions in the Language Support section and regenerate the PHP proxy/starter application. PHP Runtime Issues Missing Files in Linux or Mac Operating Systems Issue: The following is an example of a PHP error that occurs at runtime in the UNIX/LINUX or Mac server machine: Warning: require_once(Resource\Messages.php) [function.require-once]: failed to open stream: No such file or directory in /Applications/XAMPP/xamppfiles/htdocs/ odataphp/Common/ACSUtil.php on line 17 Fatal error: require_once() [function.require]: Failed opening required 'Resource \Messages.php' (include_path='.:/Applications/XAMPP/xamppfiles/lib/php:/ Applications/XAMPP/xamppfiles/lib/php/pear:/Applications/XAMPP/xamppfiles/htdocs/ odataphp/') in/Applications/XAMPP/xamppfiles/htdocs/odataphp/Common/ACSUtil.php on line 17

268

2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

The error indicates missing files that are required by the file, <OData_SDK_Path>/ Common/ACSUtil.php Solution: Open the OData SDK for PHP code, and change all occurrences of the character '\' character to the '/' character in the 'require_once' block in the file, .../Common/ACSUtil.php Related Links

http://odataphp.codeplex.com/workitem/11143

SAP NetWeaver Gateway Productivity Accelerator: Development Guide Service Consumption

2013 SAP AG or an SAP affiliate company. All rights reserved.

269

www.sap.com/contactsap

2013 SAP AG or an SAP affiliate company. All rights reserved.

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. National product specifications may vary. 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. SAP 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. Please see http://www.sap.com/corporate-en/legal/copyright/ index.epx for additional trademark information and notices.