574
Technical Documentation PUBLIC SAP HANA Cloud Document Version: 1.6.0 - 2013-06-18 SAP HANA Cloud Platform

Hana Cloud

  • Upload
    visinna

  • View
    306

  • Download
    6

Embed Size (px)

Citation preview

Page 1: Hana Cloud

Technical Documentation PUBLIC

SAP HANA CloudDocument Version: 1.6.0 - 2013-06-18

SAP HANA Cloud Platform

Page 2: Hana Cloud

Table of Contents1 SAP HANA Cloud. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .31.1 Product Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

1.1.1 Runtime for Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.1.2 Services. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91.1.3 UI Development Toolkit for HTML5 (SAPUI5). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191.1.4 Product Restrictions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

1.2 Getting Started. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221.2.1 Signing Up for an Account. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231.2.2 Setting Up the Tools and SDK. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271.2.3 Updating the Tools and SDK. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341.2.4 Creating a HelloWorld Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361.2.5 Creating a HelloWorld Application with SAPUI5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .411.2.6 Samples. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421.2.7 Tutorials. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

1.3 Developer's Guide. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491.3.1 SAP HANA Cloud Cockpit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .501.3.2 Development Environment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561.3.3 Developing Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631.3.4 UI Development with SAPUI5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 691.3.5 Consuming the Connectivity Service. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3031.3.6 Consuming the Persistence Service. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4101.3.7 Consuming the Document Service. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4731.3.8 Securing Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4861.3.9 Deploying Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5321.3.10 Profiling Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5461.3.11 Logging in Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5501.3.12 Monitoring Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 558

1.4 Glossary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571

2P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformTable of Contents

Page 3: Hana Cloud

1 SAP HANA Cloud

Getting Started

Set up your environment and start developing applications

Development Environment

Use our standards-based development environment

Connectivity Service

Provide seamless integration with SAP and other systems via our connectivity service

Persistence Service

Provide relational persistence with JPA and JDBC via our persistence service

Document Service

Use our scalable document service for managing unstructured data

Identity Service

Delegate identity and authorization management to the identity service

UI Development Toolkit for HTML5 (SAPUI5)

Use the user interface technology to build and adapt client applications based on SAP HANA Cloud

Cockpit

Manage your applications remotely using SAP HANA Cloud Cockpit

Monitoring and Alerting

Configure checks and monitor the state of your applications

Release Notes

Check what is new and what has changed since the last release

1.1 Product Overview

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 3

Page 4: Hana Cloud

What is SAP HANA Cloud

SAP HANA Cloud is the Platform-as-a-Service (PaaS) offering from SAP, which enables SAP partners and customers to develop, deploy and use Java applications in a cloud environment.

SAP HANA Cloud is an open-standards, Eclipse-based, module software development kit. It is certified at the latest industry cloud standards and operated by SAP. The platform supports the complete lifecycle of building and deploying cloud-based enterprise business applications, extensions, and services.

SAP HANA Cloud also facilitates integration scenarios with your on-premise SAP software.

Features

SAP HANA Cloud offers the following platform capabilities for application development and consumption:

● Development EnvironmentThe development process is enabled by the SAP HANA Cloud Tools, which comprise the SAP HANA Cloud Tools for Java and the SAP HANA Cloud SDK.For more information, see Development Environment [page 56].

● RuntimeThe SAP HANA Cloud Runtime for Java comprises components which create the environment for deploying and running applications on the platform.For more information, see SAP HANA Cloud Runtime for Java.

● Platform ServicesSAP HANA Cloud provides a rich set of services and APIs.For more information, see Services [page 9].

● UI development toolkit for HTML5This is a user interface technology that is used to build and adapt client applications based on SAP HANA Cloud. The runtime is a client-side HTML5 rendering library with a large set of RIA-like standard and extension controls based on JavaScript (JS), and a lightweight programming model. The rendering control library is Open AJAX-compliant and based on open source jQuery and can be used together with other client-side libraries.For more information, see UI Development Toolkit for HTML5 (SAPUI5) [page 19].

Related Information

SAP HANA Cloud Developer Center

SAP HANA Cloud Applications Partner Center

1.1.1 Runtime for Java

The SAP HANA Cloud Runtime for Java comprises the components which create the environment for provisioning and running applications on SAP HANA Cloud. The runtime is represented by Java Virtual Machine, Application

4P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 5: Hana Cloud

Runtime Container and Compute Units. Cloud applications can interact at runtime with the containers and services via the platform APIs.

Components

● Java Virtual MachineSAP HANA Cloud infrastructure runs on SAP's own implementation of a Java Virtual Machine - SAP Java Virtual Machine (JVM). SAP JVM is a fully certified Java Standard Edition Virtual Machine for Java 6 and 7. It is derived from Oracle’s HotSpot VM and JDK implementation, but enhanced with several supportability features.

● Application Runtime ContainerApplications developed on SAP HANA Cloud run on a modular and lightweight runtime container which allows them to consume standard Java EE APIs and platform services that are centrally provided and shared across the platform. SAP HANA Cloud leverages open source as a key element and Java EE 6 Web Profile as a default programming model.

● Compute UnitsA Compute Unit is a virtualized hardware on which a SAP HANA Cloud application runs.

Related LinksJava Virtual Machine [page 6]Application Runtime Container [page 7]Compute Units [page 9]Supported APIs [page 58]

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 5

Page 6: Hana Cloud

1.1.1.1 Java Virtual Machine

SAP HANA Cloud infrastructure runs on SAP's own implementation of a Java Virtual Machine - SAP Java Virtual Machine (JVM).

SAP JVM is a fully certified Java Standard Edition Virtual Machine for Java 6 and 7. It is derived from Oracle’s HotSpot VM and JDK implementation, but enhanced with several supportability features such as the SAP JVM Profiler for better monitoring, and profiling applications running on the SAP HANA Cloud local runtime. Customer support is provided directly by SAP for the full maintenance period of SAP applications that use the SAP JVM.

SAP JVM

The SAP JVM is a standard compliant certified JDK, supplemented by additional supportability and developer features and extensive monitoring and tracing information. All these features are designed as interactive, on-demand facilities of the JVM with minimal performance impact. They can be switched on and off without having to restart the JVM (or the application server that uses the JVM).

Supportability and Developer Features

Debugging on Demand

With SAP JVM debugging on demand, Java developers can activate and deactivate Java debugging directly – there is no need to start the SAP JVM (or the application server on top of it) in a special mode. Java debugging in the SAP JVM can be activated and deactivated using the jvmmon tool, which is part of the SAP JVM delivery. This feature does not lower performance if debugging is turned off. The SAP JVM JDK is delivered with full source code providing debugging information, making Java debugging even more convenient.

Profiling

To address the root cause of all performance and memory problems, the SAP JVM comes with the SAP JVM Profiler, a powerful tool that supports the developer in identifying runtime bottlenecks and reducing the memory footprint. Profiling can be enabled on-demand without VM configuration changes and works reliably even for very large Java applications.

The user interface – the SAP JVM Profiler – can be easily integrated into any Eclipse-based environment by using the established plugin installation system of the Eclipse platform. It allows you to connect to a running SAP JVM and analyze collected profiling data in a graphical manner. The profiler plug-in provides a new perspective similar to the debug and Java perspective.

A number of profiling traces can be enabled or disabled at any point in time, resulting in snapshots of profiling information for the exact points of interest. The SAP JVM Profiler helps with the analysis of this information and provides views of the collected data with comprehensive filtering and navigation facilities.

6P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 7: Hana Cloud

The profiling traces provided address the following use cases:

● Memory Allocation Analysis – investigates the memory consumption of your Java application and finds allocation hotspots

● Performance Analysis – investigates the runtime performance of your application and finds expensive Java methods

● Network Trace - analyzes the network traffic● File I/O Trace - provides information about file operations● Synchronization Trace - detects sychronization issues within your application● Method Parameter Trace – yields detailed information about individual method calls including parameter

values and invocation counts● Profiling Lifecycle Information – a lightweight monitoring trace for memory consumption, CPU load, and GC

events.

Extensive Monitoring and Tracing Information

The SAP JVM provides comprehensive statistics about threads, memory consumption, garbage collection, and I/O activities. For solving issues with SAP JVM, a number of traces may be enabled on demand. They provide additional information and insight into integral VM parts such as the class loading system, the garbage collection algorithms, and I/O. The traces in the SAP JVM can be switched on and off using the jvmmon tool, which is part of the SAP JVM delivery.

Further Information

Critical Java exceptions (such as NullPointerException, ClassCastException, NoClassDefFoundError, or OutOfMemoryError) provide additional information and further details to help identify the reason for an exception.

Thread dumps not only contain a Java execution stack trace, but also information about monitors or locks, consumed CPU and memory resources, I/O activities, and a description of communication partners (in the case of network communication).

1.1.1.2 Application Runtime Container

SAP HANA Cloud applications run on a modular and lightweight Application Runtime Container where they can use the platform services APIs and Java EE APIs according to standard patterns. SAP HANA Cloud is Java EE 6 Web Profile certified. The lightweight Web Profile of Java EE 6 is targeted at next-generation Web applications. Developers benefit from productivity improvements with more annotations and less XML configuration, more Plain Old Java Objects (POJOs), and simplified packaging.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 7

Page 8: Hana Cloud

Reference

The Java EE 6 Web Profile is a minimal specification which incorporates the following Java Specification Requests (JSRs):

Specification version JSR

Java EE 6 (Web Profile) JSR - 316

Servlet 3.0 JSR - 315

JavaServer Pages (JSP) 2.2 JSR - 245

Expression Language (EL) 2.2 JSR - 245

Debugging Support for Other Languages 1.0 JSR - 45

Standard Tag Library for JavaServer Pages (JSTL) 1.2 JSR - 52

JavaServer Faces (JSF) 2.0 JSR - 314

Common Annotations for Java Platform 1.1 JSR - 250

Enterprise JavaBeans (EJB) Lite 3.1 JSR - 318

Java Transaction API (JTA) 1.1 JSR - 907

Java Persistence API (JPA) 2.0 JSR - 317

Dependency Injection for Java 1.0 JSR - 330

Contexts and Dependency Injection for Java EE platform 1.0 JSR - 299

Bean Validation 1.0 JSR - 303

Managed Beans 1.0 JSR - 316

Interceptors 1.1 JSR - 318

Source: JSR-316 (Web Profile), Chapter 2: Web Profile Definition

For more information about the differences between EJB 3.1 and EJB 3.1 Lite, see the Java EE 6 specification, JSR 318: Enterprise JavaBeans, section 21.1.

Development Process

The Java EE 6 Web Profile enables you to easily create your applications for SAP HANA Cloud.

For more information, see Using Java EE 6 Web Profile [page 65].

Related Information

Java EE at a Glance

8P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 9: Hana Cloud

1.1.1.3 Compute Units

A Compute Unit is the virtualized hardware resources used by an SAP HANA Cloud application.

After being deployed to the cloud, the application is hosted on a compute unit with certain central processing unit (CPU), main memory, disk space and an installed OS.

Compute Unit Sizes

SAP HANA Cloud offers four standard sizes of compute units according to the provided resources.

Depending on their needs, customers can choose from the following compute unit configurations:

Compute Unit Configuration

Lite edition 1 CPU Core; 2048 MB Main memory

Professional edition 2 CPU Cores; 4096 MB Main memory

Premium edition 4 CPU Cores; 8192 MB Main memory

Premium Plus edition 8 CPU Cores; 16384 MB Main memory

For developer accounts, only the Lite edition is available.

For customer accounts, all sizes of compute units are available. During deployment, customers can specify the compute unit on which they want their application to run.

For more information, see Deploy [page 539].

1.1.2 Services

Overview

SAP HANA Cloud provides the following services:

Service Description

Connectivity Service SAP HANA Cloud connectivity service provides a secure, reliable and easy-to-consume access to business systems, running either on-premise or in a cloud. SAP HANA Cloud provides a trusted channel to your business systems, while at the same time your IT has complete control and auditability of what is technically exposed to the on-demand world.

Persistence Service SAP HANA Cloud persistence service provides relational persistence. The main way for accessing it is using JPA (Java

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 9

Page 10: Hana Cloud

Service Description

Persistence API). However JDBC (Java Database Connectivity) is also supported. All maintenance activities, such as data replication, backup and recovery, are handled by the platform.

Document Service SAP HANA Cloud document service provides a content repository for unstructured or semi-structured content. Applications access it using the OASIS standard protocol Content Management Interoperability Services (CMIS). The applications consume the service using the provided client library.

Identity Service SAP HANA Cloud identity service is responsible for identity management and authentication on SAP HANA Cloud. It also enables Single Sign-On (SSO) between applications running on SAP HANA Cloud, based on the Security Assertion Markup Language (SAML) 2.0. It has already more than 2.5 million users which could access applications hosted on SAP HANA Cloud.

NoteApplications using features or services in beta state cannot be deployed to productive SAP HANA Cloud accounts. Beta features and services can be tested with the free developer account, which you can request on http://hanatrial.ondemand.com.

1.1.2.1 Connectivity Service

Overview

SAP HANA Cloud connectivity service allows a secure, reliable, and easy-to-consume access to remote services running either on the Internet or in an on-premise network. This service:

● Consists of a Java API that application developers can use to consume remote services.● Allows account-specific configuration of application connections via HTTP and Mail destinations.● Offers a technical connectivity solution, which can be used to establish a secure tunnel from the customer

network to an on-demand application in SAP HANA Cloud. At the same time, the customer IT department has full control and auditability of what is technically exposed to the on-demand world.

● Allows you to make connections to both Java and ABAP on-premise systems.

Use SAP HANA Cloud connectivity service for the following scenarios:

● Consume a service from the Internet. More information: Tutorial: Using Internet Services in Cloud Applications [page 358]

10P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 11: Hana Cloud

● Make connections between Web applications and on-premise backend services via HTTP protocol. More information: Tutorial: Using On-Premise Back-End Services in Cloud Applications [page 364]

● Make connections between Web applications and on-premise backend services via RFC protocol. More information: Tutorial: Invoking ABAP Function Modules in On-Premise ABAP Systems [page 384]

● Establish connections from on-premise systems to SAP HANA Cloud, using the Cloud connector. More information: Using the Cloud Connector [page 319]

● Send and fetch e-mails. More information: Sending and Fetching E-Mail [page 391]

General Internet Connectivity On-Demand to On-Premise Connectivity

Sending and Fetching E-Mail

A company that uses SAP HANA Cloud has been granted an account on the platform to which only authorized users of the company have access. The company can subscribe applications to its account or deploy its own applications, and those applications can then be used in this account. The administrator of the Cloud connector can set up a secure tunnel from the customer network to his or her account. The platform ensures that the tunnel can be only used by the account applications. This means that applications of other accounts have no access to the tunnel. The tunnel itself is encrypted via transport layer security so that connection privacy can be guaranteed.

Features

The Connectivity service supports the following protocols as well as the relevant scenarios:

● HTTP Protocol - this protocol enables you to exchange data between your on-demand application and on-premise systems or internet services. For this aim, you can create and configure HTTP destinations to make

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 11

Page 12: Hana Cloud

the needed Web connections. For on-premise connectivity, you can reach backend systems using the Cloud Connector via HTTP.

● Mail Protocols - the SMTP protocol allows you to send electronic mail messages from your Web applications using e-mail providers that are accessible on the Internet, such as Google Mail (Gmail). The IMAP and POP3 allow you to retrieve e-mails from the mailbox of your e-mail account. Applications use the standard javax.mail API. The e-mail provider and e-mail account are configured using mail destinations.

● RFC Protocol - this protocol enables you to invoke ABAP function modules. You can create and configure RFC destinations as well as make connections to back-end systems using the Cloud connector via RFC.

Restrictions

To check all connectivity restrictions, go to Product Restrictions [page 20] → section "SAP Hana Cloud Connectivity Service".

Related LinksConsuming the Connectivity Service [page 303]Using the Cloud Connector [page 319]Sending and Fetching E-Mail [page 391]

1.1.2.2 Persistence Service

Overview

The SAP HANA Cloud persistence service provides persistence in a relational database for applications that are hosted on the SAP HANA Cloud platform. Each application is assigned a default schema in which tables can be created and data stored. The persistence service handles not only the JDBC connection parameters, such as URLs, drivers, and users, but also performs other tasks such as backup and recovery, load balancing, and scaling.

Applications can access the storage using JPA (Java Persistence API) or JDBC (Java Database Connectivity). The recommended programming model is JPA 2.0 with EclipseLink as the persistence provider, since it provides a higher level of abstraction and is geared towards application development. Plain JDBC is, however, also supported.

A high-level overview of the persistence service is shown below:

12P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 13: Hana Cloud

Features

The persistence service provides the following:

● Dedicated database user and schema per applicationWhen an application is deployed within the SAP HANA Cloud landscape, the persistence service automatically creates a dedicated database user and schema on one of the database instances within the persistence service database pool. It generates the credentials (URL, unique user name, and unique password) needed to create the default data source containing the JDBC connection pool.

● Application redeployment with the same schemaThe dedicated schema and tables are identified by the account name and application name used when the application was deployed. A redeployed application can reuse the schema with its associated database objects and data if the names for account and application are the same as previously used.

● Application isolation in the cloudBy providing each application with its own database user and schema, the persistence service ensures strict application isolation in the cloud.

● Choice of database platformThe databases currently used on the Cloud platform are the SAP HANA database and SAP MaxDB. At present, only one database type can be selected per account.

● Local test facility

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 13

Page 14: Hana Cloud

A lightweight Apache Derby database is provided as part of the SDK for local development, allowing you to both develop and test in a local environment. When running on the SAP HANA Cloud local runtime, the persistence service automatically enables an embedded Derby instance and configures the default data source accordingly. Note that you can reconfigure the persistence service to replace the standard database with a database of your choice.

Restrictions

When consuming the SAP HANA Cloud persistence service in your applications, you have to be aware of the following restrictions:

● No database abstractionThe persistence service does not provide database abstraction for the supported database types (SAP MaxDB and the SAP HANA database). Applications must be aware of the type of database they use and must be written, if necessary, in a database-specific way.

● No automatic life cycle management for database objectsThe persistence service does not provide automatic life cycle management for database objects, such as tables, indices, sequences, and so on. It is the responsibility of the application to create the necessary database objects, either by using JDBC to send the corresponding data definition statements to the database or by using the schema creation capabilities of EclipseLink. Due to limitations of the EclipseLink schema creation feature, changes to the schema, like altering a table definition, need to be done by the application. Alternatively, open source tools for database schema management (like Liquibase) can be used for life cycle management for database objects, but must be bundled with the application.

● No external access to the databaseAt present, the database can only be accessed from within the application using JDBC (or JPA). It is therefore not possible to use external data administration tools, such as the SAP HANA studio, to manage the application data.

● Restrictions with the SAP HANA database

○ An application using the SAP HANA database is automatically assigned a schema and a (technical) user in the SAP HANA database. All communication from the application to the SAP HANA database is done on behalf of this technical user, which can neither be accessed nor changed by the application. The technical user has only the lowest privileges (the default PUBLIC role). For example, it cannot create HANA users or HANA roles in the SAP HANA database.

○ Since the SAP HANA studio cannot be used to connect to the SAP HANA database used by the persistence service, all database entities, such as tables and stored procedures (SQLScript), need to be created from within the application by manually sending the corresponding data definition statements via JDBC to the SAP HANA database.

○ SAP HANA XS is not supported.

Related LinksConsuming the Persistence Service [page 410]

14P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 15: Hana Cloud

1.1.2.3 Document Service

Overview

The SAP HANA Cloud document service provides an on-demand content repository for unstructured or semi-structured content. Applications access it using the OASIS standard protocol Content Management Interoperability Services (CMIS). Applications running on SAP HANA Cloud can easily consume the document service using the provided client library. Since the document service is exposed using a standard protocol, it can also be consumed by any other technology that supports the CMIS protocol.

Deployment in the Cloud

Applications using the SAP HANA Cloud document service can be developed offline, without access to the SAP HANA Cloud. The API that is needed to connect to the repository, and the SAP HANA Cloud SDK include the local document service, which can be connected to a local persistence.

Features

The document service is an implementation of the CMIS standard and is the primary interface to a reliable and safe store for content in SAP HANA Cloud.

Features of the document service are for example:

● Storage and retrieval of files (on traditional platforms often handled by the file system)● Organization of files in a hierarchical structure of folders● Association of metadata along with the content and the ability to read and write them● Query interface based on these metadata by using a query language similar to SQL● Managing access control (Access Control Lists)● Versioning of content● Powerful Java API (Apache Chemistry OpenCMIS)● Streaming support so that even large files can be handled efficiently● Encryption and compression of content on disk● Access from applications running internally in SAP HANA Cloud or externally

The following figure illustrates the document services architecture:

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 15

Page 16: Hana Cloud

The CMIS standard defines:

● A domain model and service bindings that can be used by applications to work with a Content Management repository

● An abstraction layer for controlling diverse document management systems and repositories using Web protocols

CMIS provides a common data model covering typed files and folders with generic properties that can be set or read. There is a set of services for adding and retrieving documents ('objects'). It defines an access control system, a checkout and version control facility, and the ability to define generic relations. Two protocol bindings are defined, one using WSDL and SOAP and another using Representational State Transfer (REST), using the Atom convention.

The consumption of CMIS-enabled document repositories is easy using the Apache Chemistry libraries. Apache Chemistry provides libraries for several platforms to consume CMIS using Java, PHP, .Net, or Python. The subproject OpenCMIS, which includes the CMIS Java implementation, also includes tools around CMIS, like the CMIS Workbench, which is a desktop client for CMIS repositories for developers.

Since the SAP HANA Cloud document service API includes the OpenCMIS Java library, applications can be built on SAP HANA Cloud that are independent of a specific content repository.

16P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 17: Hana Cloud

Related LinksUsing the Document Service in a Web Application [page 482]http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=cmishttp://docs.oasis-open.org/cmis/CMIS/v1.0/os/cmis-spec-v1.0.htmlhttp://chemistry.apache.org/

1.1.2.4 Identity Service

Overview

SAP HANA Cloud identity service is the default identity provider (IdP) used by SAP HANA Cloud for Security Assertion Markup Language (SAML) 2.0 authentication. This protocol provides reliable standards-based authentication and single sign-on (SSO).

NoteIf you want to use your custom IdP, you can configure trust to it using the SAP HANA Cloud cockpit. For more information, see Using a Custom Identity Provider [page 487]

SAP ID service provides an easy way for your applications to delegate authentication and identity management and keep your developers focused on the business logic. It allows authentication decisions to be removed from the application and handled in a central service that consists of the following main components:

● A central user store for all your identities that require access to protected resources of your application(s)● A standards-based Single Sign-On (SSO) service that enables users to log on only once and get seamless

access to all your applications deployed using SAP HANA Cloud

In addition to being the central storage location for all your application user data, the SAP ID service is also the place where developers or administrators within your organization have to register to get access to the cockpit or be able to deploy applications to the cloud.

All existing SAP Community Network users, SAP Service Marketplace users, and SAP employees can start to use the SAP ID service right away for central authentication in SAP HANA Cloud. New users can register on the self-service registration page.

How It Works

The diagram below shows how the SAP ID service is integrated into the authentication process of a user accessing a protected resource in your application. Depending on your requirements, the SAP ID service can be configured in your application for browser-based HTTP authentication (Basic Authentication), form-based authentication, or SAML-based SSO.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 17

Page 18: Hana Cloud

1. User requests resource.2. User is redirected to Identity Provider.3. Response artifact is returned.4. Signed assertion is POST-ed.5. SAP HANA Cloud responds with resource to the user.

Single Sign-On with the SAP ID Service

The SAP ID service supports version 2 of the Security Assertion Markup Language (SAML) to provide SSO across all your applications deployed in the SAP HANA Cloud. SAML 2 is a widely adopted standard in the industry that was defined by the Organization for the Advancement of Structured Information (OASIS). Setting up SSO with SAML in your application essentially assigns the SAP ID service the role of the SAML Identity Provider (IdP). Upon

18P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 19: Hana Cloud

request from your application, the SAP ID service IdP authenticates the user if he or she is not already signed on. If the user entered valid credentials, the IdP confirms to your application that the user did authenticate with the IdP at a particular time using a particular authentication method.

How can I use it?

To develop an application that delegates authentication and identity management to the SAP ID service, you can choose from the following options:

● Declarative authentication - enables resource protection as defined by the Java EE servlet API● Programmatic authentication - enables resource protection handled by the application● Programmatic logout - enables explicit logout within applications from a logout button or link● Getting specific user attributes

For more information, see Securing Applications [page 486].

1.1.3 UI Development Toolkit for HTML5 (SAPUI5)

Overview

The SAPUI5 runtime is a client-side HTML5 rendering library with a rich set of standard and extension controls and a lightweight programming model. The client-side rendering library provides a rich set of controls. You can extend these controls as well as develop new custom controls. To support you in developing applications, SAPUI5 tools come with a set of eclipse-based wizards and editors. They provide wizards to create application projects and views according to the Model View Controller concept and other features like JavaScript code completion, templates, snippets, and in-place application preview. SAPUI5 provides many features to enable you to easily create and extend state-of-the-art user interfaces:

● It supports RIA-like client-side features based on JavaScript● It supports CSS3, which allows you to adapt themes to your company’s branding in an effective manner.● It is based on an extensibility concept regarding custom controls.● It uses the open source jQuery library as a foundation● It fully supports SAP product standards.● It complies to OpenAjax and can be used together with standard JavaScript libraries.

SAPUI5 SDK

The SDK - also called Demo Kit - provides the following sections:

● Developer Guide with important information about the programming languages, open source technologies, development tools and APIs

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 19

Page 20: Hana Cloud

● Controls containing active demos examples with descriptions and source codes.● API Reference with JavaScript documentation of Framework and Control API● Test Suite that shows all controls running with different property settings where you can interactively adapt

the controls you use for your test purpose.

To directly access the Demo Kit: https://sapui5.hana.ondemand.com/sdk/

Restrictions

SAPUI5 control sap.ui.richtexteditor.RichTextEditor

The RichTextEditor contains a third party component TinyMCE provided by Moxiecode Systems AB. The SAP license agreement does not cover development of own applications with RichTextEditor of SAPUI5. To develop own applications with RichTextEditor of SAPUI5 a customer or partner has to first obtain an appropriate license from Moxiecode Systems AB. To prevent accidental usage, the TinyMCE code cannot be used directly.

1.1.4 Product Restrictions

General Constraints

● Upload limit: an application being deployed on SAP HANA Cloud cannot be bigger than 1.5 GB. If the application is packaged as a WAR file, the size of the unzipped content is taken into account.

● SAP HANA Cloud has Java SE 6 and Java SE 7 Hotspot compatible JVM and supports bytecode compiled in Java SE 6 and Java SE 7 Hotspot format.

● To be able to deploy your application in a customer account, you have to use SAP HANA Cloud Tools version 0.24.4.3 or higher.

● Currently supported platform languages: English.

NoteYou can find the restrictions related to each SAP HANA Cloud service in the respective service documentation.

For more information, see Services.

Browser Support

Supported Browsers

For Windows:

20P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 21: Hana Cloud

● Internet Explorer 9 and higher● Mozilla Firefox 10 (Firefox Extended Support Release - ESR) and latest version● Chrome latest version

For MAC OS X:

● Safari 5.1 and higher

Browsers with restricted support

● Internet Explorer 8: there are degradations in visual design and over time also restricted functionality.

Browsers which are not supported

● Internet Explorer 6 and 7 and in general all browsers not mentioned above.

For more information about browser support in SAP HANA Cloud, see Browser Support: SAPUI5 for Desktop [page 71].

Development Platform Support for SAP HANA Cloud Tools and SDK

● SAP HANA Cloud Tools for Java and SDK have been tested on Windows 7 (64 bit) with Java Standard Edition 6 (Java SE 6)

● SAP HANA Cloud Tools for Java and SDK run fine in many operating environments with Java SE 6 and Java SE 7 that are supported by Eclipse. However, we do not systematically test all platforms.

● SAP HANA Cloud Tools for Java must be installed on Eclipse IDE with platform version Indigo Service Release 1 or higher. Note that the support for Indigo has entered end of maintenance. Indigo update site is still operational but no updates will be made. We recommend that you use Eclipse Juno 4.2 Service Release 2.

● For JCo-enabled applications, the SDK local runtime needs to be hosted by a 64-bit JVM.

Connectivity Service

● SAP HANA Cloud connector installation requires an operating system SUSE Linux 11 SP1 or SP2. For more information, see Installing the Cloud Connector [page 320] → the "Prerequisites" section.

● For the on-demand to on-premise connectivity scenario, HTTP(S) is currently the only supported protocol and the HTTP Destination API must be used to make calls through the SAP HANA Cloud connector.

● Each SAP HANA Cloud account can be connected to one SAP HANA Cloud connector only. A single SAP HANA Cloud connector can expose an arbitrary number of back-end systems.

● For Internet connectivity scenarios, you can use any HTTP clients, as the usage of HTTP Destinations is just an option. The HTTP proxy used in SAP HANA Cloud is set on JVM level.

● For Internet connections, you are allowed to use the following ports in URLs: 1080; 1443; 21000; 44300; 44305; 50000; 50001; 50013; 50900; 51000; 8081; 8101; 8111; 8443; 9013.For on-demand to on-premise solutions there are no port limitations.

● If a destination configuration consists of a key store or trust store, it must be stored in JKS files with a standard .jks extension.

● To develop a JCo application, your SDK version needs to be at least 1.29.18. Also, your SDK local runtime needs to be hosted by a 64-bit JVM.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 21

Page 22: Hana Cloud

On Windows platforms, you need to install Microsoft Visual C++ 2010 Redistributable Package (x64). To download this package, go to http://www.microsoft.com/en-us/download/details.aspx?id=14632.

● To provide connectivity tunnel via RFC destinations, your Cloud connector version needs to be at least 1.3.0.● You cannot communicate with an e-mail provider via an unencrypted SMTP protocol on port 25.● Fetched e-mail is not scanned for viruses.

Document Service

The following features, which are defined in the OASIS CMIS standard, are supported with restrictions:

● Versioning: Only major versions are supported● Versioning: No support for check-in comments● Query: Only metadata searches, no joins and no type aliases● getContentStream: Offset and length not yet supported

The following CMIS features are not yet supported:

● Multifiling● Policies● Relationships● Change logs

There is a limit for the properties of a document:

● For searchable properties, a maximum of 100 values with a maximum of 5.000 characters is allowed.● For non-searchable properties, a maximum of 1.000 values with a maximum of 50.000 characters is allowed.

1.2 Getting Started

1. Sign Up

You first need to sign up for an SAP HANA Cloud account.

2. Set Up

Download Eclipse IDE for Java EE Developers, and set up SAP HANA Cloud Tools for Java.

3. Create or Import

Create a classic Java EE HelloWorld application or import an existing sample application to get started.

4. Deploy

Deploy your application using the Eclipse IDE.

5. Monitor

You can view the status and logs of your applications in SAP HANA Cloud Cockpit.

22P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 23: Hana Cloud

Related Information

To download SAP HANA Cloud Tools, go to: http://tools.hana.ondemand.com

Check our video tutorial: Getting Started Video

1.2.1 Signing Up for an Account

To deploy applications on SAP HANA Cloud, you need an account. The platform offers three types of accounts: developer, customer and partner account.

Signing Up for a Developer Account

A developer account offers you access to the trial landscape for an unlimited period and is free of charge.

For more information, see Signing Up for a Developer Account [page 24].

Signing Up for a Customer Account

You can select from a set of predefined packages and get them from SAP Store (https://store.sap.com). You can also contact an SAP sales representative and opt for a configuration, tailored to your needs.

For more information about the pricing of predefined packages, see Get started with the right SAP HANA Cloud package.

Signing Up for a Partner Account

You need to fill in an application form and then sign your partner contract. To access the form, visit SAP HANA Cloud Applications Partner Center.

You will receive a welcome mail with further information afterwards.

Related LinksSigning Up for a Developer Account [page 24]A developer account offers you access to the trial landscape for an unlimited period and is free of charge. You are restricted to one developer account.

Account Types [page 25]SAP HANA Cloud offers three types of accounts: developer, customer, and partner accounts. The account type determines pricing, conditions of use, resources, services available, and deployment landscape. The main features of each account type are described below.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 23

Page 24: Hana Cloud

1.2.1.1 Signing Up for a Developer Account

A developer account offers you access to the trial landscape for an unlimited period and is free of charge. You are restricted to one developer account.

Context

We recommend that you first get a developer account and then download and set up the tools.

Procedure

1. Go to the SAP HANA Cloud landing page (https://account.hanatrial.ondemand.com).2. Depending on whether or not you already have an SAP ID user, proceed as follows:

You already have an SAP ID user Steps

No: Register with the SAP ID service and create a developer account

1. Click Register:

2. On the registration screen, enter the required data and click Register.A dialog box appears informing you that you will be sent an e-mail with a link to activate your account.

3. Go to your e-mail account and activate your developer account.A dialog box appears confirming that your developer account has been activated.

4. Click Continue.

Yes: Sign in and create a developer account 1. Click Log On and sign in with your SAP ID or SCN credentials:

2. Read and accept the SAP HANA Cloud Developer Edition License Agreement.

3. Enter your login details for SAP HANA Cloud and click Log On.

24P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 25: Hana Cloud

4. On the account creation screen, select the database type you want to be used by default for applications deployed in your developer account.You can choose between the SAP HANA database and SAP MaxDB.

5. Click Create Account.A dialog box appears confirming that your developer account has been created.

6. Click OK to go to the SAP HANA Cloud cockpit.

Note○ The name of your developer account comprises your user ID and the suffix trial, for example,

p1234567trial.○ Developer accounts are intended for personal exploration, and not for use in a production environment

or for team development. You cannot assign members to the account (you will not see the Members list normally available).

○ A developer account has only one virtual machine (VM) at its disposal. You can deploy multiple applications, but you can start only one application at any one time.

○ Applications will be stopped automatically after a certain period of time for cleanup purposes.○ When deploying to the cloud, remember to use the SAP HANA Cloud landscape host

hanatrial.ondemand.com.

Related LinksSAP HANA Cloud Cockpit [page 50]Applications [page 52]Account Types [page 25]SAP HANA Cloud offers three types of accounts: developer, customer, and partner accounts. The account type determines pricing, conditions of use, resources, services available, and deployment landscape. The main features of each account type are described below.

1.2.1.2 Account Types

SAP HANA Cloud offers three types of accounts: developer, customer, and partner accounts. The account type determines pricing, conditions of use, resources, services available, and deployment landscape. The main features of each account type are described below.

Developer Account Customer Account Partner Account

Use case A developer account allows you to explore the basic SAP HANA Cloud functionality for a non-committal and unlimited period. Access is open to everyone.

A customer account allows you to host productive, business-critical applications with 24x7 support.

You can purchase a customer account just like any other SAP software.

A partner account enables you to build applications and to sell them to your customers.

Benefits ● Free of charge● Self-service registration

Support for productive applications

It includes SAP Application

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 25

Page 26: Hana Cloud

Developer Account Customer Account Partner Account

● Unlimited period● Automatic access to

SAP HANA Cloud Portal, SAP Mobile Platform, and Gateway as a Service

Development licenses to enable you to get started with scenarios across cloud and on-premise applications. It also offers the opportunity to certify applications and receive SAP partner logo package with usage policies. Partners can advertise and sell applications via the SAP Store. This option is not included in the other accounts.

Services available Productive and beta services Productive services Productive services

Limitations ● You can only run one application

● Only 1 GB of database storage

● Only 1 GB of document storage

● Only one user per account

Resources according to your contract

Predefined resources according to your partner package. More can be purchased if there is a need.

Registration For information about how to register, see Signing Up for a Developer Account [page 24].

Via the SAP store or an SAP sales representative. For inquiries, use the SAP HANA Cloud Developer Center.

To join the partner program, fill in the application form on the SAP HANA Cloud Applications Partner Center.

Databases SAP MaxDB or the SAP HANA database, as selected during registration.

SAP MaxDB or the SAP HANA database, as requested.

SAP MaxDB or the SAP HANA database, as requested.

Deployment landscape hanatrial.ondemand.com hana.ondemand.com hana.ondemand.com

NoteAt present, each account is assigned one database type only.

26P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 27: Hana Cloud

1.2.2 Setting Up the Tools and SDK

Overview

Before developing your application, you need to download and set up the necessary tools, which include Eclipse IDE for Java EE Developers, SAP HANA Cloud Tools, and SDK.

Features

From the SAP Development Tools for Eclipse page, you can download the following tools:

● SAP HANA Cloud Tools:

○ SAP HANA Cloud Tools for Java○ SAP JVM Profiler○ UI development toolkit for HTML5 (Developer Edition)○ Documentation for SAP HANA Cloud

● SAP HANA Cloud SDK - provides local server runtime, deploy tools, samples and test applicactions, APIs, and javadoc.

● SAP JVM - the Java runtime used in SAP HANA Cloud. SAP JVM is an important prerequisite for local profiling with SAP JVM Profiler.

● SAP HANA Cloud Connector - a connectivity tool providing a tunnel between on-demand applications in SAP HANA Cloud and existing on-premise systems.

Next Steps

Installing the SDK [page 27]

Installing Eclipse [page 29]

Installing SAP Development Tools for Eclipse [page 29]

1.2.2.1 Installing the SDK

Overview

There are two major versions of SAP HANA Cloud SDK:

● SAP HANA Cloud SDK for Java Web (1.x) – provides support for some of the standard Java EE APIs● SAP HANA Cloud SDK for Java EE 6 Web Profile (2.x) - provides support for Java EE 6 Web Profile APIs

For the complete list of supported APIs, see Supported APIs [page 58].

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 27

Page 28: Hana Cloud

Procedure

1. Open https://tools.hana.ondemand.com/#cloud2. From the SAP HANA Cloud SDK section, download the relevant SDK archive file and save it to your local file

system.3. Extract the ZIP file.

Related LinksSetting Up the SDK Location and Landscape Host [page 30]

1.2.2.2 Installing SAP JVM

Overview

Follow the steps below to install an SAP Java Virtual Machine.

NoteThis is an optional procedure. You can also run your local server for SAP HANA Cloud on a standard JDK platform, that is an Oracle JVM. SAP JVM, however, is a prerequisite for local profiling with the SAP JVM Profiler.

Prerequisites

In case you want to run your Eclipse IDE on SAP JVM instead of Oracle JVM, you need to edit your eclipse.ini file. Add the following line under <vmargs>:

-XX:MaxPermSize=256m

Procedure

1. Open https://tools.hana.ondemand.com/#cloud2. From the SAP JVM section, download the SAP JVM archive file compatible to your operating system and save

it to your local file system.Depending on the Java version of your application, you should download either SAP JVM 6 (JDK 6) or SAP JVM 7 (JDK 7). For more information regarding incompatibility issues, see http://www.oracle.com/technetwork/java/javase/compatibility-417013.html.

3. Extract the archive file.

Note

28P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 29: Hana Cloud

If you use Windows as your operating system, you need to install the Visual C++ 2005 Runtime prior to using SAP JVM. The installation package for the Visual C++ 2005 Runtime can be obtained from Microsoft. Download and install vcredist_x64.exe from the following site: http://www.microsoft.com/en-us/download/details.aspx?id=14431.

Related LinksSetting Up SAP JVM in Eclipse IDE [page 32]Updating SAP JVM [page 35]

1.2.2.3 Installing Eclipse

Ovreview

Follow the steps below to install a new Eclipse IDE package.

NoteNote that the support for Indigo has entered end of maintenance. Indigo update site is still operational but no updates will be made. We recommend that you use Eclipse Juno 4.2 Service Release 2.

Procedure

1. Download and install the Eclipse IDE for Java EE Developers from http://www.eclipse.org/downloads/.2. Go to the eclipse folder and run the eclipse executable file.3. Specify a <Workspace> directory.

NoteIf the version of your previous Eclipse IDE is 32-bit based and your currently installed Eclipse IDE is 64-bit based (or the other way round), you need to delete the Eclipse Secure Storage, where Eclipse stores, for example, credentials for source code repositories and other login information.

For more information, see Eclipse Help: Secure Storage.

1.2.2.4 Installing SAP Development Tools for Eclipse

Overview

To use SAP HANA Cloud features, you first need to install the relevant toolkit. Follow the steps below.

Note

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 29

Page 30: Hana Cloud

Note that the support for Indigo has entered end of maintenance. Indigo update site is still operational but no updates will be made. We recommend that you use Eclipse Juno 4.2 Service Release 2.

Procedure

1. Open the Eclipse IDE.

2. In the main menu, choose Window Preferences .

Note

For some operating systems, the path is Eclipse Preferences .

3. Configure your proxy settings:

a. Go to General Network Connections .b. In the Active Provider dropdown menu, choose Manual.c. Configure your <HTTP> and <HTTPS> connections.d. Choose Apply.

4. Optional: If you want to have your SAP HANA Cloud Tools for Java updated regularly and automatically, in the Preferences window, go to Install/Update Automatic Updates , then select Automatically find new updates and notify me and choose Apply.

5. Choose OK to close the Preferences window.

6. In the main menu, choose Help Install New Software .7. Enter URL https://tools.hana.ondemand.com/juno and press the ENTER key.8. Make sure that the Contact all update sites during install to find required software checkbox is selected.9. Select SAP HANA Cloud Tools to install the whole toolkit. If you do not need the complete package, expand the

node and only select the necessary components.10. Choose Next.11. Read and accept the Eclipse and SAP license agreements and choose Finish.12. After the successful installation, restart the Eclipse IDE.

1.2.2.5 Setting Up the SDK Location and Landscape Host

Overview

Follow the steps below to set or configure your SDK location and the landscape host on which you want to deploy your applications.

30P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 31: Hana Cloud

Procedure

1. In the Eclipse IDE main menu, choose Window Preferences .

2. Choose Server SAP HANA Cloud .3. The SAP HANA Cloud landscape host hana.ondemand.com is set by default. Enter the relevant landscape

host for your account type:

○ For customer accounts, use hana.ondemand.com.○ For developer accounts, use hanatrial.ondemand.com.

4. For SDK Location, choose the Browse... button and browse to the folder to which you have extracted the downloaded SDK ZIP file.

5. In the Account information pane, enter your account name and e-mail (or user name).

Note○ The name of your account comprises your SCN user ID and the suffix trial, for example,

p1234567trial.○ Developer accounts are intended for personal exploration, and not for use in a production environment

or for team development. You cannot assign members to the account (you will not see the Members list normally available).

○ A developer account has only one virtual machine (VM) at its disposal. You can deploy multiple applications, but you can start only one application at any one time.

○ When deploying to the cloud, remember to use the SAP HANA Cloud landscape host hanatrial.ondemand.com.

6. Choose the Validate button to check whether the data on this preference page is valid.7. Choose OK.

1.2.2.6 Setting Up the Runtime Environment

Overview

Once you have installed SAP HANA Cloud Tools for Java, you need to set up your runtime environment. Follow the steps below.

Procedure

1. In the Eclipse IDE main menu, choose Window Preferences .

2. Choose Server Runtime Environments .3. Choose the Add button.

4. Select SAP SAP HANA Cloud and choose Next.5. SAP HANA Cloud is set as the default name.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 31

Page 32: Hana Cloud

6. Select the Use SAP HANA Cloud SDK from the following location radio button.The previously selected SDK location is set by default.

7. Choose Finish.The server runtime environment SAP HANA Cloud is added.This is the default runtime you will later use to deploy Java EE applications and for consuming services.

8. In the Preferences window, choose OK.

1.2.2.7 Setting Up SAP JVM in Eclipse IDE

Overview

Once you have installed SAP JVM, you need to do the relevant settings. Follow the steps below.

Procedure

1. In the Eclipse IDE main menu, choose Window Preferences .

2. Choose Java Installed JREs .

a. Choose the Add button.Standard VM is set as the default JRE type.

b. Choose Next.c. For the JRE home field, choose the Directory... button and browse to the SAP JVM folder within the folder

to which you previously extracted the archive.d. Choose Finish.

3. In the Preferences window, choose OK.

4. Open the Preferences window again and choose Plug-in Development Target Platform .

a. Make sure that SAP HANA Cloud SDK is selected. Then choose the Edit button.b. Choose the Environment tab.c. Select the JRE name option.d. Switch to the SAP JVM entry.e. Choose Finish.

5. In the Preferences window, choose OK.

1.2.2.8 Setting Up SAP HANA Cloud Console Client

Overview

Before working with the SAP HANA Cloud console client, you need to configure it.

32P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 33: Hana Cloud

Procedure

1. Download and extract the SAP HANA Cloud SDK from https://tools.hana.ondemand.com/ .2. If you use a proxy server, you need to configure proxy settings specifying them using the environment

variables. You can find sample proxy settings in the readme.txt file in the tools folder of your SDK location.

○ Windows

Note○ For the new variables to be effective every time you open the console, define them using

<Windows Advanced System Settings> and restart the console.○ For the new variables to be valid only for the currently open console, define them in the console

itself.

For example, if your proxy host is proxy and proxy port is 8080, specify the following environment variables:

set HTTP_PROXY_HOST=proxyset HTTP_PROXY_PORT=8080set HTTPS_PROXY_HOST=proxyset HTTPS_PROXY_PORT=8080set HTTP_NON_PROXY_HOSTS="localhost"

If you need basic proxy authentication, enter your user name and password:

set HTTP_PROXY_USER=<user name>set HTTP_PROXY_PASSWORD=<password>set HTTPS_PROXY_USER=<user name>set HTTPS_PROXY_PASSWORD=<password>

○ Linux, Mac OS X or other Unix based:

export http_proxy=http://proxy:8080export https_proxy=https://proxy:8080export no_proxy="localhost"

If you need basic proxy authentication, enter your user name and password:

export http_proxy=http://user:password@proxy:8080export https_proxy=https://user:password@proxy:8080

3. Open the Command Prompt and change the current directory to the extracted location of your download. For example:

cd neo-sdk*cd tools

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 33

Page 34: Hana Cloud

Next Steps

You can now perform various operations provided by SAP HANA Cloud console client.

For more information, see SAP HANA Cloud Console Client [page 61].

1.2.3 Updating the Tools and SDK

Overview

If you have already installed and used the SAP HANA Cloud Tools, SDK and SAP JVM, you only need to update them.

Follow the steps from the relevant procedures listed below.

Related LinksUpdating the SDK [page 34]Updating SAP Development Tools for Eclipse [page 36]Updating SAP JVM [page 35]

1.2.3.1 Updating the SDK

Overview

If you have already installed an SDK package, you only need to update it regularly. To update your SDK, follow the steps below.

Procedure

1. Download the new SDK version from https://tools.hana.ondemand.com/#cloud2. Unzip the SDK to a new directory on your local file system. Do not install the new SDK version to a directory

that already contains SDK.

3. Configure the location of the new SDK version in the Eclipse IDE: Window Preferences Server SAP HANA Cloud SDK Location .

NoteIf the SDK version is higher and not supported by the version of your SAP HANA Cloud Tools for Java, a message appears prompting you to update your SAP HANA Cloud Tools for Java. You can check for updates (recommended) or ignore the message.

34P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 35: Hana Cloud

4. Go to the Servers tab view.5. Delete all servers of type <SAP HANA Cloud local runtime>.

6. Choose Window Preferences Server Runtime Environment .For every SAP HANA Cloud runtime:

a. Select the corresponding entry in the table.b. Choose the Edit button.c. Select the Use SAP HANA Cloud SDK from the following location option and make sure the location points

to the new SDK.

NoteAgain, if the SDK version is higher and not supported by the version of your SAP HANA Cloud Tools for Java, a message appears prompting you to update your SAP HANA Cloud Tools for Java. You can check for updates (recommended) or ignore the message.

d. Choose Finish.7. After editing all SAP HANA Cloud runtimes, choose OK.

1.2.3.2 Updating SAP JVM

Overview

If you have already installed an SAP Java Virtual Machine, you only need to update it. To update your JVM, follow the steps below.

Procedure

1. Download the new SAP JVM version from https://tools.hana.ondemand.com/#cloud2. Extract the SAP JVM archive locally on your machine to a new directory.

NoteDo not install the new SAP JVM version to a directory that already contains SAP JVM.

3. In the Eclipse IDE main menu, choose Window Preferences Java Installed JREs and select the JRE configuration entry of the old SAP JVM version.

4. Choose the Edit... button.5. Use the Directory... button to select the directory of the new SAP JVM version.6. Choose Finish.7. In the Preferences window, choose OK.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 35

Page 36: Hana Cloud

1.2.3.3 Updating SAP Development Tools for Eclipse

Overview

If you have already installed SAP HANA Cloud Tools, you only need to update them. To do so, follow the steps below.

Procedure

1. Ensure that the SAP HANA Cloud Tools software site is checked for updates:

a. Find out whether you are using an Indigo or Juno release of Eclipse. The name of the release is shown on the welcome screen when the Eclipse IDE is started.

NoteNote that the support for Indigo has entered end of maintenance. Indigo update site is still operational but no updates will be made. We recommend that you use Eclipse Juno 4.2 Service Release 2.

b. In the main menu, choose Window Preferences Install/Update Available Software Sites .c. Make sure there is an entry with location https://tools.hana.ondemand.com/juno, and that the

entry is selected.d. Choose OK to close the Preferences dialog box.

2. Choose Help Check for Updates .3. Choose Finish to start installing the updates.

NoteIf you want to have your SAP HANA Cloud Tools for Java updated regularly and automatically, open the Preferences window again and choose Install/Update Automatic Updates . Select Automatically find new updates and notify me and choose Apply.

1.2.4 Creating a HelloWorld Application

Overview

This document describes how to create a simple HelloWorld Web application, which you can use for testing on SAP HANA Cloud.

First, you create a Dynamic Web Project and then you add a simple HelloWorld servlet to it.

36P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 37: Hana Cloud

After you have created the Web application, you can test it on the local runtime and then run it on SAP HANA Cloud.

Prerequisites

You have installed the SAP HANA Cloud Tools.

For more information, see Setting Up the Tools and SDK [page 27].

1. Create a Dynamic Web Project

1. Open your Eclipse IDE for Java EE Developers.

2. From the Eclipse IDE main menu, choose File New Dynamic Web Project .3. In the Project name field, enter HelloWorld.4. Leave the default value in the Target runtime field, that is SAP HANA Cloud. The target runtime defines against

what the HelloWorld Web application will be executed at runtime.5. In the Configuration area, leave the default configuration.6. Optional: If you want your context root to be different from "HelloWorld", proceed as follows:

a. Choose the Next button until you reach the Web Module wizard page.b. Edit the Context root field. In case you wish to deploy the application in the server's root, just replace the

current string with "/".

7. Choose Finish.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 37

Page 38: Hana Cloud

2. Create a HelloWorld Servlet

1. On the HelloWorld project node, open the context menu and choose New Servlet . Window Create Servlet opens.

38P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 39: Hana Cloud

2. Enter hello as Java package and HelloWorldServlet as class name.

3. Choose Next.4. In the URL mappings field, select /HelloWorldServlet and choose Edit.5. In the Pattern field, replace the current value with just "/". In this way, the servlet will be mapped as a welcome

page for the application.

6. Choose Finish to generate the servlet. The Java Editor with the HelloWorldServlet opens.7. Change the doGet(…) method so that it contains:

response.getWriter().println("Hello World!");

8. Save your changes.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 39

Page 40: Hana Cloud

Result

You have now created a Web application containing a HelloWorld servlet that is ready to be tested on the local runtime and deployed to SAP HANA Cloud .

Next Steps

Test your HelloWorld application locally and deploy it to SAP HANA Cloud.

For more information, see Deploying from the Eclipse IDE.

You can create a HelloWorld application with SAPUI5.

For more information, see Creating a HelloWorld Application with SAPUI5 [page 41].

40P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 41: Hana Cloud

1.2.5 Creating a HelloWorld Application with SAPUI5

Prerequisites

The SAPUI5 tools are installed in your eclipse environment.

Context

Instead of creating a HelloWorld Servlet, you can directly go for the UI part and create an SAPUI5 application.

Using the tools SAPUI5 provides, you create application projects and views according to the Model View Controller concept with a clear separation between the user interface and the controller logic.

For SAPUI5 applications the following development paradigms are supported:

● JavaScript (file extension: js)● XML (file extension: xml)● JSON (file extension: json)● HTML (file extension: html)

In the following steps you will create a JavaScript example.

Procedure

1. To open the wizard for creating an SAPUI5 application, choose File New Other... SAPUI5 Application Development Application Project

2. Specify the name and location for your project. Select the checkbox for Create an initial View .3. In the next wizard step:

a) Enter a name for the initial view in the Name field, e. g. helloworld. Don't add a file extension, this is done automatically based on the development paradigm.

a) Choose JavaScript as Development Paradigm and finish the wizard.If you want to use XML or JSON, just proceed accordingly.

4. To add a control to your view (in this example: helloworld.view.js), insert the following coding:

createContent : function(oController) { var aControls = []; var oButton = new sap.ui.commons.Button({ id : this.createId("MyButton"), text : "Hello World" }); aControls.push(oButton.attachPress(oController.doIt)); return aControls;}

For your convenience the coding is put into a separate method called createContent

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 41

Page 42: Hana Cloud

5. To implement the doIt method for the button's press event, insert the following coding into the controller (in this exmaple: helloworld.controller.js)

doIt : function(oEvent) { alert(oEvent.getSource().getId() + " does it!"); }

6. That's it! To test your application, open the context menu of your project, choose Run As Run on Server and select your local test server.

Your SAPUI5 application is started in a browser.

Related LinksUI Development with SAPUI5 [page 69]

1.2.6 Samples

Overview

The sample applications allow you to explore the core functionality of SAP HANA Cloud and show how this functionality can be used to develop more complex Web applications. The samples available are described below.

SDK Samples

The samples provided as part of the SAP HANA Cloud SDK demonstrate important concepts and application features of the SAP HANA Cloud platform and show how common development tasks can be automated using build and test tools.

The samples are located in the <sdk>/samples folder. The table below lists the samples currently available:

Sample Feature More Information

hello-world A simple HelloWorld Web application Creating a HelloWorld Application

explore-ui5 SAPUI5 controls Creating a HelloWorld Application with SAPUI5 [page 41]

authentication HTTP BASIC authentication scheme User Authentication

connectivity-outbound-internet

Consumption of Internet services Tutorial: Using Internet Services in Cloud Applications [page 358]

persistence-with-ejb Container-managed persistence with JPA

Adding Container-Managed Persistence with JPA (SDK 2.x) [page 411]

persistence-with-jpa Application-managed persistence with JPA

Adding Application-Managed Persistence with JPA (SDK 1.x) [page 420]

persistence-with-jdbc

Relational persistence with JDBC Adding Persistence Using JDBC [page 430]

document-store Document storage in repository Using the Document Service in a Web Application

42P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 43: Hana Cloud

Sample Feature More Information

mail Sending e-mails Tutorial: Sending E-Mails [page 396]

All samples can be imported as Eclipse or Maven projects. While the focus has been placed on the Eclipse and Apache Maven tools due to their wide adoption, the principles apply equally to other IDEs and build systems.

For more information about using the samples, see Running Samples [page 43] and Building Samples with Maven [page 44].

Community Samples

The sample Web application “Paul the Octopus" is part of a community blog and shows how the SAP HANA Cloud services and capabilities can be combined to build more complex Web applications, which can be deployed on the SAP HANA Cloud platform.

Features of "Paul the Octopus":

● It is intended for anyone who would like to gain hands-on experience with the SAP HANA Cloud platform.● It involves the following platform services: identity, connectivity, persistence, and document.● Its user interface is developed via SAPUI5 and is based on the Model-View-Controller concept. SAPUI5 is

based on HTML5 and can be used for building applications with sophisticated UI. Other technologies that you can see in action in "Paul the Octopus" are REST services and job scheduling.

For more information on how to get and run these samples, see the SCN community blog Get Ready for Your Paul Position.

Related LinksRunning Samples [page 43]To get a sample application up and running, import it as an Eclipse project into your Eclipse IDE and then deploy it on the local runtime and SAP HANA Cloud.

Building Samples with Maven [page 44]All samples provided can be built with Apache Maven. The Maven build shows how a headless build and test can be completely automated.

1.2.6.1 Running Samples

To get a sample application up and running, import it as an Eclipse project into your Eclipse IDE and then deploy it on the local runtime and SAP HANA Cloud.

Prerequisites

You have installed the SAP HANA Cloud Tools and created a SAP HANA Cloud server runtime environment as described in Setting Up the Tools and SDK [page 27].

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 43

Page 44: Hana Cloud

Context

When you import samples as Eclipse projects, the tests provided with the samples are not imported. To be able to run automated tests, you need to import the samples as Maven projects.

Procedure

1. From the main menu of the Eclipse IDE, choose File Import… General Existing Projects into Workspace and then choose Next.

2. Browse to locate and select the directory containing the project you want to import, for example, <sdk>/samples/hello-world, and choose OK.

3. Under Projects select the project (or projects) you want to import.4. Choose Finish to start the import.

The project is imported into your workspace and appears in the Project Explorer view.

NoteIf you have not yet set up a server runtime environment, the following error will be reported: "Faceted Project Problem: Target runtime SAP HANA Cloud is not defined". To set up the runtime environment complete the steps as described in Setting Up the SDK Location and Landscape Host [page 30] and Setting Up the Runtime Environment [page 31].

5. To run the sample application locally and then in the cloud, proceed as described in Deploying Locally from Eclipse IDE [page 533] and Deploying on the Cloud from Eclipse IDE [page 535].

1.2.6.2 Building Samples with Maven

All samples provided can be built with Apache Maven. The Maven build shows how a headless build and test can be completely automated.

Context

The build and test does the following:

● Builds a Java EE application based on the SAP HANA Cloud platform API● Demonstrates how to run rudimentary unit tests (not available in all samples)● Installs, starts, waits for, and stops the local server runtime● Deploys the application to the local server runtime and runs the integration test● Starts, waits for, and stops the cloud server runtime● Deploys the application to the cloud server runtime and runs the integration test

Related Links

44P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 45: Hana Cloud

Building Samples from the Command Line [page 45]You can use the Apache Maven command line tool to run local and cloud integration tests for any of the samples provided.

Building Samples from Eclipse [page 46]To use the Eclipse IDE rather than the Maven command line, you need to install the Maven Integration for Eclipse WTP plugin, which provides a bridge between Maven, Eclipse, and the WTP tooling. This allows you to run Maven goals and view the results from within Eclipse.

1.2.6.2.1 Building Samples from the Command Line

You can use the Apache Maven command line tool to run local and cloud integration tests for any of the samples provided.

Context

You can find the Maven command line tool and detailed Maven documentation at http://maven.apache.org.

Procedure

1. Open the folder of the relevant project, for example, <sdk>/samples/hello-world, and then open the command prompt.

2. Enter your proxy settings as shown in the example below:

Windows Linux

set PROXY_HOST=proxy_host export PROXY_HOST=proxy_host

set PROXY_PORT=proxy_port export PROXY_PORT=proxy_port

NoteIf you do not have a proxy, you need to remove all occurrences of the proxy properties in the parent pom.xml file (<sdk>/samples/pom.xml).

3. Enter the verify command with the following profile in order to activate the local integration test:

mvn verify -P local-integration-tests

4. Press ENTER to start the build process.

All phases of the default lifecycle are executed up to and including the verify phase.The status of the build is confirmed on completion.

For more information about the Apache Maven build lifecycle, see http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 45

Page 46: Hana Cloud

5. To run the cloud integration test, which involves deploying the built Web application to the cloud, provide your account details using the following environment variables: SAP_CLOUD_ACCOUNT, SAP_CLOUD_USERNAME, and SAP_CLOUD_PASSWORD:

Windows Linux

set SAP_CLOUD_ACCOUNT=your_account export SAP_CLOUD_ACCOUNT=your_account

set SAP_CLOUD_USERNAME=your_username export SAP_CLOUD_USERNAME=your_username

set SAP_CLOUD_PASSWORD=your_password export SAP_CLOUD_PASSWORD=your_password

NoteIf you are using a developer account, you need to change the cloud host in the parent pom.xml file (<sdk>/samples/pom.xml) to hanatrial.ondemand.com.

6. Enter the following profile to activate the cloud integration test:

mvn verify -P cloud-integration-tests

Alternatively, you can run both tests together with the following command:

mvn verify -P local-integration-tests -P cloud-integration-tests

1.2.6.2.2 Building Samples from Eclipse

To use the Eclipse IDE rather than the Maven command line, you need to install the Maven Integration for Eclipse WTP plugin, which provides a bridge between Maven, Eclipse, and the WTP tooling. This allows you to run Maven goals and view the results from within Eclipse.

Prerequisites

You have installed the SAP HANA Cloud Tools and created a SAP HANA Cloud server runtime environment as described in Setting Up the Tools and SDK [page 27].

Installing the Maven Integration for Eclipse WTP

Procedure

1. From the Eclipse main menu, choose Help Eclipse Marketplace .2. Enter Maven in the Find field and choose Go.

46P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 47: Hana Cloud

3. Locate the Maven Integration for Eclipse WTP (Incubation) item and choose the Install button.

Alternatively, you can use the drag and drop installation provided at http://marketplace.eclipse.org/content/maven-integration-eclipse-wtp-incubation.

Note

To configure the Maven settings.xml file, choose Window Preferences Maven User Settings . This configuration is required if you need to provide your proxy settings. For more information, see http://maven.apache.org/settings.html. However, see also step 4 in the "Running a Build and Test" section below.

Importing a Sample Maven Project

Procedure

1. From the Eclipse main menu, choose File Import… Maven Existing Maven Projects and then choose Next.

2. Browse to locate and select the directory containing the project you want to import, for example, <sdk>/samples/hello-world, and choose OK.

3. Under Projects select the project (or projects) you want to import.4. Choose Finish to start the import.

The project is imported into your workspace and appears in the Project Explorer view.

5. If necessary, update the project to remove any errors after the import. To do this, choose Maven Update Project and then OK.

Running a Build and Test

Procedure

1. To start a Maven build, select the project node and from the Eclipse main menu choose Run Run AsMaven build .The Edit Configuration dialog box appears.

2. In the Goals field, enter verify.

3. In the Profiles field, enter local-integration-tests.

4. Switch to the Environment tab and choose the New button to create the following variables:

○ PROXY_HOST: proxy_host○ PROXY_PORT: proxy_port

Note

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 47

Page 48: Hana Cloud

If you don’t have a proxy, you need to remove all occurrences of the proxy properties in the parent pom.xml file (<sdk>/samples/pom.xml).

5. Choose Run to start the test.The status of the build is confirmed on completion.

6. To run the cloud integration test, select the project and choose Run Run Configurations .The Run Configurations dialog box appears.

7. On the left, select Maven Build and then choose the New button to create a new configuration.8. In the Goals field, enter verify.

9. In the Profiles field, enter cloud-integration-tests.

You can also run both the local and cloud tests together by entering both profiles: local-integration-tests cloud-integration-tests

10. Switch to the Environment tab and choose the New button to create the following variables:

○ PROXY_HOST: proxy_host○ PROXY_PORT: proxy_port○ SAP_CLOUD_ACCOUNT: your_account○ SAP_CLOUD_USERNAME: your_username○ SAP_CLOUD_PASSWORD: your_password

11. Choose Run to start the test.

NoteIf you are using a developer account, you need to change the cloud host in the parent pom.xml file (<sdk>/samples/pom.xml) to hanatrial.ondemand.com.

The status of the build is confirmed on completion.

1.2.7 Tutorials

Follow the tutorials below to get familiar with the services offered by SAP HANA Cloud.

Create a simple "HelloWorld" Web application, which you can test on SAP HANA Cloud

Creating a HelloWorld Application [page 36]

Connectivity Service tutorials Tutorial: Using Internet Services in Cloud Applications [page 358]

Tutorial: Using On-Premise Back-End Services in Cloud Applications [page 364]

Tutorial: Invoking ABAP Function Modules in On-Premise ABAP Systems [page 384]

Tutorial: Sending E-Mails [page 396]

Persistence Service tutorials Adding Application-Managed Persistence with JPA (SDK 1.x) [page 420]

48P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 49: Hana Cloud

Adding Container-Managed Persistence with JPA (SDK 2.x) [page 411]

Adding Persistence Using JDBC [page 430]

Migrating Web Applications That Use context.xml [page 439]

Document Service tutorials Using the Document Service in a Web Application [page 482]

Accessing Document Service from External Applications [page 479]

Monitoring tutorial Tutorial: Configuring an Availability Check to Monitor Your Application [page 561]

Security tutorial Tutorial: Using the Keystore Service for Client Side HTTPS Connections [page 520]

1.3 Developer's Guide

You can develop your own custom SAP HANA Cloud applications that bring value to your customers. The Developer’s Guide provides information about the programming patterns you can use, and the APIs for accessing the SAP HANA Cloud services.

To learn more about See

How to develop SAP HANA Cloud applications Developing Applications [page 63]

How to use SAP HANA persistence service in applications Consuming the Persistence Service [page 410]

How to use SAP HANA connectivity service in applications Consuming the Connectivity Service [page 303]

How to use SAP HANA identity service and add other security aspects to applications

Securing Applications [page 486]

How to use SAP HANA document service in applications Using the Document Service in a Web Application [page 482]

How to send and fetch e-mail Sending and Fetching E-Mail [page 391]

How to enable logs in applications Logging in Applications [page 550]

How to deploy applications Deploying Applications [page 532]

How to manage deployed applications in the SAP HANA Cloud cockpit

SAP HANA Cloud Cockpit [page 50]

API Documentation API Documentation

Related Information

Visit the SAP HANA Cloud Developer Center for news, discussions, requests.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 49

Page 50: Hana Cloud

1.3.1 SAP HANA Cloud CockpitOverview

The cockpit is the central point for managing all activities associated with your account and for accessing key information about your applications. It allows you to manage all applications deployed in your account from a single dedicated user interface. You retain an overview of the current status of the individual applications and the overall application deployment status in your account, while at the same time being able to drill down quickly to review logging and monitoring information and initiate actions at application and process level.

Accounts

The cockpit provides integrated access to all accounts you operate on the production landscape, hana.ondemand.com. Bear in mind that the accounts are totally independent of each other.

A separate cockpit for developer accounts is available on the trial landscape, hanatrial.ondemand.com.

Login

You can log into the cockpit from the landing page, which is available at the following URLs:

● Customer and partner accounts: https://account.hana.ondemand.com● Developer accounts: https://account.hanatrial.ondemand.com

Navigation

The object on which you are currently focused is shown in the object area in the upper left section of the screen. At the highest level it is an account and, as you drill down to lower levels, an application or application process. The main areas of the cockpit screen are outlined below, showing the object area (upper left), the navigation options (lower left), and the content area (on the right), which in this example consists of just one panel (Applications):

50P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 51: Hana Cloud

Each level determines which navigation options are available and the information that is displayed. You can navigate upwards in the hierarchy using the links in the object area and switch to other objects by clicking the triangular selector, as shown in the example below:

Auto Refresh

By default, auto refresh is deactivated. You can trigger the auto-refresh function using the Auto-Refresh button located above a panel. Note that auto refresh is only available for panels that may occasionally require automatic updates to track progress or see trends, while other panels allow manual refresh or do not have a refresh function at all. Auto refresh, when activated, runs for a maximum of 30 minutes. Certain actions also trigger auto refresh, such as when you start or stop an application

Related LinksAccount Members [page 52]Applications [page 52]Resources [page 55]Information about the resources available to your account and their current and past usage is available at both account and application level. At account level, the values are aggregated for all applications in the account.

Subscriptions and Services [page 55]The cockpit provides an overview of all subscriptions purchased by your account and services to which you have access.

Using a Custom Identity Provider [page 487]Managing Role Assignments [page 501]

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 51

Page 52: Hana Cloud

1.3.1.1 Account Members

Overview

You use an account to set up your team. All users assigned to your account can use the functions provided by the cockpit within the scope of this account, such as viewing the log files, starting, stopping, and undeploying applications, and adding and removing account members. All account members can use the account for application deployment with the console client and Eclipse IDE.

Note the following points about account members:

● A user may be assigned to more than one account.● Account members are not distinguished by their role (for example, developer, IT administrator, or application

operator).● Members can perform all operations associated with an account.

Adding and Deleting Members

You manage your account members using the Members option in the cockpit. All members currently assigned to the account are displayed in a list.

To add a new member, you need to enter the user ID of the person you want to add as a member and then choose the Add Member button. The user ID is case-insensitive and must contain alphanumeric characters only. Make sure that the user ID is correct since there is currently no user validation.

The user is added to the list of team members and automatically has the permissions required to access the cockpit for this account as well as perform all operations associated with the account, irrespective of the tool used (cockpit, Eclipse IDE, or console client).

To delete a member, select the relevant row and then choose the Delete button.

NoteEvery member of the team is allowed to delete any member contained in the account member list except themselves.

1.3.1.2 Applications

Overview

The cockpit allows you to retain an overview of the current status of the individual applications deployed in your account and to drill down to application and application process level to obtain a further breakdown of information.

At account level, the application overview summarizes the key information about each application:

52P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 53: Hana Cloud

● Name: Applications are uniquely named within an account.● Application processes: The number of processes started for the specific application.● Status: The overall status of the application.● Started: If started, the date and time when the application was last started.

Application Status

An application’s overall status is specified at the account level and is one of the following:

● Stopped: The application has been deployed but is currently not running on a virtual machine (VM).● Started: The application has been started on the VM.● Starting or Stopping: The application is transitioning between the Started and Stopped states.● Error: Indicates a fault, such as server unavailability, timeout, or VM failure.

Actions

You can directly start, stop, or undeploy an application, depending on its current state, at both account and application level. Typically you manage an application as follows: :

1. Deploy the application: The application appears in the application list in the Stopped state (the Start and Delete buttons are enabled).

2. Start the application: The application transitions to the Started state (the Stop button is enabled).3. Stop the application: The application transitions to the Stopped state (the Start and Delete buttons are

enabled again).4. Undeploy (delete) the application: The application is deleted from your account and disappears from the

application list. This also removes all data related to the application, such as configuration settings and logs.

Note the following points about starting and stopping application processes:

● By default, an application is started with one process. You cannot start additional application processes from the cockpit. To start an application with multiple processes, deploy the application with the console client and remember to set the minimum and maximum number of server processes appropriately.

● When you stop an application, all application processes are stopped, irrespective of the tool used.

Application Dashboard

At account level, click an application link to view its details in the dashboard, as shown in the figure below:

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 53

Page 54: Hana Cloud

The dashboard provides more detailed information about the application and allows you to do the following. Note that most of these options are only available for an application that has been started:

● View the status and effective compute unit size of each individual application process. Compute unit sizes are given as Lite, Professional, Premium, or Premium Plus.

● Navigate to the application process level and view the current metrics for the selected process in the dashboard. It provides details about two groups of metrics - those monitored by default and those defined by the application operator.

● Display the most recent log files for the selected application● Open the application by clicking the URL

Application Availability

Availability information about an application is provided at application level. Note that these details are only shown if an availability check has been configured for the application and the application has been started.

Logs

You can view the logs and change the log settings of any applications deployed in your account. For more information, see Using Logs in the Cockpit [page 556].

Related LinksUsing Logs in the Cockpit [page 556]You can view the logs and change the log settings of any applications deployed in your account.

Configuring Destinations from the Cockpit [page 311]

Deploying on the Cloud with the Console Client [page 537]Deploying an application publishes it to SAP HANA Cloud. During deploy, you can define various specifics of the deployed application using the deploy command optional parameters.

54P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 55: Hana Cloud

1.3.1.3 Resources

Information about the resources available to your account and their current and past usage is available at both account and application level. At account level, the values are aggregated for all applications in the account.

Key resource usage is shown in the upper half of the screen. Key resources include the following: Number of compute units (virtual machines); database storage (in bytes); HTTP requests per day; outgoing network data transfer, in bytes per day.

More detailed information about the resources is provided in the lower half of the screen, as follows:

● The latest values recorded for each resource type, listed with the associated platform service, the time when the value was recorded, and the quota actually assigned to the account.

● Resource consumption statistics for time periods that can be selected in the dropdown box (last 24 hours, last 7 days, and last 30 days). Each resource type is listed with the average and maximum consumption values recorded over the selected time period.

Note that at present the only resource limit that is actually enforced is the compute unit size (number of virtual machines).

1.3.1.4 Subscriptions and Services

The cockpit provides an overview of all subscriptions purchased by your account and services to which you have access.

Subscriptions

All applications to which your account has subscribed are listed on the Subscriptions screen. You can purchase new subscriptions from the SAP store by choosing the Add button. When you have completed the purchasing process, the subscription will be listed in the table with the following information:

● The account name of the application provider from which the subscription was purchased● Name of the application● Application URLs allowing you to directly launch the application

Services

All services that you are authorized to access are listed on the Services screen. The services currently available are the following:

● SAP HANA Cloud Portal● SAP Mobile Platform, enterprise edition, cloud version● Gateway as a Service

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 55

Page 56: Hana Cloud

1.3.2 Development Environment

The basic tools of the SAP HANA Cloud development environment, the SAP HANA Cloud Tools, comprise the SAP HANA Cloud Tools for Java and the SAP HANA Cloud SDK.

The focus of the SAP HANA Cloud Tools for Java is on the development process and enabling the use of the Eclipse IDE for all necessary tasks: creating development projects, deploying applications locally and in the cloud, and local debugging. It makes development for the platform convenient and straightforward and allows short development turn-around times.

The SDK, on the other hand, contains everything necessary to work with the platform, including a local server runtime and a set of command line tools. The command line capabilities enable development outside of the Eclipse IDE and allow modern build tools, such as Apache Maven, to be used to professionally produce Web applications for the cloud. The command line is particularly important for setting up and automating a headless continuous build and test process.

A graphical overview of this tool environment is shown below:

1.3.2.1 SAP HANA Cloud SDK

Overview

The SDK contains everything necessary to work with SAP HANA Cloud, including a local server runtime and a set of command line tools. An overview of the structure and content of the SDK is shown in the table below. The folders and files are located directly below the common root directory in the order given:

Folder/File Description

add-ons Additional software that supports the development of SAP HANA Cloud applications (SDK 2.x only).

56P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 57: Hana Cloud

Folder/File Description

api The platform API containing the SAP and third-party API JARs required to compile Web applications for SAP HANA Cloud (for more information about the platform API, see the "Supported APIs" section further below).

javadoc Javadoc for the SAP platform APIs (also available as online documentation via the API Documentation link in the title bar of the SAP HANA Cloud Documentation Center). Javadoc for the third-party APIs is cross-referenced from the online documentation.

repository The P2 repository from which the local server runtime is created.

samples Samples demonstrating how to develop for SAP HANA Cloud. The samples can be imported as Eclipse or Maven projects.

server Initially not present, but created once you install a local server runtime.

tools Command line tools required for interacting with the cloud runtime (for example, to deploy and start applications) and the local server runtime (for example, to install and start the local server).

licenses.txt Licenses of third-party components contained in the SAP HANA Cloud SDK.

readme.txt Brief introduction to the SDK, its content, and how to set it up.

sdk.version SDK version information for use by other tools interacting with the SDK.

Local Server Runtime

The cloud server runtime consists of the application server, the platform API, and the cloud implementations of the provided services (connectivity, persistence, document, and identity). The SDK, on the other hand, contains a local server runtime that consists of the same application server, the same platform API, but local implementations of the provided services. These are designed to emulate the cloud server runtime as closely as possible to support the local development and test process. For example:

● The identity service cannot be used on the local server. Instead, user authentication can be tested locally based on a set of user accounts defined in a local JSON file.

● The persistence service makes available a lightweight embedded database instance for local testing, while the cloud server runtime provides professional database support with high availability, backup and recovery.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 57

Page 58: Hana Cloud

Supported APIs

The SAP HANA Cloud SDK contains the platform API of SAP HANA Cloud. All Web applications intended for deployment in the cloud should be compiled against this platform API. The platform API is used by the SAP HANA Cloud Tools for Java to set the compile-time classpath.

All JARs contained in the platform API are considered part of the provided scope and must therefore be used for compilation. This means that they must not be packaged with the application, since they are provided and wired at runtime in the SAP HANA Cloud runtime, irrespective of whether you run your application locally for development and test purposes or centrally in the cloud.

When you develop applications to run on the SAP HANA Cloud platform, you should be aware of which APIs are supported and provisioned by the runtime environment of the platform:

● Third-party APIs: These include Java EE standard APIs (standards based and backwards compatible as defined in the Java EE Specification) and other APIs released by third parties.

● SAP APIs: The platform APIs provided by the SAP HANA Cloud services.

Related LinksSupported APIs [page 58]Samples [page 42]Deploying Locally with the Console Client [page 536]The console client allows you to install a server runtime into a local folder and use it to deploy your application.

SAP HANA Cloud Console Client [page 61]

1.3.2.1.1 Supported APIs

When you develop applications that run on SAP HANA Cloud, you can rely on certain Java EE standard APIs. These APIs are provided with the runtime service of the platform. They are based on standards and are backward compatible as defined in the Java EE specifications. Currently, you can make use of the APIs listed below:

● javax.activation● javax.annotation● javax.el● javax.mail● javax.persistence● javax.servlet● javax.servlet.jsp● javax.servlet.jsp.jstl

You can also make use of the following third-party APIs:

● org.slf4j.Logger● org.slf4j.LoggerFactory

If you are using the SAP HANA Cloud SDK for Java EE 6 WebProfile, you can have access to the following Java EE APIs as well:

● javax.faces

58P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 59: Hana Cloud

● javax.validation● javax.inject● javax.ejb● javax.interceptor● javax.transaction● javax.enterprise● javax.decorator

The table below summarizes the Java Request Specifications (JSRs) supported in the two SAP HANA Cloud SDKs for Java.

Supported Java EE 6 Specification SAP HANA Cloud SDK for Java Web

SAP HANA Cloud SDK for Java EE 6 WebProfile

Servlet 3.0 yes yes

JavaServer Pages (JSP) 2.2 yes yes

Expression Language (EL) 2.2 yes yes

Debugging Support for Other Languages 1.0

yes yes

Standard Tag Library for JavaServer Pages (JSTL) 1.2

yes yes

Common Annotations for Java Platform 1.1

yes yes

JavaServer Faces (JSF) 2.0 no yes

Enterprise JavaBeans (EJB) Lite 3.1 no yes

Java Transaction API (JTA) 1.1 no yes

Java Persistence API (JPA) 2.0 no yes

Dependency Injection for Java 1.0 no yes

Contexts and Dependency Injection for Java EE platform 1.0

no yes

Bean Validation 1.0 no yes

Managed Beans 1.0 no yes

Interceptors 1.1 no yes

In addition to the standard APIs, SAP HANA Cloud offers platform-specific services that define their own APIs that can be used from the SAP HANA Cloud SDK. The APIs of the platform-specific services are listed in the table below

API More Information

Persistence JPA and JDBC APIs [page 471]

Security Securing Applications [page 486]

Connectivity Connectivity Service API [page 401]

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 59

Page 60: Hana Cloud

API More Information

Document Document Service Concepts [page 473]

The SAP HANA Cloud SDK contains a platform API folder for compiling your Web applications. It contains the above content, that is, all standard and third-party API JARs (for legal reasons provided "as is", that is, they also have non-API content on which you should not rely) and the platform APIs of the SAP HANA Cloud services.

You can add additional (pure Java) application programming frameworks or libraries and use them in your applications. For example, you can include Spring Framework in the application (in its application archive) and use it in the application. In such cases, the application should handle all dependencies to such additional frameworks or libraries and you should take care for the whole assembly of such additional frameworks or libraries inside the application itself.

SAP HANA Cloud also provides numerous other capabilities and APIs that might be accessible for applications. However, you should rely only on the APIs listed above.

For more information, see API Documentation.

1.3.2.2 SAP HANA Cloud Tools

Overview

SAP HANA Cloud Tools package enables you to:

● Develop and deploy Web applications● Configure connectivity destinations● View and configure logs and log files● Manage user roles and groups● Profile Web applications locally● Build and adapt Web applications using SAPUI5

Features

You can download SAP HANA Cloud Tools from the SAP Development Tools for Eclipse page. The toolkit package contains:

● SAP HANA Cloud Tools for Java● SAP JVM Profiler● UI development toolkit for HTML5 (Developer Edition)● Documentation for SAP HANA Cloud

Related LinksSetting Up the Tools and SDK [page 27]Updating the Tools and SDK [page 34]Configuring Destinations from the Eclipse IDE [page 307]Deploying on the Cloud from Eclipse IDE [page 535]

60P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 61: Hana Cloud

Follow the steps below to deploy an application on SAP HANA Cloud.

Profiling Applications [page 546]UI Development with SAPUI5 [page 69]

1.3.2.3 SAP HANA Cloud Console Client

SAP HANA Cloud console client enables development, deployment and configuration of an application outside the Eclipse IDE as well as continuous integration and automation tasks. The tool is part of the SDK. You can find it in the tools folder of your SDK location.

Setting up the SAP HANA Cloud Console Client

Download and configure the console client.

For more information, see Setting Up SAP HANA Cloud Console Client [page 32].

Parameters

You can define the parameters of the different commands either in a properties file, or directly in the command line.

● Properties file

A sample file example_war.properties can be found in the samples/deploy_war folder. In the file, enter your own user and account name:

################################################ # General settings - relevant for all commands # ################################################

# Your account name account=<your account>

# Application name application=<your application name>

# User for login to hana.ondemand.com. user=<user name or email>

# Host of the landscape admin server. Optional. Defaults to hana.ondemand.com. host=hana.ondemand.com

################################################################# # Deployment descriptor settings - relevant only for deployment # #################################################################

# List of file system paths to *.war files and folders containing them source=samples/deploy_war/example.war

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 61

Page 62: Hana Cloud

# The severity of the logs on the server process(es), created on the start up of the deployed component. Optional. # Defaults to debug. Can be: error|info|warn|debug. severity=error

Then execute the deployment with the following line:

neo deploy samples/deploy_war/example_war.properties

Note that you can have more than one properties file. For example, you can have a different properties file for each application or user in your account.

● Command line

You can deploy the same application as in the example above by executing the following command directly in the command line:

neo deploy --account <your account> --application <application name> --source samples/deploy_war/example.war --user <user name or email>

● Parameter priority

Argument values specified in the command line override the values specified in the properties file. For example, if you have specified account=a in the properties file and then enter account=b in the command line, the operation will take effect in account b.

● Argument Values

Since the client is executed in a console environment, not all characters can be used in arguments. There are special characters that should be quoted and escaped.

Consult your console/shell user guide on how to use special characters as command line arguments.

For example, to use argument with value abc&()[]{}^=;!'+,`~123 on Windows 7, you should quote the value and escape the ! character. Therefore you should use "abc&()[]{}^=;^!'+,`~123".

User

Instead of user name, you can use your e-mail.

Password

Do not specify your password in the properties file or as a command line argument. Enter a password only when prompted by SAP HANA Cloud console client.

For example, instead of:

neo deploy --password <mypassword > samples/deploy_war/example_war.properties

use

neo deploy samples/deploy_war/example_war.properties

62P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 63: Hana Cloud

Console Client Operations

To see a complete list of all available commands for operations you can perform with the SAP HANA Cloud console client, enter neo help in the command line.

Operations and commands Description

Deployment and lifecycle.

deploy; start; status

stop; undeploy

You can deploy an application on SAP HANA Cloud. Then, you can start the application, check its status, stop and undeploy it

Logging

list-logs; get-log

list-loggers; set-log-level

You can download and manage configuration logs.

Monitoring

list-availability-check; create-availability-check; delete-availability-check

create-jmx-check; delete-jmx-check; list-jmx-checks

list-alert-recipients; clear-alert-recipients; set-alert-recipients

To monitor the state of your application, you can configure availability checks, custom JMX checks and alert recipients.

1.3.3 Developing Applications

You can develop applications for SAP HANA Cloud just like for any application server. SAP HANA Cloud applications are based on the Java EE Web application model. You can use programming logic that is well-known to you, and benefit from the advantages of Java EE, which defines the application frontend. Inside, you can embed the usage of the services provided by the platform.

Development Environment

SAP HANA Cloud development environment is designed and built to optimize the process of development and deployment.

It includes the SAP HANA Cloud Tools for Java, which integrate the standard capabilities of Eclipse IDE with some extended features that allow you to deploy on the cloud. You can choose between two types of SAP HANA Cloud SDK for Java applications:

● SAP HANA Cloud SDK for Java Web - provides support for some of the standard Java EE APIs (Servlet, JSP, JSTL, EL)

● SAP HANA Cloud SDK for Java EE 6 Web Profile - certified to support Java EE 6 Web Profile APIs

For more information, see Development Environment [page 56]

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 63

Page 64: Hana Cloud

Create a basic application

In the Eclipse IDE, create a simple HelloWorld application with basic functional logic wrapped in a Dynamic Web Project and a Servlet. You can do this with both SDKs.

For more information, see Creating a HelloWorld Application [page 36]

Use Java EE 6 Web Profile

SAP HANA Cloud is Java EE 6 Web Profile certified so you can extend the basic functionality of your application with Java EE 6 Web Profile technologies. If you are working with the SDK for Java EE 6 Web Profile, you can equip the basic application with additional Java EE functionalities, such as EJB, CDI, JTA.

For more information, see Using Java EE 6 Web Profile [page 65]

Use services and utilities

Create a fully-fledged application benefiting from the capabilities and services provided by SAP HANA Cloud. In your application, you can choose to use:

● Authentication - by default, SAP HANA Cloud is configured to use SAP ID service as identity provider (IdP), as specified in SAML 2.0. You can configure trust to your custom IdP, to provide access to the cloud using your own user database.

● SAPUI5 - use the platform's official UI framework.● Persistence Service - provide relational persistence with JPA and JDBC via our persistence service.● Connectivity Service - use it to connect Web applications to Internet, make on-demand to on-premise

connections to Java and ABAP on-premise systems and configure destinations to send and fetch e-mail.● Document Service - use the service to store unstructured or semistructured data in your application.● Logging - implement a logging API if you want to have logs produced at runtime.

Deploy

First, deploy and test the ready application on the local runtime and then make it available on SAP HANA Cloud.

For more information, see Deploying Applications [page 532]

Manage

Manage all applications deployed in your account from a single dedicated user interface - SAP HANA Cloud cockpit.

For more information, see SAP HANA Cloud Cockpit [page 50]

64P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 65: Hana Cloud

Monitor

Configure checks and monitor the state of your applications.

For more information, see Monitoring Applications [page 558]

1.3.3.1 Using Java EE 6 Web Profile

SAP HANA Cloud is certified to support the Java EE 6 Web Profile. If you want to use the Java EE 6 Web Profile in your applications, you have to develop them using the SAP HANA Cloud SDK for Java EE 6 Web Profile.

Prerequisites

● You have downloaded the SAP HANA Cloud Tools. Make sure you download the SDK for Java EE 6 Web Profile.For more information, see Setting Up the Tools and SDK.

● If you have a previously installed version of the SAP HANA Cloud Tools, make sure you update them to the latest version.For more information, see Updating the Tools and SDK.

Procedure

First, create a basic HelloWorld application.

Then, equip the simple application with additional Java EE functionalities.

Create a Dynamic Web project

1. From the Eclipse IDE main menu, choose File New Dynamic Web Project .2. In the Project name field, enter HelloWorld.3. Leave the default value in the Target runtime field, that is SAP HANA Cloud.4. For Web module version, choose 3.0.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 65

Page 66: Hana Cloud

5. In the Configuration area, leave the default configuration. When you are working with the SDK for Java EE 6 Web Profile, your application is provisioned on Java 7 by default.

6. Choose Finish.

For more information, see Creating a HelloWorld Application [page 36] .

66P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 67: Hana Cloud

Create a servlet

1. On the HelloWorld project node, open the context menu and choose New Servlet . Window Create Servlet opens.

2. Enter hello as the Java package and HelloWorldServlet as the class name. Choose Next.3. In the URL mappings field, select /HelloWorldServlet and choose Edit.4. In the Pattern field, replace the current value with just "/" and choose OK. In this way, the servlet will be

mapped as a welcome page for the application.

5. Choose Finish to generate the servlet. The Java Editor with the HelloWorldServlet opens.6. Change the doGet(…) method so that it contains:

response.getWriter().println("Hello World!");

7. Save your changes.

For more information, see Creating a HelloWorld Application [page 36].

Create a JSP

1. On the HelloWorld project node, open the context menu and choose New JSP file . Window New JSP file opens.

2. Enter the name of your JSP file and choose Finish.

Create an EJB business method

EJB components represent the business logic in a Java EE application.

1. On the HelloWorld project node, choose File New Other EJB Session Bean . Choose Next.2. In the Create EJB session bean wizard, define the Java package and name of your new class. Choose Finish.3. Implement a simple public method sayHello that returns a greeting string. Save the project.

package test;

import javax.ejb.LocalBean;import javax.ejb.Stateless;

/** * Session Bean implementation class HelloWorldBean */@Stateless

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 67

Page 68: Hana Cloud

@LocalBeanpublic class HelloWorldBean {

/** * Default constructor. */ public HelloWorldBean() { // TODO Auto-generated constructor stub } public String sayHello() { return "Hello from session bean"; }

}

Call the EJB from the Servlet

1. Create a reference from the servlet to the session bean:

@EJBprivate HelloWorldBean helloWorldBean;

2. Change the doGet method to call the business method:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.getWriter().println(helloWorldBean.sayHello());

Call the EJB from the JSP

1. Create imports to the bean class and EJB API.2. Look up the HelloWorldBean using JNDI.3. Call the HelloWorldBean business method using a JNDI lookup.

Your modified JSP should look like this:

<%@page import="javax.naming.InitialContext"%><%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><%@ page import = "test.HelloWorldBean" %><%@ page import = "javax.ejb.EJB" %><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Insert title here</title></head>

<body>

</body>

68P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 69: Hana Cloud

</html><%

try { InitialContext ic = new InitialContext(); HelloWorldBean h= (HelloWorldBean)ic.lookup("java:comp/env/<HelloWorldBean_Lookup_String>"); out.println(h.sayHello()); } catch(Exception e) { out.println("error at client"); }

%>

You can test the application on the local runtime and then deploy it on SAP HANA Cloud.

For more information, see Deploying an Application on SAP HANA Cloud.

You can now use JPA together with EJB to persist data in your application

For more information, see Adding Container-Managed Persistence with JPA (SDK 2.x) [page 411]

1.3.4 UI Development with SAPUI5

Overview

UI development toolkit for HTML5 (SAPUI5) is a user interface technology that is used to build and adapt client applications based on SAP HANA Cloud.

The SAPUI5 runtime is a client-side HTML5 rendering library with a rich set of UI controls for building as welldesktop as mobile applications. To support you in developing applications, SAPUI5 tools comes with a set of eclipse-based wizards and editors. They provide wizards to create application projects and views according to the model-view-controller concept and other features like JavaScript code completion, templates and snippets and in-place application preview.

SAPUI5 provides many features to enable you to easily create and extend state-of-the-art user interfaces:

● It supports RIA like client-side features based on JavaScript.● It supports CSS3, which allows you to adapt themes to your company's branding in an effective manner.● It is based on an extensibility concept regarding custom controls. You can extend existing SAPUI5 controls as

well as develop own new controls.● It uses the open source jQuery library as a foundation.● It fully supports SAP Product standards.● It complies to OpenAjax and can be used together with standard JavaScript libraries.● It is produced in a release independent code line to enable short shipment cycles.

SAPUI5 SDK

The SDK - also called Demo Kit - provides the following sections:

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 69

Page 70: Hana Cloud

● Controls containing running demo examples with descriptions and source codes● API Reference with JavaScript documentation of Framework and Control API● Test Suite which shows all controls running with different property settings where you can interactively adapt

the controls you use for your test purpose.

To directly access the Demo Kit: https://sapui5.hana.ondemand.com/sdk/

Related LinksGetting Started with SAPUI5 [page 70]When having installed SAP HANA Cloud Tools, SAPUI5 runtime and tools are included and ready to run. Here you find information on how to adjust your enviroment and to get started with some easy examples including an introduction to the SAPUI5 tools.

1.3.4.1 Getting Started with SAPUI5

When having installed SAP HANA Cloud Tools, SAPUI5 runtime and tools are included and ready to run. Here you find information on how to adjust your enviroment and to get started with some easy examples including an introduction to the SAPUI5 tools.

Choose your browser

Before you really get started, check the list of supported browsers to choose one that fits your needs.

Browser Support: SAPUI5 for Desktop [page 71]

Browser Support: SAPUI5 for Mobile [page 77]

To get started with SAPUI5, you now have two different options: Either you just create an HTML page (even with notepad, if you want to) or you start directly using the SAPUI5 tools in Eclipse.

Creating Simple SAPUI5 Applications

The easiest way to work with SAPUI5 is to include a set of JavaScript libraries into your HTML page. You declare the list of used UI libraries when including the framework's bootstrap script. After that, you can use all controls provided by these libraries to construct one or more control trees and connect these to the different parts of your HTML page. You program against a well-designed control API, mostly calling setters for properties and aggregations and managing event subscriptions. The framework also supports the JavaScript Object Notation (JSON) to initialize controls with a reduced typing effort. Within an event handler, you may want to retrieve control instances by ID and use getters for properties. Of course, you are free to modify a control's state from within an event handler. Re-rendering will be done automatically by the framework.

Create Your First SAPUI5 Application [page 85]

When you develop mobile apps, there are some slight differences: Create your First Mobile App using SAPUI5 [page 79]

70P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 71: Hana Cloud

Create applications using SAPUI5 tools

Using the SAPUI5 application tools in Eclipse allows you to create sophisticated SAPUI5 application projects based on the Model View Controller concept. The tools provide additional features such as SAPUI5 Snippets or JavaScript Templates.

Develop Your First Application using SAPUI5 Tools [page 89]

Running your SAPUI5 applications

Running a SAPUI5 application [page 110]

1.3.4.1.1 Choose Your Browser

You need to check which browser suits best to your use case.

Supported Browsers

For displaying Mobile apps for testing purposes locally on your Desktop computer, you need a WebKit based browser such as Google Chrome.

Related LinksBrowser Support: SAPUI5 for Desktop [page 71]As the UI development toolkit for HTML5 (SAPUI5) is a control library that depends on the availability of CSS3, HTML5, new JavaScript API and JavaScript speed, mainly the HTML5 capable browsers are supported.

Browser Support: SAPUI5 for Mobile [page 77]

Browser Support: SAPUI5 for Desktop

As the UI development toolkit for HTML5 (SAPUI5) is a control library that depends on the availability of CSS3, HTML5, new JavaScript API and JavaScript speed, mainly the HTML5 capable browsers are supported.

Browser Support for Core and Standard Libraries

NoteAlso refer to SAP Note 1716423

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 71

Page 72: Hana Cloud

Supported Browsers

The following browsers are supported for Microsoft Windows platforms only:

● Microsoft Internet Explorer 9 and upwards, so including Microsoft Internet Explorer 10● Mozilla Firefox 10 (aka Firefox Extended Support Release - ESR) and latest version● Chrome latest version

The following browser is only supported for MAC OS X:

● Safari 5.1 and upwards

Browsers with Restricted Support

Internet Explorer 8 (IE8): There are degradations in visual design and over time also restricted functionality. So far, there is no functional restriction but when HTML5 features are added to SAPUI5 which are not available in IE8, there is not necessarily an alternative solution created by the SAPUI5 teams.

For more information, see

● Degradations by Feature.● Degradations by Control [page 75]

Not supported Browsers

Internet Explorer 6 and 7 are not supported. All browsers not mentioned above are also not supported.

Browser Support Policies of the Respective Vendors

● Internet Explorer (IE)In general, IE is seen as a "component" of a "parent major product" = Windows. Every IE version is supported on a particular Windows version for as long as the Windows version is supported. Explanation: "Internet Explorer is considered as a component of the operating system (OS) for which it was released. The support timelines for IE are inherited from the OS and its associated service packs. Basically, this means that the versions of Internet Explorer that shipped for a specific OS or service pack will be supported with the support lifecycle of the OS or service pack. Support for older versions of IE will not end unless we ship a replacement version of IE in a future OS service pack....As per the policy, we will not end support previous versions of Internet Explorer on supported operating system versions." (see http://blogs.technet.com/b/lifecycle/archive/2009/06/27/the-support-lifecycle-for-internet-explorer.aspx).IE6 support is coupled with the XP lifetime even though Microsoft strongly encourages users to switch to newer browsers.

● FirefoxSAPUI5 supports Extended Support Release (ESR) and the current version.Firefox ESR can be downloaded but it "will be maintained with security and stability updates" only. Features and performance updates will take more time to get into ESR version.

72P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 73: Hana Cloud

● Safari: Apple doesn't seem to issue any information which browser version is supported until when.There is a concept of vintage products that have been discontinued more than 7 years ago, but this refers to hardware and not softwareThe assumption is that Apple only really supports the last version of their browser

Browser Support for VIZ Charting

The VIZ charting library (sap.viz) relies on the open source component D3 which in turn relies on the availability of Scalable Vector Graphics (SVG). As SVG is not supported by IE8 and not fully supported by FF ESR, the VIZ charting library is also not supported on those browsers.

Degradations by Feature

The following sections describe the degradations for older Browser versions, such as FireFox 3.6 or Internet Explorer 8 (IE8).

Rounded Corners

IE8 and lower versions of IE do not support the CSS property border-radius. As a result, controls in themes that use this property have square corners instead of rounded corners.

In the UX theme this affects the following controls:

● Button● ComboBox● DatePicker and its popup● DropdownBox● ListBox● MessageBar● Panel● ProgressIndicator● TextArea● TextField

Button in FireFox 3.6 Button in Internet Explorer 8

Box Shadow

IE 8 and lower versions of IE do not support the CSS property box-shadow. As a result, controls in themes that use this property do not have a shadow. This property is usually used to either enhance a 3D effect, for example, along vertical edges or to drop a shadow for a box "floating" above other content, which is used for all kinds of popup windows.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 73

Page 74: Hana Cloud

In the UX theme, this affects the following controls:

● Button(3D)● ComboBox(Popup)● DatePicker(Popup)● DropdownBox(Popup)● Menu(Popup)● MenuButton(Popup)● MessageBar(+Popup)● ProgressIndicator(3D)● RichTooltip● TextArea(3D)● TextField(3D)● Toolbar(OverflowMenu)

ComboBox in FireFox 3.6 ComboBox in Internet Explorer 8

Background Size

IE 8 and lower versions of IE do not support the property background-size which allows to stretch a background image or gradient.

This affects the Button control.

Button in FireFox 3.6 Button in Internet Explorer 8

Gradient Backgrounds

IE8 only supports gradients in a limited way, so some gradients may be missing.

This affects tables. In the example, compare the table header and row selectors.

74P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 75: Hana Cloud

Gradient Background in FireFox 3.6 Gradient Background in Internet Explorer 8

Native Scrollbars

For native scrollbars, see the ComboBox example in the Box Shadow section.Degradations by Control

The following table gives an overview of degradations.

Control Corners Shadow BG Size Gradients Scrollbars Degradation in IE8

Accordion

Button X X X No rounded corners, vertical edges without 3D effect and background has no scale when button size differs from default height

CheckBox

ComboBox X X X No rounded corners, no 3D effect for vertical edges and popup has no shadow

DatePicker X X X No rounded corners, no 3D effect for vertical edges and popup has no shadow

Dialog X Native scrollbars

DropdownBox X X X No rounded corners, no 3D

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 75

Page 76: Hana Cloud

Control Corners Shadow BG Size Gradients Scrollbars Degradation in IE8

effect for vertical edges and popup has no shadow

FileUploader X X Inherited from the components used (InputField and Button)

HorizontalDivider

Image

Label

Link

ListBox X X X No rounded corners, no 3D effect for vertical edges

Menu X Popup without shadow

MenuButton X X X No rounded corners, vertical edges without 3D effect, background does not scale when button size differs from default height, popup without shadow

MenuBar X Menu items without rounded corners

MessageBar X X No rounded corners, no shadow, message list popup without shadow

MessageBox

Panel X Native scrollbars

ProgressIndicator

X X No rounded corners, vertical

76P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 77: Hana Cloud

Control Corners Shadow BG Size Gradients Scrollbars Degradation in IE8

edges without 3D effect

RadioButton

RichTooltip X X No shadow; if it had a shadow, the shadow would not have rounded corners

RoadMap?

Slider

Splitter

Table X X Native scrollbars, headers/line markers only show 2-colors instead of gradient

TabStrip?

TextArea X X X No rounded corners, vertical edges without 3D effect

TextField X X No rounded corners, vertical edges without 3D effect

TextView

Toolbar X Overflow menu without shadow

Browser Support: SAPUI5 for Mobile

The following tables give an overview of the platforms supported by the sap.m library of SAPUI5 for Mobile.

NoteThe sap.makit library supports the same platforms excluding BlackBerry 10.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 77

Page 78: Hana Cloud

iOS

Table 1: iOS is supported as of platform version 5

Browser Safari Web View Chrome Opera Mini

Supported Yes Yes No No

Theme iOS iOS - -

Android

Table 2: Android is supported as of platform version 5

Browser Safari Web View Chrome Opera Mini

Supported Yes Yes No No

Theme Android Android - -

BlackBerry

,

Table 3: Blackberry is supported as of platform version 10

Browser BlackBerry Browser Web View Opera Mini

Supported Yes Yes No

Theme Android Android -

Windows Mobile

Windows Mobile is not supported

Desktop

SAPUI5 for Mobile is not supported on the Desktop. Only for development scenarios Safari and Google Chrome are enabled, with either Android or iOS, depending on your configuration.

78P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 79: Hana Cloud

1.3.4.1.2 Create your First Mobile App using SAPUI5

Whether you develop a SAPUI5 application for desktop or for mobile, the concepts are very similar. SAPUI5 provides an additional control library called sap.m, which is optimized for mobile devices.

The sap.m library provides:

● It has a focus on touch interactions.● It provides a mobile-style theme, which makes users feel comfortable on both, Android and Apple devices.● It uses the most advanced features of the browsers available on modern smart phones and tablets.

NoteThe sap.m mobile library is optimized for mobile browsers based on WebKit. Currently, the library does not run properly on other browsers, such as Microsoft Internet Explorer and Mozilla Firefox. Therefore we recommend to use Google Chrome or Apple Safari for tests on desktop PCs.

Also, the mobile library only uses touch events and deduces its appearance from the platform it is running on. For tests with Chrome or Safari on desktop PCs, you therefore need the to set one of the following URL parameters:

● sap-ui-xx-fakeOS=android● sap-ui-xx-fakeOS=ios● sap-ui-xx-fakeOS=blackberry ● sap-ui-xx-fakeOS=winphone

The URL parameter suggests to emulate touch events from mouse events and to apply the styles for either Android, iOS, BlackBerry of Windows Phone. You can also add this parameter as data-sap-ui-xx-fakeOS attribute to the bootstrap script tag.

Related LinksCreate a HTML Page for Your Mobile App [page 79]You first create a HTML page and define the meta tags, a script tag to load the SAPUI5 libraries and a placeholder for your mobile app.

Initialize the Mobile App [page 81]The sap.m library provides a control called App which is meant to be the root control of a mobile application. It provides the initialization of the HTML page, sets some meta tags to ensure an as-native-as-possible look&feel, and can manage different pages and the animations between them.

Add Content Pages [page 81]Typical mobile applications are often composed of a number of pages/views/screens between which the user can navigate. You now add two of them to your app.

Run Your First Mobile App [page 82]To test a mobile app on your Desktop, you have to ensure some prerequisites.

Create a HTML Page for Your Mobile App

You first create a HTML page and define the meta tags, a script tag to load the SAPUI5 libraries and a placeholder for your mobile app.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 79

Page 80: Hana Cloud

Procedure

1. Create a HTML page called mobile.html2. Add the HTML5 doctype definition: <!DOCTYPE html>" in the first line and the Internet Explorer-specific

meta tag :<meta http-equiv="X-UA-Compatible" content="IE=edge" />" are the beginning of <head> element.

This ensures that all browsers use the latest version of their rendering engine. Although Microsoft Internet Explorer is not really used widely on mobile devices and not yet supported by the SAPUI5 mobile library, this meta tag makes the page more future-proof.

3. Add a second meta tag: <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>.

This lets all browsers treat the file as UTF-8 encoded (assuming that you use this encoding when editing/saving the file)

4. Add a <div> element to <body>.

5. The "sapUiBody" class should always be added to the <body> tag to initialize font and colors for the whole page:

<body class="sapUiBody"> <!-- This is where the App will live: --> <div id="content"></div></body>

6. To load the SAPUI5 JavaScript file, that contains the library, add the following script tag in the <head>:

<script src= "http://<http://<server>:<port>/sapui5/resources/sap-ui-core.js" id= "sap-ui-bootstrap" data-sap-ui-libs= "sap.m" data-sap-ui-theme= "sap_mvi"> </script>

Note that you are only loading the "sap.m" control library and the "sap_mvi" theme. mvi stands for Mobile Visual Identity and is the name of the SAP Mobile design.

7. Replace <server> and <port> with your local SAPUI5 installation or point to the SAPUI5 libraries on SAP HANA Cloud: https://sapui5.hana.ondemand.com/resources/sap-ui-core.js

Results

At this point, SAPUI5 including the mobile controls is loaded and ready to use.

Next Steps

Initialize the Mobile App [page 81]

80P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 81: Hana Cloud

Initialize the Mobile App

The sap.m library provides a control called App which is meant to be the root control of a mobile application. It provides the initialization of the HTML page, sets some meta tags to ensure an as-native-as-possible look&feel, and can manage different pages and the animations between them.

Procedure

Create the control and define the page that you want to display first:

// create a mobile App // it initializes the HTML page for mobile use and provides animated page handling var app = new sap.m.App("myApp", {initialPage:"page1"}); // page1 should be displayed first

○ Instead of using the App control, you can also use jQuery.sap.initMobile() to set up the HTML and use other full screen controls, such as sap.m.Page or sap.m.Carousel as root element of your app.

Add Content Pages

Typical mobile applications are often composed of a number of pages/views/screens between which the user can navigate. You now add two of them to your app.

Procedure

1. One sap.m.Page control is created, its title is set and the content is just one button:

// create the first page of your applicationvar page1 = new sap.m.Page("page1", { title: "Initial Page", content : new sap.m.Button({ // content is just one Button text : "Go to Page 2", tap : function() { app.to("page2"); // when tapped, it triggers drilldown to page 2 } })});

When the Button is pressed, it triggers a drilldown navigation by calling app.to("page2"), where page2 is the ID of the second page. You could also give the animation type. The default is a slide animation from right to left.

sap.m.Page controls can be used as pages, and the aggregation is called pages, but other controls could be used as well.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 81

Page 82: Hana Cloud

2. Add the following to the <script> seciton of the HTML page below the part, where you've initialized the app:

// create the second page of your applicationvar page2 = new sap.m.Page("page2", { title: "Page 2", showNavButton: true, // page 2 should display a back button navButtonTap: function(){ app.back(); // when tapped, the back button should navigate back up to page 1 }, icon: "http://www.sap.com/global/ui/images/global/sap-logo.png", content : new sap.m.Text({text:"Hello Mobile World!"})});

showNavButton is set to true to get a Back button displayed. When this button is triggered, the handler calls app.back(). This causes an inverse animation, which leads back to the main page.

A header icon, which is only visible on Android, and "Hello Mobile World" content is also given.3. Finally, add the two pages to the App:

// add both pages to the Appapp.addPage(page1).addPage(page2);

The app is placed into the HTML like a SAPUI5 desktop control. The App takes care to cover the whole screen.

Next Steps

Run Your First Mobile App [page 82]

Run Your First Mobile App

To test a mobile app on your Desktop, you have to ensure some prerequisites.

Prerequisites

Your operating system is Microsoft Windows and you use a current WebKit-based browser (Google Chrome or Apple Safari). Other operating systems work as well, but the procedure may differ. Also, the mobile library is currently not optimized for Mozilla Firefox and Microsoft Internet Explorer.

NoteThe URL in the script tag is pre-filled as https://sapui5.hana.ondemand.com/resources/sap-ui-core.js. This is the URL where the resources are located in the SAP HANA Cloud delivery. Test this URL first and if it does not work, replace this URL with the location of SAPUI5 on your local server.

82P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 83: Hana Cloud

Also note that the version of SAPUI5 deployed on https://sapui5.hana.ondemand.com/ may be updated with a delay of some days or weeks after a new release of SAPUI5, even though we try to keep them in sync. This example will work nevertheless.

Procedure

1. Right-click on your desktop and choose New Text Document .2. Enter a name for the new file, for example "mobile.html", and confirm the extension change warning.3. Right-click on the new file and choose Edit. Make sure it opens in Notepad and not in MS Word.4. Copy and paste the HTML code below and save the file. Keep in mind that the SAPUI5 URL may need to be

adapted.5. Drag and drop the file into the browser window.6. To load the example on a mobile device, you put the file on a server.7. To play around with the app in your desktop browser, add the following URL parameter to the file URL: sap-

ui-xx-fakeOS=ios, so that the URL reads : "mobile.html?sap-ui-xx-fakeOS=ios". This enables the simulation of touch events on desktop PCs. This also enables the iPhone/iPad styling; if you want to see the Android styling, use sap-ui-xx-fakeOS=android instead.

<!DOCTYPE HTML><html> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>

<title>Mobile App in 23 Seconds Example</title>

<script src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js" id="sap-ui-bootstrap" data-sap-ui-libs="sap.m" data-sap-ui-theme="sap_mvi"> </script> <!-- only load the mobile lib "sap.m" and the "sap_mvi" theme -->

<script>

// create a mobile App // it initializes the HTML page for mobile use and provides animated page handling var app = new sap.m.App("myApp", {initialPage:"page1"}); // page1 should be displayed first

// create the first page of your application var page1 = new sap.m.Page("page1", { title: "Initial Page", content : new sap.m.Button({ // content is just one Button text : "Go to Page 2", tap : function() { app.to("page2"); // when tapped, it triggers drilldown to page 2 } }) });

// create the second page of your application

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 83

Page 84: Hana Cloud

var page2 = new sap.m.Page("page2", { title: "Page 2", showNavButton: true, // page 2 should display a back button navButtonTap: function(){ app.back(); // when tapped, the back button should navigate back up to page 1 }, icon: "http://www.sap.com/global/ui/images/global/sap-logo.png", content : new sap.m.Text({text:"Hello Mobile World!"}) });

app.addPage(page1).addPage(page2); // add both pages to the App

app.placeAt("content"); // place the App into the HTML document

</script>

</head> <body class="sapUiBody"> <div id="content"></div> </body></html>

Results

You should now see the following mobile App on iOS:

And the following mobile App on Android:

84P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 85: Hana Cloud

If you have set the sap-ui-xx-fakeOS URL parameter, you can navigate to the second page by clicking the button.

To open the application on a real mobile device, you can also put the HTML document on a Web server and load the resulting URL in your mobile browser.

1.3.4.1.3 Create Your First SAPUI5 Application

You can include a bootstrap to the SAPUI5 JavaScript libraries to use SAPUI5 in an HTML page without having set up the SAPUI5 application development tools in Eclipse.

This page explains how to create and run a simple SAPUI5 application from scratch within twenty seconds (with some practice… the current record is 16 seconds).

If you are interested in exactly doing this without reading too much, you can skip the background information and read the And how to do it in 20 Seconds section below.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 85

Page 86: Hana Cloud

Background Information

As SAPUI5 is a client-side web UI library meaning that it runs in a browser, a SAPUI5 application typically is an HTML page and, if required, many more files.

SAPUI5 is implemented in JavaScript, so for loading SAPUI5, its bootstrap just needs to be included with a <script> tag. The last two attributes select the visual design to apply initially (other choices would be sap_hcb or sap_platinum) and the SAPUI5 control library/libraries to use (sap.ui.dev would be another one). In your scenario you need to make sure the URL points to a SAPUI5 installation.

<script id="sap-ui-bootstrap" src="resources/sap-ui-core.js" data-sap-ui-theme="sap_goldreflection" data-sap-ui-libs="sap.ui.commons"></script>

SAPUI5 UI elements are created and modified programmatically:

// create the button instancevar myButton = new sap.ui.commons.Button("btn");

// set properties, e.g. the text (there is also a shorter way of setting several properties)myButton.setText("Hello World!");

// attach an action to the button's "press" event (use jQuery to fade out the button)myButton.attachPress(function(){$("#btn").fadeOut()});

There is also a shorthand notation based on JSON for setting multiple properties; you could also write:

var myButton = new sap.ui.commons.Button({text:"Hello World!",tooltip:"Hello Tooltip!"});

Finally you need to tell SAPUI5 where the UI control should be placed. You can just give the ID of an element in the page to do so:

// place the button into the HTML element defined belowmyButton.placeAt("uiArea");

This element must exist somewhere in the HTML page, so you need to put the following code to the desired place within the <body>:

<div id="uiArea"</div>

Currently, you can only put one SAPUI5 control into a parent; for adding more SAPUI5 controls you need to either define more parents, or use a SAPUI5 layout control which can arrange many children.

An alternative way to create and initialize the control in a more jQuery-style manner is also available:

$(function(){ $("#uiArea").sapui("Button", "btn", { text:"Hello World!", press:function(){$("#btn").fadeOut();} }); });

86P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 87: Hana Cloud

As a minor detail, the <body> should have a certain CSS class, so the page background and some other styles are properly set:

<body class="sapUiBody">

There are two meta tags at the beginning of the <head>: The first meta tag is used to ensure that Internet Explorer 8+ uses its most standard-compliant rendering mode. The second meta tag is used to let all browsers treat the file as UTF-8 encoded (assuming that you use this encoding when editing/saving the file):

<meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>

And How to do it in 20 Seconds

Assumption for these instructions to work exactly as described: You have a Windows Computer (other OS will work similarly), Internet Explorer 9+ with security option set to Access data across domains for the respective zone, FireFox 13+, Safari 5+ or Chrome 20+, and you know where you can refer to SAPUI5 on some server.

NoteThe URL in the script tag is pre-filled as https://sapui5.hana.ondemand.com/resources/sap-ui-core.js. This is the URL where the resources are located in the SAP HANA Cloud delivery. Test this URL first and if it does not work, replace this URL with the location of SAPUI5 on your local server.

Also note that the version of SAPUI5 deployed on https://sapui5.hana.ondemand.com/ may be updated with a delay of some days or weeks after a new release of SAPUI5, even though we try to keep them in sync. This example will work nevertheless.

Proceed as follows:

1. Right click your desktop and select New Text Document .2. Name the new file, for example "ui5.html", and accept the extension change warning.3. Right click the new file and select Edit. Make sure that the file opens in Notepad and not in MS Word.4. Copy and paste the below HTML code. Keep in mind to adapt the SAPUI5 URL5. Drag the file to the browser window.6. That was it.

<!DOCTYPE html><html><head> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> <title>SAPUI5 in 20 Seconds</title>

<!-- 1.) Load SAPUI5 (from a remote server), select theme and control library --> <script id="sap-ui-bootstrap" src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js" data-sap-ui-theme="sap_goldreflection" data-sap-ui-libs="sap.ui.commons"></script>

<!-- 2.) Create a UI5 button and place it onto the page --> <script>

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 87

Page 88: Hana Cloud

// create the button instance var myButton = new sap.ui.commons.Button("btn");

// set properties, e.g. the text (there is also a shorter way of setting several properties) myButton.setText("Hello World!");

// attach an action to the button's "press" event (use jQuery to fade out the button) myButton.attachPress(function(){$("#btn").fadeOut()});

// place the button into the HTML element defined below myButton.placeAt("uiArea");

// an alternative, more jQuery-like notation for the same is: /* $(function(){ $("#uiArea").sapui("Button", "btn", { text:"Hello World!", press:function(){$("#btn").fadeOut();} }); }); */ </script>

</head><body class="sapUiBody">

<!-- This is where you place the UI5 button --> <div id="uiArea"></div></body></html>

Result

If you followed the steps above you should now see a button like this which fades out when clicked:

Next Steps

You can now do the following:

● Add more buttons.● Let them do trickier things.● Use a different visual theme as mentioned above, for example sap_ux

88P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 89: Hana Cloud

● Find out about further properties and events of button controls and use those.● Find out about further controls and add those. For more information, see the Controls Gallery in the Demo Kit.

1.3.4.1.4 Develop Your First Application using SAPUI5 Tools

The SAPUI5 application development tools in Eclipse support you in developing web applications according to MVC.

The SAPUI5 application development tools for Eclipse provide wizards and support for creating SAPUI5 applications in an easy way. With the SAPUI5 application project wizard, the necessary application skeleton containing view(s) and controller will automatically be created.

Creating SAPUI5 applications

The SAPUI5 tools support you in creating applications according to MVC. In this section we guide you through a simple example. You will include a control, implement a method in the controller and add an additional view.

More Information

Create an SAPUI5 Application Project [page 90]

Implement a Control [page 94]

Implement a Method in the Controller [page 95]

Utilities

With Eclipse you can make use of utilities for JavaScript development and in addition SAPUI5 provides templates and snippets.

● JavaScript Code CompletionThe Eclipse JavaScript Development Tools (JSDT) provide an editor which parses scripts and offers a code completion functionality. If you have created your SAPUI5 application with SAPUI5 application development tools, the core libraries for the code completion are made available automatically.

NoteIf your Eclipse installation contains the org.eclipse.wst.jsdt.feature feature in Version 1.3.1, we recommend to update it. Invoking the JavaScript code completion in version 1.3.1 may cause Eclipse to crash.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 89

Page 90: Hana Cloud

More Information

JavaScript Code Completion [page 99]

Use JavaScript Templates [page 101]

SAPUI5 Snippets [page 103]

Create an SAPUI5 Application Project

Context

To create a SAPUI5 Application Project, you must have installed the SAPUI5 Application Development feature in your Eclipse installation.

Procedure

1. Start the New SAPUI5 Application Project wizard in the Eclipse IDE by choosing New Other ... SAPUI5 Application Development Application Project .

90P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 91: Hana Cloud

2. Enter the following project-related data:

○ Project name○ Location (optional, prefilled from the current workspace)○ Target device: 'Desktop' or 'Mobile'○ Indicate, whether an initial view shall be created, or not; a view can be added later via the SAPUI5

Application View wizard

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 91

Page 92: Hana Cloud

3. If applicable: Enter the following view-related data:

○ Folder in which view shall be created○ View name○ Development paradigm, that is, JavaScript, XML, HTML or JSON, see View Types

4. If applicable: Check and confirm the confirmation page. Before finishing the wizard, the summary information about selected data in previous pages is displayed. With Back you can change the data before the application

92P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 93: Hana Cloud

project is created.

Results

After finishing the wizard, the system performs the following steps:

● A new dynamic web project is created. All relevant files are created in the WebContent folder.● A prefilled index.html is created which contains sap.ui.commons lib and sap_goldreflection theme in

the boostrap in case of a desktop target device and the sap.m lib and sap_mvi theme in case of mobile target device.

● A web.xml file is created which contains settings for Resource Handling and Testing a SAPUI5 Application in Eclipse; the use of SimpleProxyServlet is restricted to localhost and only intended for testing purposes and not for productive use.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 93

Page 94: Hana Cloud

● The installed SAPUI5 UI lib plugins are automatically added to the Java build path and added to the deployment assembly.

● The SAPUI5 class path container (if available) is automatically added to the JavaScript include path.● The index.html page is opened in the standard editor.● Inside the JavaScript block of index.html, code completion is available, see JavaScript Code Completion.● An automatic switch to the J2EE perspective is performed.● If you have selected the Create an Initial View option on the first page of the SAPUI5 Application Project

wizard, a view and a view controller are created and the coding to call the view is added to the index.html file. I you have selected a mobile target device, a special coding instantiating is generated, see Best Practice for Building Mobile Applications.

Next Steps

Implement a Control [page 94]

Implement a Method in the Controller [page 95]

Create an Additional View [page 96]

Integrate a New View [page 98]

Related LinksJavaScript Code Completion [page 99]The Eclipse JavaScript Development Tools (JSDT) provide an editor which parses scripts and offers a code completion functionality. When using the SAPUI5 tools, this function is enabled automatically, without the tools, you need to enable it.

Use JavaScript Templates [page 101]You can add SAPUI5 control-specific templates for JavaScript code. Such templates are available, for example, in JavaScript views of SAPUI5 application tools development. They are generated during startup of the Eclipse runtime.

SAPUI5 Snippets [page 103]

Implement a Control

In your SAPUI5 application project, the first step to build your application is to add a control to your view and implement a method to react on user interaction. In this case you create a button and implement a function to react when the user presses it.

Procedure

To add a control to your view, add the following coding depending on the type of your view:

94P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 95: Hana Cloud

○ In a JS view add the following to the createContent function

var aControls = []; var oButton = new sap.ui.commons.Button({ id : this.createId("MyButton"), text : "Hello JS View" }); aControls.push(oButton.attachPress(oController.doIt)); return aControls;

○ In an HTML view add the following to the template tag:

<div data-sap-ui-type="sap.ui.commons.Button" id="MyButton" data-text="Hello HTML View" data-press="doIt"></div>

○ In an XML view add the following coding to the core tag

<Button id="MyButton" text="Hello XML View" press="doIt"/>

○ In a JSON view add the following to the content function

"Type":"sap.ui.commons.Button", "id":"MyButton", "text":"Hello JSON View", "press":"doIt"

A button is added to your view with an event that is triggered when the user presses it.

Next Steps

The doIt method, which is called in each of these view types, is implemented in the controller:

Implement a Method in the Controller [page 95]

Implement a Method in the Controller

All functions that are not directly related to the user interface should be handled in the controller to ensure clear separation between UI and data. In this case you add a method to handle the event, which is attached to a button.

Prerequisites

You've created a button as described in: Implement a Control [page 94]

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 95

Page 96: Hana Cloud

Procedure

To handle this event, add the following function to the controller:

doIt : function(oEvent) { alert(oEvent.getSource().getId() + " does it!"); }

Create an Additional View

Context

● A SAPUI5 application view can only be created for a SAPUI5 application project that has been created with the SAPUI5 Application Wizard and not for other kinds of projects.

● A SAPUI5 application view name needs to be unique inside the project folder.● If a SAPUI5 application view if positioned on a project, the project is set as default for the view if it is a SAPUI5

application project. If a SAPUI5 application view is positioned on a folder, the folder's project is set as default for the view if it is a SAPUI5 Application Project and the folder is set as default. In other cases, the WebContent/<application name> folder is set as default.

● The specified folder for a SAPUI5 application view needs to be WebContent/<application name> or a sub folder.

Procedure

1. Choose New Other... SAPUI5 Application Development View to open the New SAPUI5 Application

View wizard.

96P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 97: Hana Cloud

2. Fill in the required data:

○ Select the SAPUI5 application project, in which you want to create the view.○ Select a folder, in which you want to store the view (default is WebContent/<application name>).○ Enter a name for the view.○ Select the development paradigm, see View Types.

Results

When you finish the wizard, the system creates the view in the specified folder. The file name suffix indicates the development paradigm:

● <viewname>.view.js for JavaScript views● <viewname>.view.xml for XML views● <viewname>.view.json for JSON views● <viewname>.view.html for HTML views

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 97

Page 98: Hana Cloud

If the corresponding index.html file contains sap.m lib in the bootstrap, that is, if the SAPUI5 application project has been created for a mobile target device, the view contains coding for instantiating a mobile page control sap.m.Page.

The system also creates a controller file <viewname>.controller.js with draft coding. For JavaScript views, code completion is available, see JavaScript Code Completion.

NoteIf you rename the view or controller file, or move them to a different folder, the coding in the view and controller and in the places where the view is used needs to be adapted manually.

Integrate a New View

To integrate a new view, you can either add it to index.html or nest it into another view.

Prerequisites

If you create a new view for an existing SAPUI5 application project, the view needs to be manually called.

98P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 99: Hana Cloud

Procedure

To call a view, choose from the following options:

○ Directly embed the new view in the index.html page○ All Views can be nested independent of the view type. Each view type behaves like any SAPUI5 control.

The viewName property defines, which views are embedded. To nest a view, proceed according to the given examples:

For XML view type:

<core:View controllerName="sap.hcm.Address" xmlns="sap.ui.commons" xmlns:core="sap.ui.core" xmlns:html="http://www.w3.org/1999/xhtml"> <Panel> <core:JSView id="myJSView" viewName="sap.hcm.Bankaccount" /> </Panel><core:View>

For HTML views, the nested view looks as follows:

<template data-controller-name= "example.mvc.test" >

<div data-sap-ui-type= "sap.ui.core.mvc.HTMLView" id= "MyHTMLView" data-view-name= "example.mvc.test2" ></div> <div data-sap-ui-type= "sap.ui.core.mvc.JSView" id= "MyJSView" data-view-name= "example.mvc.test2" ></div> <div data-sap-ui-type= "sap.ui.core.mvc.JSONView" id= "MyJSONView" data-view-name= "example.mvc.test2" ></div> <div data-sap-ui-type= "sap.ui.core.mvc.XMLView" id= "MyXMLView" data-view-name= "example.mvc.test2" ></div>

</template>

JavaScript Code Completion

The Eclipse JavaScript Development Tools (JSDT) provide an editor which parses scripts and offers a code completion functionality. When using the SAPUI5 tools, this function is enabled automatically, without the tools, you need to enable it.

If you have installed the SAPUI5 application development tools, you can use the JavaScript code completion.

NoteIf your Eclipse installation contains the org.eclipse.wst.jsdt.feature feature in Version 1.3.1, we recommend to update it. Invoking the JavaScript code completion in version 1.3.1 may cause Eclipse to crash.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 99

Page 100: Hana Cloud

Automatic Code Completion for SAPUI5 Application Projects

The Eclipse JavaScript Development Tools (JSDT) provide an editor which parses scripts and offers a code completion functionality. If you have created your SAPUI5 application with SAPUI5 application development tools, the core libraries for the code completion are made available automatically.

Enabling Code Completion for Other Projects

If you are not working with a SAPUI5 application project, you can perform the following preparing steps to add the required SAPUI5 core libraries to the JavaScript include path.

Ensure that the JavaScript Facet is set and proceed as follows:

1. Open Project Properties .2. Select Project Facets.3. If you do not see the list of all possible facets, click the link: Convert to facet form and wait a second to see all

available facets.4. Mark JavaScript Facet on the same view.5. Leave the project properties.

Your project now has the JavaScript facet. Now you can add the SAPUI5 core libraries. Proceed as follows:

● Open Project Properties .

● Choose JavaScript Include Path .● Select Add JavaScript Library….● Select SAPUI5.

You should now be able to see the following JavaScript resources in your project:

100P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 101: Hana Cloud

Use JavaScript Templates

You can add SAPUI5 control-specific templates for JavaScript code. Such templates are available, for example, in JavaScript views of SAPUI5 application tools development. They are generated during startup of the Eclipse runtime.

Prerequisites

Context

The templates are an overview over all available

● control properties● aggregations● associations and● events

To use the JavaScript templates, the SAPUI5 application development tools feature has to be installed in your Eclipse.

Note

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 101

Page 102: Hana Cloud

If your Eclipse installation contains the feature org.eclipse.wst.jsdt.feature in Version 1.3.1, we recommend to update it. In this version, invoking the JavaScript code completion may cause Eclipse to crash.

Procedure

1. To insert a template, open the JavaScript editor.2. Start typing the name of the respective control or the name of the alias, for example button.3. Choose CRTL + SPACE and choose the control from the code completion list.

All properties and events are inserted.

102P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 103: Hana Cloud

SAPUI5 Snippets

You can add SAPUI5-specific code parts, so called SAPUI5 Snippets. Code snippets are templates and examples on how to use the SAPUI5 runtime and controls and what can be done with them. SAPUI5 snippets are available as prepared HTML pages with no separation between model, view and, controller (MVC) and they are generated during startup of the Eclipse runtime.

Before you can use the SAPUI5 snippets, the SAPUI5 application development tools must be installed in your Eclipse.

To open the Snippets view, proceed as follows:

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 103

Page 104: Hana Cloud

1. Choose Window Show View Other... .

104P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 105: Hana Cloud

2. In the Show View dialog, choose General Snippets and confirm you selection with OK.

3. The Snippet view opens.

To insert a snippet, proceed as follows:

1. Create a SAPUI5 application project, see Creating a SAPUI5 Application Project.2. Open the index.html in the HTML editor.3. Delete all content.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 105

Page 106: Hana Cloud

4. To insert the snippet code, double click on the snippet or use drag&drop.

106P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 107: Hana Cloud

5. Save the code and run it in the integrated browser.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 107

Page 108: Hana Cloud

6. If you have problems with incorrect rendered pages, open the default external browser.

108P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 109: Hana Cloud

The page should then be displayed correctly:

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 109

Page 110: Hana Cloud

1.3.4.1.5 Running a SAPUI5 application

To run your SAPUI5 application, you can test it using the local runtime or you deploy it to SAP HANA Cloud server.

110P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 111: Hana Cloud

Procedure

1. Select your SAPUI5 application project, open the context menu and choose Run... Run on Server .2. Select either your local cloud test server or the cloud server directly

○ To test your SAPUI5 application locally, choose SAP HANA Cloud local runtime○ To deploy and run your SAPUI5 application on SAP HANA Cloud, choose your server instance below

hana(trial).ondemand.com and confirm with Finish.

Your application is deployed to the respective server and started in the default browser of your Eclipse.

Related LinksTest in SAPUI5 Application Preview [page 286]You access the SAPUI5 application preview using the Web App Preview, provided with the embedded Jetty server. You can quickly check on your application and open it in the default browser.

Test Your SAPUI5 Application on a Java Web Server [page 287]

1.3.4.2 SAPUI5 Concepts

The following sections introduce basic concepts for SAPUI5.

1.3.4.2.1 SAPUI5 Artifacts

The table gives an overview of the artifacts used in UI development toolkit for HTML5.

Artifact Description

UI library Top-level structural unit in SAPUI5

Libraries are the master artifacts in the SAPUI5 extensibility concept. They bundle a set of controls and related types and make them consumable by Web applications. There are predefined and standard libraries, such as sap.ui.commons with many commonly used controls. At the same time, it treats custom UI librares as first-class citizens, making it easy for you to write and use your own controls alongside the predefined controls.

UI element Basic building block for SAPUI5 interfaces

Elements are reusable entities with properties, events, methods, and relations. The most important relations are aggregations to other UI elements, and in this way a tree structure of elements can be created.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 111

Page 112: Hana Cloud

Artifact Description

control Subclass of an element, which can be used as root of a tree structure

Controls serve as an entry point, especially for rendering purposes. They are responsible for appearance and user interaction of a rectangular screen area. Examples for controls are Button, Label, TextField, or Table.

In addition to controls, the platform also provides elements that are not controls and are not used as root of the tree structure, but as dependent parts within it, for example TableRow and TableCell.

property Properties have a name and an associated data type and a well-defined default value expressed as a literal of the respective data type. Properties can be accessed from the application code by means of the element's API as getters and setters, but are also used read-only by a control renderer.

data type First class entities in the meta model; allow reuse of types across libraries and the extensibility of the type system

The SAPUI5 core library (sap.ui.core) provides a predefined set of types that can be used in other libraries.

aggregation Type of relation between UI elements defining aparent-child relation within the tree structures

Aggregations are relation types where the related entities are UI element types. The parent end of an aggregation has cardinality 0..1 and the child end can either have cardinality 0..1 or 0..*. The element's API as generated by SAPUI5 tools offers consistent methods for aggregations, for example, to get, set, or remove target elements.

Examples for aggregations are table rows and table cells or the content of a table cell.

association Type of relation between two UI elements, independent of the parent-child relation within the tree structure

SAPUI5 supports directed outgoing associations to a target of cardinality 0..1. Associations represent a loose coupling and are, thus, implemented by storing the ID of the target element instance. A typical example is the association between a label and its field.

event Events have a name and any number of parameters. The element's API offers support to manage event subscriptions.

112P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 113: Hana Cloud

1.3.4.2.2 Security Concepts

The following sections provide security-related information for specific topics, such as Cross-site srcipting.

For general information on Security concepts for SAPUI5, see the Security Guide for SAPUI5.

Cross-Site Scripting

Cross-site scripting (XSS) is a widely known vulnerability most web sites have. This page does not provide general information about cross-site scripting but focuses on what you as an application developer using SAPUI5 can do to avoid these security issues.

To give a short info on XSS: It is about injecting script code into a web page, which is then executed in the context of the page and therefore not only can access any information which currently displayed on the screen but can either access session information contained in cookies, or send new requests to the server within the current session, or even try to exploit browser vulnerabilities to get full access to the machine the browser is running on.

Cross-site Scripting in SAPUI5-based Web Applications

AJAX frameworks in general are an interesting target for XSS exploits, as not only the HTML which is initially sent to the browser may contain vulnerabilities, but also the code which is used to visualize content on the client side may have bugs which can be exploited to get the JavaScript coding executed on the client side. In addition to that, once a script has injected an AJAX application, it will be alive for a long time, as usually navigation will not reload the whole page which would also clean up any running JavaScript code, but stays within the same HTML document and uses a delta update mechanism to show new content.

It is important to understand that SAPUI5 is not involved in creating the HTML page which is sent to the client, so there is no way SAPUI5 can prevent XSS vulnerabilities which are contained in the HTML page itself. The application which is using the SAPUI5 rendering has to take care, according to the documentation of their server-side rendering framework, to properly escape user data, in a way that no JavaScript can be injected.

The SAPUI5 framework will take care of proper escaping for all content which is created and displayed on the screen using the controls provided by SAPUI5. There is no need for the application to HTML-escape user data, but the control API expects all data to be unescaped, so that it can be escaped as needed for the context it will be visualized.

URL White List Filtering

The SAPUI5 framework provides a client-side API to manage a whitelist for URLs. This whitelist can be used to validate arbitrary URLs if they are permitted or not. Internally controls which accept arbitrary HTML content like the sap.ui.richttexteditor.RichTextEditor or the sap.ui.core.HTML use the URL white list to check (sanitize) the URLs of their content and value to not infringe against the allowed URLs. The option to sanitize the value can be enabled or disabled in the respective control properly via property:

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 113

Page 114: Hana Cloud

RichTextEditor.sanitizeValue or HTML.sanitizeContent. For the HTML control it is disabled by default whereas for the RichTextEditor the sanitize option is enabled.

Maintaining the URL White List

The white list can be maintained with the following API:

● jQuery.sap.addUrlWhitelist● jQuery.sap.clearUrlWhitelist● jQuery.sap.getUrlWhitelist● jQuery.sap.removeUrlWhitelist

Here is an example how valid URLs can be added to the whitelist:

#!js

// jQuery.sap.addUrlWhitelist(/* protocol */ undefined, /* host */ undefined, /* port */ undefined, /* path */ undefined);

jQuery.sap.addUrlWhitelist(undefined, "www.sap.com");

jQuery.sap.addUrlWhitelist("https", "sdn.sap.com");

jQuery.sap.addUrlWhitelist(undefined, "sap.de", "1080");

Validating a URL

A URL can be validated by using the following API: jQuerysapvalidateUrl.

Here is an example how a given URL is validated against the before maintained whitelist:

#!js

jQuery.sap.validateUrl("http://www.sap.com"); // => true

jQuery.sap.validateUrl("http://sdn.sap.com"); // => false (wrong protocol)

jQuery.sap.validateUrl("https://sdn.sap.com"); // => true

jQuery.sap.validateUrl("ftp://sap.de:1080/anyftpfolder"); // => true

If no whitelist is maintained the URL validity check also basically checks the URL for being defined in a valid format.

HTML5 Sanitizer

The HTML5 Sanitizer can be used to cleanup HTML5 code snippets by removing potentially executable javascript. For this approach the HTML4 Sanitizer by Google is reused and adapted for the usage of HTML5 coding. The

114P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 115: Hana Cloud

Google Santizer also supports CSS3 coding. In addition the final Sanitizer makes use of the URL WhiteList which checks embedded URLs for correct formatting or against a given whitelist. For adapting the Sanitizer to support HTML5 the HTML attributes and elements were reorganized according to the actual HTML5 specification from the W3C. All types and flags were reviewed again as accurately as possible with HTML4 only elements removed, you can still see them as comments. All rules which are new or changed from the old HTML4 file are also marked "new" within the comment. The comments also state which attributes and elements are assigned to respective types and flags. All rules which were not 100% clear were analyzed in a way of similarity, so for example "audio" and "video" content behaves like images etc. URIEFFECTS state if a URL is loaded inplace within a tag where the actual document is in control of what type of content is loaded like "image" or if a new document is loaded like with "a href". LOADERTYPES state if content is loaded as sandboxed which means it is loaded within a specific surrounding player like with video content for example or if it is loaded freely without restrictions. Internally controls which accept arbitrary HTML content like the sap.ui.richttexteditor.RichTextEditor or the sap.ui.core.HTML use the HTML5 Sanitizer to sanitize the HTML code of their content and value to not infiltrate any dangerous coding. The option to sanitize the value can be enabled or disabled in the respective control properly via property: RichTextEditor.sanitizeValue or HTML.sanitizeContent. For the HTML control, it is disabled by default whereas for the RichTextEditor the sanitize option is enabled.

1.3.4.2.3 Model View Controller (MVC) Approach

In the Model-View-Controller concept, the respresentation of information is separated from the user's interaction:

● The view is responsible for defining and rendering the UI.● The model manages the application data.● The controller reacts to view events and user interaction by modifying view and model.

With this pattern, a separation of concerns is achieved that facilitates development and change of parts independently.

Views and controllers often form a 1:1 relationship, but it is also possible to have controllers without UI, so-called application controllers. It is also possible to create views without controllers. From a technical position, a view is a SAPUI5 control and can have or inherit a SAPUI5 model.

NoteView and controller represent reusable units and distributed development is highly supported.

UI development toolkit for HTML5 (SAPUI5) uses the Model View Controller (MVC) to achieve the following objectives:

● Provide support for MVC paradigm● Support development in distributed teams with different source locations● Suggest file structure, naming, and usage patterns● Add capability of UI declaration (in comparison to a programmatic construction)

The following sections introduce the use of MVC in SAPUI5, and especially the role of the artifacts view and controller.

For detailed information on the model approach and the available model flavors, see Data Binding in Applications.

SAPUI5 offers views and controllers in form of the following single files:

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 115

Page 116: Hana Cloud

● sap.ui.core.mvc.Controller● sap.ui.core.mvc.XMLView ● sap.ui.core.mvc.JSView● sap.ui.core.mvc.JSONView

For defining other or custom view types, SAPUI5 uses the base class sap.ui.core.mvc.View.

File Names and Locations (View and Controller)

Controllers and views are defined and instantiated via a name that equals a SAPUI5 module name within the require/declare concept. This means that by default all files have to be located in a subfolder of the resources folder of the Web application. If this location is not appropriate, deviations can be configured as described in the following example:

The following example assumes that your views and controllers are located on your local machine where the SAPUI5 runtime is loaded from another machine. When you instantiate a view or a controller, SAPUI5 runtime loads them in relation to the resources folder of the machine where SAPUI5 runtime was loaded. To inform SAPUI5 runtime that your views and controllers are located on your local machine, use the following code:

jQuery.sap.registerModulePath(sModuleNamePrefix, sURL);

or

sap.ui.localResources(sModuleNamePrefix);

It is usually sufficient to use sap.ui.localResources which internally registers sModuleNamePrefix to the URL "./" + sTransformedModuleNamePrefix, where all dots are replaced by slashes in the transformed name. All files starting with sModuleNamePrefix will then be loaded in relation to the location of the HTML page that called sap.ui.localResources.

If your files are located at "http://<localhost:8080>/<myapp>/", for example, you can use registerModulePath as follows:

jQuery.sap.registerModulePath("myapp", "http://<localhost:8080>/<myapp>/");

or

sap.ui.localResources("myapp");

All views and controllers with a name starting with myapp, for example myapp.MyView, will then be loaded from your local machine.

Controller Definitions

You define a simple controller without functions as follows:

sap.ui.controller("sap.hcm.Address", { // controller logic goes here});

116P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 117: Hana Cloud

The string in quotes specifies the controller name, see File Names and Locations (View and Controller. The controller file is then named Address.controller.js.

NoteThe suffix .controller.js is mandatory for controllers.

Controller Functions

SAPUI5 provides predefined lifecycle hooks for implementation. You can add event handlers or other functions to the controller and the controller can fire events, for which other controllers or entities can register.

Lifecycle Hooks

SAPUI5 provides the following lifecycle hooks:

● onInit(): Called when a view is instantiated and its controls (if available) have already been created; used to modify the view before it is displayed to bind event handlers and do other one-time initialization

● onExit(): Called when the view is destroyed; used to free resources and finalize activities● onAfterRendering(): Called when the view has been rendered and, therefore, its HTML is part of the

document; used to do post-rendering manipulations of the HTML. SAPUI5 controls get this hook after being rendered.

● onBeforeRendering(): Invoked before the controller view is re-rendered and not before the first rendering; use onInit() for invoking the hook before the first rendering

NoteFor controllers without a view, no lifecycle hooks are called.

sap.ui.controller("sap.hcm.Address", {

onInit: function() { this.counter = 0; }

});

Event Handlers and Other Functionality

In addition to lifecycle hooks, a controller can define additional methods that serve as event handlers or additional functionality offered by the controller.

sap.ui.controller("sap.hcm.Address", {

increaseCounter: function() {

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 117

Page 118: Hana Cloud

this.counter++; }

});

View Types

Although XML and JSON notation has been introduced for SAPUI5 UI controls, the MVC pattern is also supported to facilitate traditional programmatic UI constructions.

● XMLViewUI is defined in an XML file/string, see XML View Definition.

● JSONViewUI is defined via JSON in a file/string, see JSON View Definition.

● JSViewUI is constructed in a traditional manner, see JS View Definition.

● HTMLView (experimental)UI is defined in an HTML file/string

NoteThe XMLView type supports a mix of XML and plain HTML.

The above mentioned view types are predefined and offered for selection as view options in the application creation wizard. If you use SAPUI5 application development tools for Web application development, you can also plug in other view types.

JavaScript View Definition

You create a JavaScript (JS) view in the same way as a controller and use the suffix .view.js. for the file. SAPUI5 provides the following two default methods for implementation:

● getControllerName(): Specifies the controller belonging to this viewIf this method is not implemented or returns NULL, the view has no controller.

● createContent(): Called initially once after the controller has been instantiatedThis method is used to create the UI. As the method knows the controller, it can directly attach the event handlers.

sap.ui.jsview("sap.hcm.Address", { // this View file is called Address.view.js getControllerName: function() { return "sap.hcm.Address"; // the Controller lives in Address.controller.js },

createContent: function(oController) { var oButton = new sap.ui.commons.Button({text:"Hello JS View"}); oButton.attachPress(oController.handleButtonClicked); return oButton; }

});

The string in quotes denotes the view name that equals the SAPUI5 module name within the require/declare concept.

118P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 119: Hana Cloud

XML View Definition

The XML view type is defined in an XML file. The file name either ends with .view.xml or as an XML string. The file name and the folder structure together specify the name of the view that equals the SAPUI5 module name within the require/declare concept.

For resources/sap/hcm/Address.view.xml, the view name is sap.hcm.Address. The application uses this view name for displaying an instance of this view. If you define the XML view by means of an XML string, no file or require/declare is needed.

The file looks as follows:

<core:View controllerName="sap.hcm.Address" xmlns="sap.ui.commons" xmlns:core="sap.ui.core"> <Panel> <Image src="http://www.sap.com/global/ui/images/global/sap-logo.png"/> <Button text="Press Me!"/> </Panel><core:View>

Nest the XML tags analogous to the nesting sequence of SAPUI5 controls and add the property values as attributes. For information on more complex views see the following sections.

Namespaces in XML Views

Analogous to generic XML mapping features, the names of SAPUI5 control libraries are mapped to XML namespaces. You can choose any of the required namespaces as default and, thus, the respective control tags do not need a prefix.

The <View> tag is required and in the example above, the core namespace is defined in the first line. Of course you can define any name. To keep the tag names shorter, for example, you can also use "c" instead of "core".

NoteIf controls are located in a subpackage of a control library, for example sap.ui.commons.layout.MatrixLayout, they must have their own XML namespace:

<core:View controllerName="sap.hcm.Address" xmlns="sap.ui.commons" xmlns:core="sap.ui.core" xmlns:layout="sap.ui.commons.layout"> <layout:MatrixLayout> ...

Aggregation Handling in XML Views

You can simply add child controls as child tags, as shown in the example above where a <Button> tag is added to a <Panel> tag.

Some controls have more than one content area, for example the shell control that has the main content area, a pane bar, a headerItems aggregation, worksetItems, and so on. Hence, an aggregation tag usually serves as direct child of a container and contains children. It is only possible to directly add children as shown in the example above if the container control has marked one of the child aggregations as default.

Some containers may not have default content, for example, the splitter container has two equally important content areas.

Note

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 119

Page 120: Hana Cloud

The framework supports you by issuing error message in case of errors in the aggregation handling in XML views.

You fill aggregations as shown in the following example.

NoteThe namespace of the parent control tag and the aggregation tag must be the same.

<core:View controllerName="sap.hcm.Address" xmlns="sap.ui.commons" xmlns:core="sap.ui.core"> <Panel> <content> <!-- this is the general way of adding children: use the aggregation name --> <Image src="http://www.sap.com/global/ui/images/global/sap-logo.png"/> <Button text="Press Me"/> </content> </Panel><core:View>

Use of Event Handlers in XML Views

Event handlers are used as attributes. The attribute name is the event name, such as "press" for a button, and the attribute value as event handler name. The event handler must be defined as a function in the view's controller.

The following declaration causes controller.doSomething() to be executed when the button is pressed:

... <Button text="Press Me" press="doSomething"/>...

Data Binding in XML Views

To bind texts of a control in XML views to a language-dependent resource bundle, define the resource bundle by a name (resourceBundleName attribute) or a URL (resourceBundleUrl attribute) and assign an alias (resourceBundleAlias attribute) to the bundle in the view definition. The binding path is the same as for other SAPUI5 data binding, see Data Binding.

Resource bundle content:

MY_TEXT=Hello World

Example:

<core:View resourceBundleName="myBundle" resourceBundleAlias="i18n" controllerName="sap.hcm.Address" xmlns="sap.ui.commons" xmlns:core="sap.ui.core" xmlns:html="http://www.w3.org/1999/xhtml"> <Panel> <Button text="{i18n>MY_TEXT}"/> </Panel><core:View>

The ResourceModel required for binding these texts is created during view instantiation. The model is set as secondary model with the given alias to the view instance. If you want to bind other properties to another model, you have to create the model on your own in the corresponding controller or HTML page and attach it to the view with another alias. The binding itself behaves the same as every SAPUI5 data binding and as described above.

120P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 121: Hana Cloud

Use of Native HTML in XML Views

The use of native HTML depends on the XHTML feature set. When mixing XHTML and SAPUI5 controls, observe the following rules:

● XHTML elements can be used instead of the SAPUI5 type control, for example, in the root of an XML view or in the content aggregation of a layout container.

● When embedding XHTML in an aggregation of a SAPUI5 control, the XHTML must not consist of a single text node. The topmost node of an embedded XHTML tree must be an XHTML element. Embedding pure text into an aggregation is not supported.

● The XHTML nodes are converted 1:1 to HTML, the XMLView does not deal with any differences between XHTML and HTML (for example rewriting and auto-closing tags)

● The created HTML DOM nodes are preserved during re-rendering of an XML view: Modifications to the DOM are not lost.

NoteAs an alternative to embedding XHTML, you can use the sap.ui.core.HTML control. As this requires content encoding it is, however, less convenient.

To mix SAPUI5 controls with native XHTML, you only need the XHTML namespace to use (X)HTML:

<core:View controllerName="sap.hcm.Address" xmlns="sap.ui.commons" xmlns:core="sap.ui.core" xmlns:html="http://www.w3.org/1999/xhtml"> <Panel> <Button text="Press Me. I am a SAPUI5 Button"/> <html:button>No, press me. I am native HTML Button.</html:button> </Panel><core:View>

Use of CSS Style Sheets in XML Views

You include style sheets like plain HTML. You can add further CSS classes to SAPUI5 controls by using the class attribute. The effect is the same as calling myButton.addStyleClass(...).

<core:View controllerName="sap.hcm.Address" xmlns="sap.ui.commons" xmlns:core="sap.ui.core" xmlns:html="http://www.w3.org/1999/xhtml"> <html:style> .mySuperRedButton { color: red; } </html:style> <Panel> <Button class="mySuperRedButton" text="Press Me"/> </Panel><core:View>

TipWe recommend to carefully choose the elements that you style as the CSS always affects the whole page and is not restricted to the view.

JSON View Definition

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 121

Page 122: Hana Cloud

The JSON view type is defined in a file. The file name has to either end with .view.json or as a JSON string. The file name and the folder structure together specify the name of the view that equals the SAPUI5 module name within the require/declare concept.

For the file resources/sap/hcm/Address.view.json, the view name is sap.hcm.Address. The application uses this view name for displaying an instance of this view.

The file looks as follows:

{ "Type":"sap.ui.core.mvc.JSONView", "controllerName":"sap.hcm.Address", "content": [{ "Type":"sap.ui.commons.Image", "id":"MyImage", "src":"http://www.sap.com/global/ui/images/global/sap-logo.png"

}, { "Type":"sap.ui.commons.Button", "id":"MyButton", "text":"Press Me"

}]

}

You nest the JSON objects analogous to the nesting of SAPUI5 controls and add the property values as attributes. The syntax is the same as the syntax of a JSON constructor for any control.

NoteYou can only use strings in your JSONView.

Aggregation Handling in JSON Views

You add child controls as arrays. This is shown in the example above where an image and a button have been added to the view content aggregation.

Use of Event Handlers in JSON Views

Event handlers are used as attributes with the attribute name as event name like "press" for a button and the attribute value as event handler name. The event handler must be defined as a function in the view's controller.

The following declaration causes controller.doSomething() to be executed when the button is pressed:

... { "Type":"sap.ui.commons.Button", "id":"MyButton", "text":"Press Me", "press":"doSomething" }...

Data Binding in JSON Views

122P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 123: Hana Cloud

To bind texts of a control in JSON views to a language-dependent resource bundle, define the resource bundle by a name (resourceBundleName property) or a URL (resourceBundleUrl property) and assign an alias (resourceBundleAlias property) for the bundle in the view definition. The binding path is the same as for other SAPUI5 data binding, see Data Binding.

Resource bundle content:

MY_TEXT=Hello World

Example:

{ "Type": "sap.ui.core.JSONView", "controllerName":"my.own.views.test", "resourceBundleName":"myBundle", "resourceBundleAlias":"i18n", "content": [{ "Type":"sap.ui.commons.Panel", "id":"myPanel", "content":[{ "Type":"sap.ui.commons.Button", "id":"Button1", "text":"{i18n>MY_TEXT}", "press": "doIt" }] }]}

The ResourceModel required for binding these texts is created during view instantiation. The model is set as secondary model with the given alias to the view instance. If you want to bind other properties to another model, you have to create the model on your own in the corresponding controller or HTML page and attach it to the view with another alias. The binding itself behaves in the same way as every SAPUI5 data binding and as described above.

HTML View Definition

An HTML View is defined by declarative HTML, see Declarative Support. Like the declarative support, the HTML view supports embedded HTML.

The view file ends with view.html, for example myview.view.html.

Example:

<template data-controller-name="example.mvc.test"> Hello <h1>Title</h1> <div>Embedded HTML</div> <div class="test test2 test3" data-sap-ui-type="sap.ui.commons.Panel" id="myPanel"> <div class="test test2 test3" data-sap-ui-type="sap.ui.commons.Button" id="Button1" data-text="Hello World" data-press="doIt"></div> <div data-sap-ui-type="sap.ui.commons.Button" id="Button2" data-text="Hello"></div> <div data-sap-ui-type="sap.ui.core.mvc.HTMLView" id="MyHTMLView" data-view-name="example.mvc.test2"></div> <div data-sap-ui-type="sap.ui.core.mvc.JSView" id="MyJSView" data-view-name="example.mvc.test2"></div> <div data-sap-ui-type="sap.ui.core.mvc.JSONView" id="MyJSONView" data-view-name="example.mvc.test2"></div> <div data-sap-ui-type="sap.ui.core.mvc.XMLView" id="MyXMLView" data-view-name="example.mvc.test2"></div>

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 123

Page 124: Hana Cloud

</div></template>

All view specific properties can be added to the <template> tag as data-* attributes.

View Instantiation

You use the factory method sap.ui.view to instantiate views. To pass required information for the instantiation, use an object with the following properties:

● type: The type can be JSON, JS, or XML. All possible types are declared in the enumeration sap.ui.core.mvc.ViewType.

● viewName: View name corresponding to the module concept● viewContent: Only relevant for XML views and JSON views. Defines the XML or JSON string representation

of the view definition. If viewName and viewContent are given, the viewName property is used to load the view definition.

● Controller: Any controller instance; the given controller instance overrides the controller defined in the view definition

● viewData: Only used for JS views; this property contains user-specific data that is available during the whole lifecycle of the view and the controller

... var myController = sap.ui.controller("my.own.controller"); var myView = sap.ui.view({ type: sap.ui.core.mvc.ViewType.XML, viewName: "my.own.view", controller: myController });...

All regular properties of a view (control) can be passed to the object as usual.

Typed Views and Controllers

For more complex use cases, a more formal and, thus, more complex way to define views and controllers may be necessary.

The following section describes how you create new classes by using prototype inheritance and how to declare their API.

Typed Controllers

To create a controller that is a new type of its own, you need to write a boilerplate code and declare the functions of the new prototype:

/* boilerplate code for typed Controller */jQuery.sap.declare({modName:"sap.hcm.AddressController", type:"controller"}); //

124P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 125: Hana Cloud

declaring a special type of module sap.hcm.AddressController = function () { // the constructor sap.ui.core.mvc.Controller.apply(this, arguments);};jQuery.sap.require("sap.ui.core.mvc.Controller"); // this is currently required, as the Controller is not loaded by defaultsap.hcm.AddressController.prototype = jQuery.sap.newObject(sap.ui.core.mvc.Controller.prototype); // chain the prototypes/* end of boilerplate code for typed Controller */

// to avoid the above we could in the future offer it behind a simple call to:// sap.ui.defineController("sap.hcm.Address");

sap.hcm.AddressController.prototype.onInit = function() { // modify control tree - this is the regular lifecycle hook

};

// implement an event handler in the Controllersap.hcm.AddressController.prototype.doSomething = function() { alert("Hello World");};

Support for Unique IDs

Each view and its content usually defines static IDs. You use these IDs to identify and modify the controls within your controller during runtime. If you reuse or nest these views, the IDs are no longer unique. To avoid ambiguity, each view adds its own ID as prefix to all its child controls. This only happens if a static ID is provided. If the ID is created during instantiation of the control, it is unique per default.

If you create further controls during runtime, the controller creates a unique ID by calling the oController.createId("ID") method. These methods add the necessary prefix to the ID.

If you want to modify the control with the ID <ID>, you can call the byId(<ID>) method on your view to get the correct control directly. You do not have to handle all the prefix stuff on your own. The following view defines a button with the static ID abutton (ButtonView):

<core:View viewName="sap.hcm.ButtonView" controllerName="sap.hcm.myController" xmlns="sap.ui.commons" xmlns:core="sap.ui.core" xmlns:html="http://www.w3.org/1999/xhtml"> <Button id="aButton" text="Click me"/><core:View>

The following view defines a view embedding the same view several times (ContainerView):

<core:View viewName="sap.hcm.ContainerView" controllerName="sap.hcm.Address" xmlns="sap.ui.commons" xmlns:core="sap.ui.core" xmlns:html="http://www.w3.org/1999/xhtml"> <core:View id="ButtonView1" viewName="sap.hcm.ButtonView"/> <core:View id="ButtonView2" viewName="sap.hcm.ButtonView"/><core:View>

The view is created as follows:

... var oView = sap.ui.view({type:sap.ui.core.mvc.ViewType.XML,

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 125

Page 126: Hana Cloud

id:"myContainerView",viewName:"sap.hcm.ContainerView"});...

The container view has the following IDs:

Both child views IDs have the prefix myContainerView--:

myContainerView--ButtonView1

myContainerView--ButtonView2

To get one of the child views, use the following code:

... var oButtonView1 = oView.byId("ButtonView1");...

The button view has the following IDs:

ButtonView1--aButton

ButtonView2--aButton

To get the button control, use the following code:

... var oButtonView1 = oView.byId("ButtonView1"); oButtonView1.byId("aButton");...

View Cloning

Another important aspect of SAPUI5 views is their cloning behavior. As you might know, SAPUI5 aggregation bindings can use template control to create a series of similar controls based on a collection of data, for example, items in a RowRepeater for each entry in a model array. The data binding uses a ManagedObject.clone operation to create multiple controls out of a single template. For normal controls, the clone operation is based on the control settings that are decribed by SAPUI5 metadata: properties, aggregations, associations, event handlers and so on. The clone operation collects all these settings and creates a new instance out of it.

For views there is a conflict between this basic, generic approach and the way how views usually define their content: via hooks (JSView) or via persisted XML or JSON files. Furthermore, it is allowed and documented best practice to modify the view in the onInit hook of its controller. To avoid conflicts between the generic cloning and the MVC concepts, views implement a slightly modified clone operation: only a subset of the view settings are cloned, the remainder is re-created by calling the hook (JSView) or applying the external view description (XML or JSON file), depending on the view type.

Cloned in a generic way are the following settings:

● any models that have been set (setModel())● registered control event listeners (attachSomeEvent)● registered browser event listeners (attachBrowserEvent)● bindings (bindProperty, bindAggregation)

Not cloned, but recreated are all aggregations, namely the content.

126P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 127: Hana Cloud

In scenarios where the above clone approach still leads to undesirable behavior, factory functions can be used for the aggregation binding instead.

Related LinksAggregation Binding [page 165]

Model View Controller and SAPUI5 for Google Web Toolkit

NoteSAPUI5 currently does not support working on basis of the MVC approach for the Google Web Toolkit.

1.3.4.3 Developing User Interfaces with SAPUI5

1.3.4.3.1 Initializing and Loading

The following sections provide information about the following topics:

● Loading and initializing SAPUI5 in HTML pages● Runtime behavior of bootstrap● Configuration of SAPUI5 runtime

Loading and Initializing SAPUI5 in HTML Pages

To make use of the SAPUI5 framework or its controls, applications must include SAPUI5 into their HTML pages. There are several possibilities how the SAPUI5 runtime and controls can be integrated into an HTML page. Common to all alternatives is the need to load and execute at least one SAPUI5-specific JavaScript resource.

The following table lists the most important resources and describes the intended use cases. The resource names refer to the resources/ folder in the SAPUI5 installation. The actual base URL depends on the platform and adminstratrion decisions.

Resource Description

sap-ui-core.js Standard bootstrap file

The standard bootstrap file already contains jQuery, jquery-ui-position, and a minimal UI5 core. Required files are loaded dynamically using XMLHttpRequests (XHRs)

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 127

Page 128: Hana Cloud

Resource Description

For more information, see Standard Variant.

sap-ui-core-nojQuery.js Intended for applications that bring their own jQuery version with them

This file contains the same elements of SAPUI5, but everything related to jQuery is left out, that is, jQuery and jquery-ui-position.

For more information, see noJQuery Variant.

sap-ui-core-all.js Single js file containing (almost) all resources of the sap.ui.core library

Only a few duplicates, such as multiple jQuery versions, testing stuff etc. are omitted. If you use this file, the *-all.js file is loaded as well for all other libraries. This reduces the number of JS requests to the number of libraries (typically 1..4).

NoteTo ensure a proper encapsulation, the *-all.js files will be renamed in future versions of SAPUI5. The sap-ui-core-all.js will remain as is, but for other libraries the file will use a name relative to the libary, for example sap/ui/commons/library-all.js. Applications must not address these files on their own, but let SAPUI5 runtime load them. Only sap-ui-core-all.js can be referenced in the bootstrap tag.

sap/ui/core/library-preload.js Similar to the *-all.js except that modules are not parsed and executed immmediately but only on demand.

CautionApplications must never reference this file; if the configuration option is set to preload, SAPUI5 automatically loads the file.

For more information, see Preload Variant.

sap-ui-core-lean.js Similar to sap-ui-core.js, but only the jQuery and one SAPUI5 file are loaded immediately; the other files are loaded dynamically

This use case is usually not used and may be removed in future.

sap-ui5.js All-in-one file

128P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 129: Hana Cloud

Resource Description

This file contains all JS modules from the sap.ui.core, sap.ui.commons, sap.ui.table and sap.ui.ux3 libraries. Using this file as bootstrap file might require a longer load time as the other use cases, but requires only one single request. Another drawback is the fixed set of libraries.

This file is not available on all platforms, only on those based on the sapui5.war or sapui5-static.zip artifacts. The OSGI/Eclipse versions (com.sap.ui5.core.jar), for example, do not contain this file.

For more information, see All-in-one per Library Variant.

sap-ui-custom*.js Reserved for custom merged files created by the application

NoteThe proposed naming scheme for these files needs to be adapted in future versions for the same encapsulation reasons as mentioned above.

For more information, see sap-ui5.

Related LinksRuntime Behavior of Bootstrap [page 131]

Standard Variant

The most common variant for loading SAPUI5 is to include the sap-ui-core.js file. It is self-contained in the sense that it already contains jQuery and some jQuery plugins. Applications only need to specify this single resource on their page and the rest is done automatically by SAPUI5 runtime.

#!js <script id="sap-ui-bootstrap" src="resources/sap-ui-core.js" data-sap-ui-libs="sap.ui.commons" data-sap-ui-theme="sap_goldreflection" > </script>

If UI libraries are specified, SAPUI5 loads them all synchronously. If a libary requires another libary,w hich has not been mentioned in the configuration, the required library is automatically loaded as well. The theme configuration is used to load the corresponding stylesheets for all libraries.

Immediately after the above script tag, applications can call most SAPUI5 APIs. They can access the core APIs or instantiate, configure, and place controls. Only the access to the DOM must be delayed until the controls have been rendered. At the earlies, this can happen only after the document becomes ready. Applications can use the attachInitEvent method to be notified about that event.

NoteAs a further optimization to the standard variant, the default configuration of SAPUI5 automatically activates the preload=sync mode when running from optimized sources, see Preload Variant.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 129

Page 130: Hana Cloud

For further configuration options, see Configuration of the SAPUI5 Runtime.

noJQuery Variant

Applications that already integrate jQuery and/or want to use a jQuery version different to the version integrated in SAPUI5 can use the resources/sap-ui-core-noJQuery.js module. It requires that jQuery and jquery-ui-position have been loaded already.

#!js <!-- include some jQuery version --> <script src="my-jQuery-min.js" ></script>

<!-- application doesn't have its own jquery-ui-poasition, so it might use the one from UI5 --> <script src="resources/jquery-ui-position.js" ></script>

<!-- now booting UI5 --> <script id="sap-ui-bootstrap" src="resources/sap-ui-core-nojQuery.js" data-sap-ui-libs="sap.ui.commons" data-sap-ui-theme="sap_goldreflection" > </script>

Preload Variant

The preload feature loads all JavaScript modules for a library in advance with a single request. The code for the modules is not executed in the browser. Only when the application requires the module, the runtime executes the code once. Thus, using the preload mechanism helps to significantly reduce the number of roundtrips. To use the preload feature, you can use the 'preload' configuration option. The following values are available:

● syncThis option loads the modules for all declared libraries sychronously. After the bootstrap tag has been processed, all preload files for all libraries are loaded and the libraries are initialized as usual. Using the preload=sync mode should be transparent to most applications.

● asyncThis option loads the modules for all declared libraries asynchronously. Any code following the SAPUI5 bootstrap tag can, thus, not be sure that the SAPUI5 classes are available already. Applications that want to use the preload=async mode must delay access to SAPUI5 APIs with the help of the Core.attachInitEvent method. Only then it is save to access SAPUI5 APIs. The asynchronous loading is only supported for declared libraries, that is, for libraries loaded by the SAPUI5 core. Libraries loaded dynamically, that is, using the sap.ui.getCore().loadLibrary() API will be preloaded in sync mode.

● autoThis option is the default preload mode. It checks whether the SAPUI5 runtime uses optimized sources. If so, it enables the 'sync' mode to further optimize the runtime. When normal or debug sources are used, the preload is deactivated.

NoteAs preload sources are always optimized using preload in the debug mode of SAPUI5 would be counterproductive. Therefore, the debug mode always overrides the preload mode.

The easiest way to check the preload feature with an existing application is to specify the sap-ui-preload=/mode/ parameter in the start URL, or to add the data-sap-ui-preload attribute to the bootstrap tag:

#!js <script

130P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 131: Hana Cloud

id="sap-ui-bootstrap" src="resources/sap-ui-core.js" data-sap-ui-libs="sap.ui.commons" data-sap-ui-theme="sap_goldreflection" data-sap-ui-preload="sync" > </script>

NoteAs the async mode requires active cooperation of the application, it is not activated automatically, but only by configuration.

NoteThe preload mode can be combined with other bootstrap modules, for example, sap-ui-core-noJQuery.

All-in-one per Library Variant

The all-in-one per library variant's request behavior is similar to the request behavior of the preload=sync variant, but it immediately executes all code for a library. Historically, it is a predecessor of the preload feature and should no longer be used.

sap-ui5 Variant

The sap-ui5 variant is another predecessor of the preload variant. It loads all classes and controls of the four standard SAPUI5 libraries sap.ui.core, sap.ui.commons, sap.ui.table, sap.ui.ux3 with one single request. This variant has the following constraints:

● The set of libraries is not extensible. Therefore, custom libraries do not benefit from this approach and the all-in-one variant must be used instead.

● All contained code is executed. This may increase the initial startup time of the application depending on factors like browser, client computer or device, and so on.

● File size is huge.

We recommend to use the preload variant instead. Keep in mind that for optimized sources the preload variant is used automatically.

Runtime Behavior of Bootstrap

During initialization of SAPUI5 runtime, the following steps are executed:

1. jQuery is enriched with plugins, most of them in the jQuery.sap namesapce. These plugins provide fundamental functionality used by SAPUI5 core, such as the modularization concept, a small logging framework, performance measurement, and so on.

2. If not already available, the global object sap is created.3. The SAPUI5 core class (sap.ui.core.Core) is executed with all its dependencies.4. The runtime configuration is determined from different sources.5. All libraries and modules declared in the configuration as well as their dependencies are loaded.6. For each loaded library, the stylesheet of the configured theme is added to the page.7. When all libraries are loaded and the document is ready, the initEvent of the core is fired and all registered

handlers are executed.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 131

Page 132: Hana Cloud

Steps During Library Loading

Context

For each control library that is loaded during bootstrap, SAPUI5 runtime loads and interprets the following additional resources:

Procedure

1. Library bootstrap file /''context-path''/resources/''library-name''/library.jsA JavaScript file that contains the JavaScript code for all enumeration types provided by the library as well as library-specific initialization code that is independent from any controls in the library. The file must call the sap.ui.getCore().initLibrary method with an object that describes the content of the library (list of contained controls, elements etc.). For libraries that are developed with the SAPUI5 application development tools or with the SAPUI5 offline build tools, this file is automatically generated during the build.

2. Library stylesheet file /''context-path''/resources/''library-name''/themes/''theme-name''/library.cssA standard CSS file that contains all styles relevant for this library. For libraries that are developed with the SAPUI5 application development tools, this file is automatically generated during the build.

Dynamic Loading of UI Libraries

Declaring UI libraries in the runtime configuration is just one way to use a library at runtime. Another way is to use the sap.ui.getCore().loadLibary() at runtime to instruct SAPUI5 to load an additional library. After loading the library, all controls from that library can be used as well, but the same restriction as for declared libaries apply, that is that DOM access is only possible after document.ready and rendering.

Configuration of the SAPUI5 Runtime

If the SAPUI5 bootstrap script is included in a page, SAPUI5 runtime is automatically initialized as soon as the script is loaded and executed by the browser. For simple use cases as well as the default SAPUI5 installation, this is sufficient to build and run UIs. Only the set of used SAPUI5 libraries and the used theme can be specified additionally.

The following code shows a typical bootstrap script tag:

#!text/html <script id="sap-ui-bootstrap" type="text/javascript" src="resources/sap-ui-core.js" data-sap-ui-theme="sap_goldreflection" data-sap-ui-libs="sap.ui.commons" > </script>

The attributes data-sap-ui-theme="sap_goldreflection" and data-sap-ui-libs="sap.ui.commons" already provide examples of how SAPUI5 runtime can be configured to the needs of an application.

132P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 133: Hana Cloud

The following sections summarize the different configuration options as well as different ways to configure SAPUI5 runtime.

Related LinksWays to Provide Configuration [page 133]Configuration Options [page 136]

Ways to Provide Configuration

The following sections introduce the different possibilities to provide the configuration options for SAPUI5 runtime.

Runtime Default Values

SAPUI5 runtime provides a default value for each configuration option. For an overview of the default values, see Configuration Options.

Individual Script Tag Attributes

You can specify SAPUI5 configuration options by means of one or more attributes of the bootstrap script tag. For each configuration option, SAPUI5 accepts a correspondingly named attribute in the bootstrap script tag with the following information:

● Attribute nameThe attribute name is derived from the name of the configuration option and the prefix data-sap-ui-. The first part of the prefix (data-) is necessary to comply with the W3C recommendations for custom attributes in HTML. The second part (-sap-ui-) separates SAPUI5 attributes from custom attributes defined by any other framework.As attribute names in HTML are case insensitive, the same applies to the configuration attribute names. SAPUI5 defines some camel case names for configuration options, see Configuration Options [page 136]. SAPUI5 converts these names automatically to lower case when accessing the configuration.

● ValueElement attributes in HTML have a string value by definition. For configuration options of type string, the attribute value is equivalent to the value of the option.

NoteIf the value contains specific HTML characters, such as '<' or '>' or if the value it contains the same quote character that is used to wrap the attribute value, the usual HTML escaping mechanisms must be used: Use entities for the specific HTML characters, for example &lt; instead of < and switch the type of quotes from single to double or vice versa.

For configuration options that are not of type string, the format of the allowed values needs to be defined as follows:

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 133

Page 134: Hana Cloud

Type Notation/Values

string Just a string, but escaped according to the HTML conventions

boolean 'true' and 'x' are both accepted as true values (case-insensitive), all others are false. We recommend to use 'false' for false values

int Any integer value

string array Comma separated list of values; comma is not supported in the values (no escaping)

map from string to string JavaScript object literal (preferably JSON syntax)

For a list of types for each configuration option, see Configuration Options.

Single and Complex Configuration Attributes

Instead of attaching individual options with individual configuration attributes to the script tag, you can use a single attribute with a more complex structure. The attribute name for the complex configuration is data-sap-ui-config. Its content is similar to the global configuration object, but without the enclosing parenthesis: It is a comma separated list of key/value pairs.

NoteAgain, the usual HTML escaping mechanisms must be used when the value contains specific HTML characters (<, >, &) or the quote character that is used to enclose the attribute value.

#!text/html <script id="sap-ui-bootstrap" type="text/javascript" src="resources/sap-ui-core.js" data-sap-ui-config="theme:'sap_platinum',libs:'sap.ui.commons'" > </script>

Global Configuration Object

Another way of specifying the configuration is to create a property in the global window object with property name sap-ui-config. The property must be a simple object, where each property represents the configuration option of the corresponding name.

NoteThe name of the window property intentionally is not a valid JavaScript identifier. This helps to avoid conflicts with typical JavaScript coding and the structured nature of the name is intended to avoid conflicts with SAP objects. To define the object, quotes must be used.

134P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 135: Hana Cloud

NoteIf a configuration option has a name that is not a valid JavaScript identifier or that is a reserved token in JavaScript, the property name in the configuration object must be quoted. Currently, such a configuration option does not exist.

NoteAs the configuration is evalued during the bootstrap of SAPUI5, the configuration object must be created before SAPUI5 is booted. Otherwise the contained configuration cannot be evaluated. As a consequenece, using the global configuration object requires another script tag in front of the bootstrap tag. It is up to the application whether to use an inline script tag or a separate JavaScript file for that purpose, which is loaded via a script tag. Using a dedicated file initially requires more work, but has the following advantages:

● The file can be shared by multiple pages, which would then use the same configuration.● Using a file also works with the new Content Security Policy (CSP) mechanism as introduced, for example,

by FireFox 4.0 and others.

An example use with an inline script could look like this:

#!text/html <script type="text/javascript"> window["sap-ui-config"] = { theme : "sap_platinum", libs : "sap.ui.commons", }; </script> <script id="sap-ui-bootstrap" type="text/javascript" src="resources/sap-ui-core.js" > </script>

Although this option requires the overhead of an additional script/script tag, it opens the possibility to share configuration between pages, it can be used in environments where the scrip tag cannot be influenced (for example, because it is created out of some configuration, like in some meshup frameworks), and it allows to provide configuration before the core boots.

URL Parameters

Another way of specifying configuration options is to add theme as parameters to the start URL of an application. The name of the URL parameters is derived from the name of the configuration option and the prefix sap-ui-.

NoteThe W3C proposed data- prefix is not needed and even not allowed here as all URL parameters are kind of custom parameters.

Values of URL parameters are strings, so the same type mapping as for HTML attributes apply. Keep in mind, however, that URLs require a different encoding than HTML does (use % encoding instead of entity encoding).

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 135

Page 136: Hana Cloud

For security reasons, only some configuration options can be set via URL parameters. And by setting the ignoreUrlParameters option to true, applications can even disable URL configuration parameters completely.

Runtime Configuration Object

The above described options to provide configuration information have one thing in common: They are evaluated during boot of SAPUI5 runtime. After that, changes to these parameters are ignored. The final configuration result can be read via the sap.ui.getCore().getConfiguration() method.

The same object also provides set methods for a very limited set of configuration options. Such options can be modified at runtime and the runtime and/or the controls can react on the configuration changes. The most prominent (and so far only) example for such a configuration option is the theme.

Order of Significance

Attributes of the DOM reference override the system defaults, URL parameters override the DOM attributes (where empty URL parameters set the parameter back to its system default).

Calling setters at runtime will override any previous settings calculated during object creation.

Configuration Options

The following list is a snapshot of the configuration options available when the list has been created. For a complete list of all current configuration options, see the API documentation of sap.ui.core.Configuration.

Option Type Default Value URL Modifiable at Runtime

Description

theme string 'base' x x Theme to be used for the current page; can be changed at runtime by calling sap.ui.getCore().applyTheme()

language string user language x Language to be used for localized texts, formattings, etc.

The default value is not static, but

136P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 137: Hana Cloud

Option Type Default Value URL Modifiable at Runtime

Description

determined from the browser or user language in the following order: navigator.language, navigator.browserLanguage, navigator.userLanguage

formatLocale string undefined x Locale to use for formatting purposes; defaults for the locale are derived from the language

accessibility boolean true x Determines whether the SAPUI5 controls are rendered for or running in accessibility mode

animation boolean true x Determines whether animations are generally allowed in SAPUI5 controls

rtl boolean false x Determines whether all controls should be rendered in right-to-left (RTL) mode; not yet

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 137

Page 138: Hana Cloud

Option Type Default Value URL Modifiable at Runtime

Description

determined automatically

debug boolean false x If set to true, the debug sources are loaded; if the bootstrap code is loaded from an optimized source, the bootstrap will be aborted and start anew from a debug source

inspect boolean false x If set to true, the sap-ui-debug.js module is included and provides some supportability features

originInfo boolean false x If set to true, additional information for text resources is maintained that should allow to trace where a translated text in the UI came from

noConflict boolean false ! Determines whether the SAPUI5 core should already force jQuery into noConflict mode

138P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 139: Hana Cloud

Option Type Default Value URL Modifiable at Runtime

Description

noDuplicateIds boolean true x Enforces a check in SAPUI5 runtime that does not allow mutliple controls to have the same ID; we highly recommend this, as duplicate IDs may cause unforseeable issues and side effects

trace boolean false ! Activates an overlay div that contains a trace

logLevel 0|1|2|3|4|5|6|NONE|FATAL|ERROR|WARNING|INFO|DEBUG|ALL

ERROR x x Sets the log level to the given value; for minified (productive) sources, the default level is ERROR, for debug sources it is DEBUG. At runtime, the log level can be modified with jQuery.sap.log.setLevel

modules string[] [ ] ! List of JavaScript modules to load after the code has been initialized

areas string[] null ! x UIAreas to create in advance; at runtime, new UIAreas can be created with sap.ui.getC

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 139

Page 140: Hana Cloud

Option Type Default Value URL Modifiable at Runtime

Description

ore().createUIArea and existing ones can be deleted with sap.ui.getCore().getUIArea(id).destroy()

libs string[] [ ] ! x List of libraries to be loaded initially; further libs can be loaded via the loadLibrary() method of SAPUI5 runtime

themeRoots object undefined X sap.ui.getCore().setThemeRoot()

Locations of themes, for details see Theming: FAQ.

onInit code undefined ! Code has to be executed after the core has been initialized

uidPrefix string '--' ! Prefix to be used for automatically generated control IDs; must be choosen carefully to avoid conflicts with IDs defined by the application or DOM IDs

ignoreUrlParams

boolean false ! Security relevant parameter that allows applications to disable configuration modifications via URL parameters

140P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 141: Hana Cloud

Option Type Default Value URL Modifiable at Runtime

Description

weinreServer string URL to a WEINRE server to be used for debugging purposes; if set, SAPUI5 will automatically include the WEINRE target modules

weinreId string x

xx-loadAllMode boolean false !Note

This is an experimental feature, which might be modified or removed in future versions.

Used internally by SAPUI5 runtime. To activate it, load sap-ui-core-all.js instead of sap.ui.core.js

preload not specified, auto, sync, or asynch

'auto' ! After loading SAPUI5 core runtime and before loading any further libraries, so called preload files are loaded that contain all modules of a library. The modules are only loaded, but not executed, thus reducing

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 141

Page 142: Hana Cloud

Option Type Default Value URL Modifiable at Runtime

Description

initialization time.

The values are used as follows:

● When set to 'auto', SAPUI5 runtime automatically uses 'sync' when running from optimized sources.

● When set to 'sync', the preload files for the declared libraries are loaded synchronously.

● When set to 'async' the preload files are loaded asynchronously.

● For any other value (for example blank), the preload feature is deactivated and modules are loaded on demand.

xx-test-mobile boolean false xNote

This is an experimental feature,

142P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 143: Hana Cloud

Option Type Default Value URL Modifiable at Runtime

Description

which might be modified or removed in future versions.

Activates support for mobile device-specific events, such as touch events. This enables the test of standard SAPUI5 controls on mobile devices.

xx-fakeOS string undefined xNote

This is an experimental feature, which might be modified or removed in future versions.

Used to simulate iOS, Android and BlackBerry on desktop PCs for easier development of mobile apps and controls. The following values are supported:

● ios● android● blackberry

The user-agent is modified and

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 143

Page 144: Hana Cloud

Option Type Default Value URL Modifiable at Runtime

Description

the complete runtime and theming acts as the selected mobile platform. This includes Browser detection mechanisms such as jQuery.browser.

NoteThis configuration parameter only works on desktop webkit browsers, such as Chrome and Safari. On other browsers and on mobile devices, this switch has no effect.

1.3.4.3.2 UI Control API: Using JSON Data in UI Control Constructors

You can specify a unique identifier as the first argument to the constructor. If you omit it, an identifier is computed automatically by the SAPUI5 framework. Specifying an identifier is optional and allows your application to find the control again, for example, for retrieving the current user input from it. Alternatively, you may keep a reference to the control in a variable.

As second value of the constructor, you can specify a JSON string with all control properties that should be set:

var oTextField = new sap.ui.commons.TextField("testTextField", {value : "Hello SAPUI5", tooltip: "This is an example tooltip", width: "100px"});

144P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 145: Hana Cloud

The constructor call above is an abbreviation of the following list of statements which are alternatively supported:

var oTextField = new sap.ui.commons.TextField("testTextField"); oTextField.setValue("Hello SAPUI5"); oTextField.setTooltip("This is an example tooltip"); oTextField.setWidth("100px");

In summary, SAPUI5 control constructors accept the following arguments in the specified order specified order:

1. An optional ID of type string, which must either be the first argument, or omitted altogether.2. One JSON-like object (object literal) as mSettings parameter that defines values for any property,

aggregation, association, or event. If a specific name for a control is ambiguous, meaning that a property has the same name as an event, the framework assumes in the following order: Property, aggregation, association. To resolve ambiguities, add the respective prefix to the key in the JSON object: "aggregation:", "association:", or "event:".

For more information about the supported parameters, see the JsDoc of the respective control.

1.3.4.3.3 UI Control API: Event Handling

You can register JS event handlers for any controls that raise events. The control API provides attach<EventName> methods as shown in the following example:

#!js

var oButton = new sap.ui.commons.Button("b1", {text:"Go", width:"80px"}); oButton.attachPress( function (oControlEvent) { alert("You clicked on Button " + oControlEvent.getSource().getId()); });

NoteYou can register the event handler for button control also directly via the button constructor.

#!js

function buttonPressed(oControlEvent) { alert("You clicked on Button " + oControlEvent.getSource().getId());};var oButton = new sap.ui.commons.Button("b1", {text:"Go", width:"80px", press:buttonPressed});

For more information on control constructors, see UI Control API: Using JSON Data in UI Control Constructors.

SAPUI5 describes events such as "press button" as "semantic events". Semantic events do not exist as native HTML browser events. The UI control implementation is responsible for mapping native browser events to semantic events. For button control, for example, the button implementation must define a mapping of the "onclick" event to the "press" event. This can be done in the button behavior file as follows:

#!js

/**

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 145

Page 146: Hana Cloud

* Function is called when button is clicked. */sap.ui.commons.Button.prototype.onclick = function(oBrowserEvent) { if (this.getEnabled()) { this.firePress({id:this.getId()}); }};

1.3.4.3.4 Data Binding

Data binding is used to bind two data or information sources together to keep them in sync. If data binding is implemented and defined properly, all changes in one data source are automatically reflected in the other data source. Usually, the UI uses data binding to bind UI controls to a data source that holds the application data, so that the controls are updated automatically whenever application data is changed.

The term data binding is also used when changes in the control cause updates in the underlying application data, such as data being entered by a user. This is called bidirectional binding or two-way binding.

Purpose

The purpose of data binding in the UI is to separate the definition of the user interface (view), the data that visualized by the application (model), and the code for the business logic for processing the data (controller). This is known as the MVC (model, view, controller) paradigm. The separation has the following advantages: It provides a better readability, maintainability, and extensibility and it allows you to change the view without touching the underlying business logic and to define several views of the same data.

Design

A Web application should support several data sources, such as JSON, XML, Atom, or OData. However, the way in which data binding is defined and implemented within the UI controls should be independent of the respective data source. It should also be possible to create a custom model implementation for data sources that are not yet covered by the framework or are domain-specific.

To achieve this, there is a Model and a Binding. The Model instance holds the data and provides methods to set the data or to retrieve data from a server. It also provides a method for creating bindings to the data. When this

146P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 147: Hana Cloud

method is called, a Binding instance is created, which contains the binding information and provides an event, which is fired whenever the bound data is changed. An element can listen to this event and update its visualization according to the new data.

Data Binding: Getting Started

This chapter gives an overview of how to use data binding in conjunction with SAPUI5 controls in a simple application. It provides information about binding data to a property of a control (property binding) as well as binding a collection of values (aggregation/list binding).

The following steps show how you use data binding in your application:

1. Decide on the model you want to use. Depending on the service or backend type, you can choose a different model that supports your backend. Currently, model implementations for JSON, XML format, and OData services are available. If no suitable model for your backend is available, you can use your own implementation.

2. Create a model instance.3. Create a control instance.4. Bind properties or lists of the control to your model.5. Unbind properties if you wish.

The following example uses the JSON model. This model is not specific to a particular backend type or implementation. The only requirement is that the data for the model is provided in JSON format.

The JSON model supports two-way/bidirectional data binding by default, which means that the model will automatically reflect changes to the view and vice versa.

Defining the Data

To define the data, proceed as follows:

1. Create a simple HTML page and load the SAPUI5 runtime.2. Create the data that you want to bind to a control property. As we are using the JSON model, you need to

provide this data in JSON format.3. Place the code into your sample page:

// JSON sample datavar data = { firstName: "John", lastName: "Doe", birthday: {day:01,month:05,year:1982}, address:[{citry:"Heidelberg"}], enabled: true};

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 147

Page 148: Hana Cloud

Creating a Data Binding Model Instance

Now you create a new JSON data model and add the data you have created to the model, so that the data is stored there and can be used for binding. Finally, you attach the model to the SAPUI5 core so that it can be used by various controls. It is also possible to attach the model to a specific control by calling oElement.setModel(oModel).

// create JSON model instancevar oModel = new sap.ui.model.json.JSONModel();// set the data for the modeloModel.setData(data);// set the model to the coresap.ui.getCore().setModel(oModel);

Creating Controls and Property Binding

Now you can create the SAPUI5 controls and define the binding to the properties. In the sample, you first define a TextView control and a TextField control. Both controls should display the firstName property of the model. The corresponding control properties have to be bound to the model property. You do this directly in the control constructor by using {} braces and specifying the path to the property in the model. You do this for both controls.

// create your controls var oTextView = new sap.ui.commons.TextView("textView", { // bind text property of textview to firstName property in the model text: "{/firstName}", tooltip: "First Name"});var oTxt = new sap.ui.commons.TextField("txtField", { // bind text property of textfield to firstName property in the model value: "{/firstName}"});

Next you create a CheckBox control and bind its checked property to the enabled property in the model. You also do this for the previously created TextField by using an alternative binding notation:

// create your controlsvar oChkBx = new sap.ui.commons.CheckBox("box", { // bind checked property against enabled property in the model checked: "{/enabled}", change: handleCheckBoxChange});// generic bind method bindProperty(control property, model property)oTxt.bindProperty("enabled", "/enabled");

function handleCheckBoxChange(oEvent){ var bEnabled = oEvent.getParameter("checked"); // modify the enabled property value in the model to reflect changes oModel.setData({enabled: bEnabled}, true); // true means merge the data instead of replacing};

The handleCheckBoxChange method sets the enabled property in the model, depending on the current checked state of the CheckBox.

148P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 149: Hana Cloud

In a last step, you create a button and define the update method for updating the firstName value in the model with the value of the TextField when the button is clicked.

// create your controlsvar oBtn = new sap.ui.commons.Button({ id: "btn", text: "Trigger Change", press: update});

function update(){ // modify the firstName property value in the model to reflect changes oModel.setData({firstName: sap.ui.getCore().byId("txtField").getValue()}, true);};

When you now open the sample application in the Web browser, you can see that the value of the firstName property is already displayed in the TextView and TextField. When you select the CheckBox, the enabled value is modified in the model (by the handleCheckBoxChange method), and the changes are immediately reflected in all control properties that are bound to this property. In this case, the TextField is enabled or disabled.

As described above, clicking the button modifies the firstName value in the model with the value of the TextView. When this happens, all control properties bound to this model field are updated immediately to reflect the changes (direction Model → View).

Additionally, since the JSON model supports two-way binding, entering a text value into the TextField will also update the corresponding value in the model, and the TextView will display the changes because it is bound to the same property (direction Model ← View).

The page then looks as shown in the following figure.

Aggregation Data Binding in a Simple Application

The above sample covers the binding of single properties to a control property. Now we want to focus on binding a collection of values, for example, binding multiple rows into a table, the values for a ListBox, or the items in a ComboBox.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 149

Page 150: Hana Cloud

In this example we use the RowRepeater control and bind it to a collection of data. Again, you start with the definition of data and set it to the model and the model to the core.

//create test datavar dataObject = { data : [{index:0, level: "Warning", description: "HAL: I'm sorry, Dave. I'm afraid I can't do that."}, {index:1, level: "Warning", description: "Windows Boot Manager has encountered a problem."}, {index:2, level: "Error", description: "Failwhale: Twitter is over capacity"}, {index:3, level: "Success", description: "Jun 25 12:20:47 pc1h kernel: lp0 on fire"}, {index:4, level: "Error", description: "Software failure. Press left mouse button to continue. Guru Meditation #00000004,#0000AACB."}, {index:5, level: "Error", description: "[root@localhost root]# Kernel Panic"}, {index:6, level: "Error", description: "That does not compute."}, {index:7, level: "Warning", description: "404 File not found. Stop messing with the URL."}, {index:8, level: "Success", description: "Blue Screen of Death."},};

//create JSON modelvar oModel = new sap.ui.model.json.JSONModel();oModel.setData(dataObject);sap.ui.getCore().setModel(oModel);

The next step covers the creation of the controls and the definition of a single Message control, which will be used as a template for all items in the RowRepeater. The Message control will hold the corresponding level and description values from the model so that these properties are bound to the model:

//create the template control that will be repeated and will display the datavar oRowTemplate = new sap.ui.commons.Message("rowTemplate", { text : "{description}", type : "{level}"});

Once the template is defined, you create the RowRepeater control. The RowRepeater has an aggregation rows, which can be any SAPUI5 control. In our case, this is the above mentioned Message control. You create an aggregation or list binding for this rows property. To do this, you specify the name of the array in the JSON model that contains the actual data (path) and also specify the Message row template:

//create the RowRepeater controlvar oRowRepeater = new sap.ui.commons.RowRepeater("rowRepeater", { design : "Standard", numberOfRows : 5, currentPage : 1, title : oTitle, // bind row aggregation rows : {path : "/data", template : oRowTemplate}});

The SAPUI5 runtime clones the row template for each entry in the JSON array for the data property and also binds the description and level properties for each message item.

The following figure shows a sample page.

150P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 151: Hana Cloud

For more information, see Data Binding in Applications [page 151].

Data Binding in Applications

This page describes how data binding can be used in SAPUI5 Web applications. It describes how to create a model instance, how to assign it to the UI, and how the controls on the UI can be bound to the model.

To use data binding in SAPUI5 Web applications, the following steps are required:

1. Creating a Model Instance2. Assigning the Model to the UI3. Defining a Binding Path4. Binding Controls to the Model

SAPUI5 provides several binding modes and provides multimodel support. For more information, see the following sections:

● Binding Modes● Multimodel Support

Creating a Model Instance

The first step when using data binding is to create a model instance and to provide the data for that model. Depending on the requirements and the availability of data formats on the server side, you can either choose one of the existing model implementations or, if none of them suits your needs, create a custom model implementation, see Implementing a Custom Model.

SAPUI5 provides the following predefined models:

● JSONModel for JSON data, see Data Binding Models: JSON Model● XMLModel for XML data, see Data Binding Models: XML Model● ResourceModel for resource bundle data, see Data Binding Models: Resource Model● ODataModel for retrieving data from OData services, see Data Binding Models: OData Model

The JSON model, XML model, and the Resource model are client-side models, meaning that the model data is loaded completely and is available on the client. Operations such as sorting and filtering are executed on the client without further server requests. The OData model is a server-side model and only loads the data requested by the user interface from the server. Any changes in data binding or list operations require a new request to the server.

The JSON model and the XML model support one-way, two-way (default), and one-time binding modes, whereas the OData model currently supports the one-way binding (default) and one-time binding modes. The Resource model only supports the one-time binding mode because it deals with static texts only. For more information on the binding modes, see Binding Modes [page 153].

Assigning the Model to the UI

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 151

Page 152: Hana Cloud

Before you can bind controls to a model instance, you have to make it known to the framework. SAPUI5 provides a flexible and modularized concept in which you can not only define one model for your applications, but define different areas in your application with different models and assign single controls to a model. You can also define nested models, for example, a JSON model defined for the application and an OData model for a table control contained in the application.

In order to find the model it should bind to, the control looks up the parent hierarchy until it finds a control or UI area that has an assigned model. A control can only bind to one model, so if you have a container control with an assigned model, all controls contained in this container can only see the local model of the container and are no longer able to bind to the global model.

Global Model

You can define a global model that can be accessed by all controls from all UI areas by using the setModel method on the SAPUI5 core object. This is useful for simple form applications or demo applications.

sap.ui.getCore().setModel(oModel);

Control-specific Model

You can also define a specific model for sections within a UI area, for example, inside a panel or for a table control. In this case, you can use the setModel method available on any control:

var oTable = sap.ui.getCore().byId("table");oTable.setModel(oModel);

Defining a Binding Path

You use binding paths to address the different properties and lists contained in a model. The binding path defines how a specific node in the hierarchical data tree can be found. A binding path contains a number of name tokens, which are separated by a separator char. In all models provided by the framework, the separator char is the slash "/".

A binding path can either be absolute or relative: Absolute binding paths start with a slash, relative binding paths start with a name token and are resolved relative to the contet of the control that is bound.

A context exists either for each entry of the aggregation in case of aggregation binding or can be set explicitly for a control by using the setBindingContext method. Relative bindings without a defined context are resolved relative to the model root.

The syntax is specific to the rspective model. For information see the respective data binding model descriptions under Data Binding Models.

Binding Controls to the Model

To retrieve data from the model for visualization in the UI, the controls have to be bound to the model, using a binding path as explained above. In general, the control itself, all properties of controls, and all multiple aggregations can be bound to a model.

152P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 153: Hana Cloud

Element binding allows to bind elements to a specific object in the model data, which will create a binding context and allow relative binding within the control and all of its children. This is especially helpful in master/detail scenarios.

Property binding allows properties of the control to get automatically initialized and updated from model data. You can only bind control properties to model properties of a matching type, or you use a formatter function or datatype to convert the data as needed.

Aggregation binding can be used to automatically create child controls according to model data. This can be done either by cloning a template control, or by using a factory function. Aggregations can only be bound to lists defined in the model, that is, to arrays in a JSON model or a collection in the OData model.

Related LinksBinding Types [page 162]

Binding Modes

A model implementation supports different binding modes. The following binding modes are available:

● One Way: One-way binding means a binding from the model to the view; value changes in the model update all corresponding bindings and the view

● Two Way: Two-way binding means a binding from the model to the view and from the view to the model; value changes in the model and in the view update all corresponding bindings and the view and model, respectively

● One Time: One-time binding means from model to view once.

The following table shows, which binding modes the respective binding models support:

Model One-way Two-way One-time

Resource model -- -- X

JSON model X X X

XML model X X X

OData model X -- X

The available binding modes are defined in sap.ui.model.BindingMode.

Default Binding Mode of Models

When a model instance is created, the instance has a default binding mode. All bindings of this model instance have this binding mode as their default.

The following table shows the supported binding modes and their default binding mode for each model implementation.

Model Default binding mode

Resource model One-time

JSON model Two-way

XML model Two-way

OData model One-way

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 153

Page 154: Hana Cloud

To change the default binding mode directly after model creation, call the setDefaultBindingMode method on the model as follows:

var oModel = new sap.ui.model.json.JSONModel();oModel.setDefaultBindingMode(sap.ui.model.BindingMode.OneWay);

In this example, all new bindings for the model will have the one-way binding mode by default.

You can, however, only set supported binding modes as default binding mode. You can check if a binding mode is supported as follows:

var oModel = new sap.ui.model.json.JSONModel();if (oModel.isBindingModeSupported(sap.ui.model.BindingMode.OneTime)) { // true oModel.setDefaultBindingMode(sap.ui.model.BindingMode.OneTime); }

Multimodel Support

You can set an additional model for an element or for the core by specifying a name for the model to identify it:

var oModel = new sap.ui.model.json.JSONModel();// define data for that modeloModel.setData({ test: "Test", enabled: true});

// define a name for that modelsap.ui.getCore().setModel(oModel, "myModel");

To create property bindings for this model call

oText.bindValue("myModel>/test").

You can also create aggregation bindings for this model by calling:

oListItem.bindProperty("text", "myModel>text");oComboBox.bindItems("myModel>/items", oListItem);

You specify the model name and following the > sign you specify the binding path to the values in the model that is to be bound.

NoteYou can create a model with an identifying name without first creating a model without a name.

Data Binding Models

The following sections introduce the data binding models provided by SAPUI5:

● Data Binding Model: ResourceModel● Data Binding Model: JSONModel● Data Binding Model: XMLModel● Data Binding Model: ODataModel

154P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 155: Hana Cloud

Data Binding Models: ResourceModel

The ResourceModel is used as a wrapper for resource bundles. You can, for example, bind texts of a control to language-dependent resource bundle properties.

Creating the Model Instance

You can instantiate a ResourceModel as follows:

● With a bundleName, that is, the name of a resource bundle and equals a SAPUI5 module name within the require/declare concept, see Modularization and Dependency Management

● With a bundleUrl that points to the resource bundle

If you use the bundle name, the file must have the .properties suffix. If you do not specify a locale, the system uses the login language. For more information about localization and resource bundles, see Localized Texts.

var oModel = new sap.ui.model.resource.ResourceModel({bundleName:"myBundle",locale:"en"});

NoteIn this ResourceModel implementation you cannot pass parameters to your texts within the resource bundle. If you have to pass parameters, you must do this on your own. Therefore, you can load the bundle yourself or retrieve it from the model.

var myBundle = oModel.getResourceBundle();

After the instance has been created, you have a model containing the resource bundle texts as data.

For a complete overview of the available methods and parameters, see the API reference.

Binding Path Syntax

The ResourceModel has a simple binding path syntax, as it contains only a flat list of properties. The following example shows a simple ResourceModel that illustrates the possible binding paths:

Resource bundle content:

CLOSE_BUTTON_TEXT=CloseOPEN_BUTTON_TEXT=OpenCANCEL_BUTTON_TEXT=Cancel...

Binding paths within the model:

CLOSE_BUTTON_TEXTOPEN_BUTTON_TEXTCANCEL_BUTTON_TEXT

Data Binding Models: JSONModel

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 155

Page 156: Hana Cloud

The JSONModel can be used to bind controls to JavaScript object data, which is usually serialized in the JSON format. The JSONModel is a client-side model and, therefore, intended for small datasets, which are completely available on the client. The JSONModel does not support mechanisms for server-based paging or loading of deltas. It supports, however, two-way binding.

Creating the Model Instance

The JSONModel is used for JSON data. You can create a model instance as follows:

var oModel = new sap.ui.model.json.JSONModel();

After the instance has been created, there are different options to get the data into the model. The easiest option is to set data by using the setData method:

oModel.setData({ firstName: "Peter", lastName: "Pan"});

NoteThe correct JSON notation uses double quotes for the keys and string values.

Usually, you do not define your data inline in the application but load it from a server-side service using an XHR request. The JSONModel, however, also has a loadData method, which loads the JSON data from the specified URL asynchronously and applies it to the model:

oModel.loadData("data.json");

For a complete overview of the available methods and parameters, see the API reference.

Binding Path Syntax

As the JSONModel only consists of named objects (properties, arrays, or nested objects), it has a simple binding path syntax. The following example shows a simple JSONModel with the different binding paths:

{ company: { name: "Treefish Inc", info: { employees: 3, }, contacts: [ { name: "Barbara", phone: "873" }, { name: "Gerry", phone: "734" },

156P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 157: Hana Cloud

{ name: "Susan", phone: "275" } ] }}

Absolute binding paths within this model:

/company/name/company/info/employees/company/contacts

Relative binding paths within the "/company" context:

nameinfo/employeescontacts

Relative binding paths within an aggregation binding of "/company/contacts":

namephone

Custom Sorting and Filtering

As all data is available on the client, sorting and filtering are also implemented in JavaScript. This allows the usage of custom sorting and filtering methods in the JSONModel. To define custom methods, set the fnCompare method on the Sorter object or the fnFilter method on the Filter object after creating it.

The fnFilter method of the Filter gets the value to test as the only parameter and returns, whether the row with the given value should be filtered or not.

var oFilter = new sap.ui.model.Filter("property");oFilter.fnFilter = function(value) { return (value > 100); };

The fnCompare method of the Sorter gets the two values to compare as parameters and returns -1, 0 or 1, dependent which of the two values should be ordered before the other.

var oSorter = new sap.ui.model.Sorter("property");oSorter.fnCompare = function(value1, value2) { if (value1 < value2) return -1; if (value1 == value2) return 0; if (value1 > value2) return 1;};

Data Binding Models: XMLModel

The XMLModel allows to bind controls to XML data. It is a client-side model inteded for small datasets, which are completely available on the client. The XMLModel does not contain mechanims for server-based paging or loading of deltas. It supports two-way binding.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 157

Page 158: Hana Cloud

Creating the Model Instance

The XMLModel can be used for all kinds of XML data. To create a model instance, call the constructor:

var oModel = new sap.ui.model.xml.XMLModel();

The XMLModel also has a setData method. As XML documents cannot be embedded inline in JavaScript, the XMLModel uses an XML document reference as a parameter.

oModel.setData(oXMLDocument);

To create inline XML data or to get XML data as a string, the XMLModel provides a setXML method. This method takes XML in text format and uses the browser's XML parser to create a document.

oModel.setXML("<?xml version=\"1.0\"?><some><xml>data</xml></some>");

Usually, you load your data from the server using an HTTP-based service, so the loadData method provides an easy way to load XML data from the given URL:

oModel.loadData("data.xml");

For a complete listing of the available methods and parameters, see the API Reference.

Binding Path Syntax

XML differentiates between attributes and content, XML has no arrays and defines lists as multiple elements with the same name instead. This makes data binding in XMLModels more difficult. For attributes, a special selector using the "@" character exists and "text()" can be used to reference the content text of an element. Lists are referenced by using the path to the multiple element.

NoteFor the XMLModel the root must not be included in the path.

#!xml<companies> <company name="Treefish Inc"> <info> <employees>3</employees> </info> <contact phone="873">Barbara</contact> <contact phone="734">Gerry</contact> <contact phone="275">Susan</contact> </company></companies>

Absolute binding paths within this model:

/company/@name/company/info/employees

158P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 159: Hana Cloud

Relative binding paths within the "/company" context:

@nameinfo/employees/text()

Relative binding paths within an aggregation binding of "/company/contact":

text()@phone

NoteIn a similar JSONModel you would use /companies/company/locations as binding path for the "locations" collection. In an XMLModel the respective collection binding path is: /company/locations/location.

XML Namespace Support

The XMLModel does support documents using XML namespaces. For this purpose, you must declare namespaces using the setNameSpace method. The namespace prefixes do not necessarily need to be the same as in the XML document, they only used in the binding paths which are used to address nodes in the document.

Assumed this sample XML document:

<data xmlns="http://tempuri.org/base" xmlns:ext="http://tempuri.org/ext"> <ext:entry id="1" value="foo" /> <ext:entry id="1" value="foo" /></data>

The namespaces must be declared in the JavaScript like this, to be able to bind to them:

var oModel = new sap.ui.model.xml.XMLModel(oXMLDoc);oModel.setNameSpace("http://tempuri.org/base");oModel.setNameSpace("http://tempuri.org/ext", "e"); [...]oTable.bindRows("/e:entry");

Custom Sorting and Filtering

As all data is available on the client, sorting and filtering are also implemented in JavaScript. This allows the usage of custom sorting and filtering methods in the XMLModel. To define custom methods, set the fnCompare method on the Sorter object or the fnTest method on the Filter object after creating it.

The fnTest method of the Filter gets the value to test as the only parameter and returns, whether the row with the given value should be filtered or not.var oFilter = new sap.ui.model.Filter("property");oFilter.fnFilter = function(value) { return (value > 100);}; The fnCompare method of the Sorter gets the two values to compare as parameters and returns -1, 0 or 1, dependent which of the two values should be ordered before the other.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 159

Page 160: Hana Cloud

var oSorter = new sap.ui.model.Sorter("property");oSorter.fnCompare = function(value1, value2) { if (value1 < value2) return -1; if (value1 == value2) return 0; if (value1 > value2) return 1;}; Data Binding Models: ODataModel

The ODataModel enables binding of controls to data from OData services. The ODataModel is a server-side model: the dataset is only available on the server and the client only knows the currently visible rows and fields. Sorting and filtering on the client is not possible. The client has to send a request to the server to accomplish these tasks.

The default binding mode of the ODataModel is one-way, but as experimental write support is implemented, two-way binding can be enabled. For more information, see OData Write Suport.

NoteBe aware of the Same-Origin-Policy security concept which prevents access to backends on different domains or sites.

Creating the Model Instance

The service URL is the first parameter of the constructor. One ODataModel instance can only cover one OData service. If you need access to multiple services, you have to create multiple instances of the ODataModel.

var oModel = new sap.ui.model.odata.ODataModel("http://services.odata.org/Northwind/Northwind.svc/");

Requests to the service to fetch data are made automatically according to the data bindings defined in the controls.

For additional methods and parameters, see the API Reference.

Binding Path Syntax

You access the data provided by the ODataModel according to the structure of the OData service as defined in the metadata of a service. The syntax of the binding path matches the URL path relative to the service URL used in OData to access specific entries or collections. URL parameters such as filters cannot be added to a binding path. The following samples of bindings within the ODataModel are taken from the well-known Northwind demo service.

Absolute binding paths:

/Customers/Customers('ALFKI')/Orders

Relative binding paths within a Customer context:

CompanyNameAddressOrders

160P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 161: Hana Cloud

Relative binding paths within an aggregation binding of "/Customer('ALFKI')/Orders:

OrderIDShipNameShipAdressEmployee/LastNameOrder_Details/Discount

Adding Additional Parameters

When using OData services, you can use URL parameters for configuration. SAPUI5 sets most of the required URL parameters automatically according to the data binding. Two options for adding custom parameters to the request exist: URL parameters can be appended to the service URL and a map of parameters can be passed when using bindElement or bindAggregation.

Additional parameters, which are added to the OData service URL, are included in every request sent to the OData server. This is useful for authentication tokens or general configuration options.

var oModel = new sap.ui.model.odata.ODataModel("http://myserver/MyService.svc/?custom1=value1&custom2=value2");

For other parameters it makes no sense to include them in every request. These parameters should only be added to specific aggregation or element bindings, for example, $expand or $select. For this, the binding methods can pass a map of parameters, which is then included in all requests for this specific binding. Currently, the ODataModel only supports $expand and $select.

Expand Parameters

To use the $expand parameter see the following snippet below:

oControl.bindElement("/Category(1)", {expand: "Products"});

oTable.bindRows({ path: "/Products", parameters: {expand: "Category"}});

In the first example all products of Category(1) are embedded inline in the server response and loaded in one request. In the second example the Category for all Products is embedded inline the response for each product.

Select Parameter

The $select parameter returns only the specified properties of requested entries.

oControl.bindElement("/Category(1)", {expand: "Products", select: "Name,ID,Products"});

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 161

Page 162: Hana Cloud

oTable.bindRows({ path: "/Products", parameters: {select: "Name,Category"}});

In the first example the properties Name and ID ofCategory(1) and all properties of the embedded products are returned. In the second example the properties Name and Category are included for each product. The Category property will contain a link to the related Category entry.

Binding Types

The following sections introduce the data binding types provided by SAPUI5:

● Property Binding● Aggregation Binding● Element Binding

Property Binding

To define a property binding on a control, the following two options exist:

● In the settings object in the constructor of a control● Using the bindProperty method of a control

Once you have defined the property binding, the property is updated automatically every time the bound model property value is changed.

The most convenient way to define a property binding, which is sufficient in most cases, is to include the binding path within curly brackets as a string literal in the settings object:

var oTextField = new sap.ui.commons.TextField({ value: "{/company/name}"});

Alternatively, you can use an extended syntax for property bindings. This extended syntax allows you to define additional binding information to be contained in the settings object, such as a formatter function. In this case you use a JS object instead of a string literal. This must contain a path property containing the binding path and can contain additional properties:

var oTextField = new sap.ui.commons.TextField({ value: { path: "/company/name", mode: sap.ui.model.BindingMode.OneWay }});

Depending on the use case, it can be useful to define the binding at a later time, using the bindProperty method:

oTextField.bindProperty("value", "/company/name");

This option also allows the use of the same object-literal as in the constructor to define the binding

oTextField.bindProperty("value", { path: "value", type: new sap.ui.model.type.Integer()});

162P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 163: Hana Cloud

Some controls offer convenience methods for the main properties of a control that are most likely to be bound by an application.

oTextField.bindValue("/company/name");

To remove a property binding, you can use the unbindProperty method. The property binding is removed automatically whenever a control is destroyed.

oTextField.unbindProperty("value");

For a complete list of supported parameters, see the API Reference.

Formatting Property Values

The values in the data are often represented in some internal format and need to be converted to an external format for visual representation. This is especially necessary for numbers, dates, and times with locale dependent external formats. SAPUI5 provides two different conversion options: Formatter functions allow one-way conversion only, while data types can also be used for two-way binding as they cannot only format, but also parse user input. You can choose freely for each binding, depending on your scenario.

The formatter function can either be passed as a third parameter to the bindProperty method, or contained in the binding info with the key "formatter". It has a single parameter value, which is the value which needs to be formatted to an external representation, and is executed as a member of the control, so can access additional control properties or model data.oTextField.bindProperty("value", "/company/title", function(sValue) { return sValue && sValue.toUpperCase();});

oControl = new sap.ui.commons.TextField({ value: { path:"/company/revenue", formatter: function(fValue) { if (fValue) { return "> " + Math.floor(fValue/1000000) + "M"; } return "0"; } }}) The formatter function, as it can contain any JavaScript, can not only be used for formatting a value, but can also do type conversion or calculate results from a given value, for example to show a special traffic light image depending on a boolean value:oImage.bindProperty("src", "/company/trusted", function(bValue) { return bValue ? "green.png" : "red.png";});

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 163

Page 164: Hana Cloud

Using Data Types

The type system provides the possibility to format and parse data, as well as validating if the entered data is within defined constraints. You can define a type to be used for a property binding, by passing it as a third parameter in bindProperty or by adding it to the binding information with the key "type".

oTextField.bindProperty("value", "/company/title", new sap.ui.model.type.String());

oControl = new sap.ui.commons.TextField({ value: { path:"/company/revenue", type: new sap.ui.model.type.Float({ minFractionDigits: 2, maxFractionDigits: 2 }) }}) You can define custom types by inheriting from sap.ui.model.SimpleType and implementing the three methods formatValue, parseValue and validateValue. formatValue will be called whenever the value in the model is changed to convert it to the type of the control property it is bound to and may throw a FormatException. parseValue is called, whenever the user modified a value in the UI and the change is transported back into the model. It may throw a ParseException in case the value cannot be converted. In case of successful parsing validateValue is called to check additional constraints, like minimum or maximum value, and throws a ValidateException in case constraints are violated.

sap.ui.model.SimpleType.extend("sap.test.PLZ", { formatValue: function(oValue) { return oValue; }, parseValue: function(oValue) { return oValue; }, validateValue: function(oValue) { if (!/^(\d{5})?$/.test(oValue)) { throw new sap.ui.model.ValidateException("PLZ must have 5 digits!"); } }});

For more information, see Using the Data Binding Type System.

Binding Mode

By default, all bindings of a model instance have the default binding mode of the model. You can change this behavior. When creating a PropertyBinding, you can specify a different binding mode, which is then used exclusively for this specific binding. Of course, a binding can only have a supported binding mode of the model.

var oModel = new sap.ui.model.json.JSONModel();// default binding mode is Two WayoModel.setData(myData);sap.ui.getCore().setModel(oModel);var oText = new sap.ui.commons.TextField();// bind value property one way only // propertyname, formatter function, binding modeoText.bindValue("/firstName", null, sap.ui.model.BindingMode.OneWay);oText.placeAt("target1");

164P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 165: Hana Cloud

oText = new sap.ui.commons.TextField();// bind value property two way which is the defaultoText.bindValue("/firstName");oText.placeAt("target2");}

In the example above, two TextFields are created and their value property is bound to the same property in the model. The first TextField binding has a one-way binding mode, whereas the second TextField has the default binding mode of the model instance, which is two-way. So, when text is entered in the first TextField, the value will not be changed in the model. This happens only if text is entered in the second TextField. Then, of course, the value of the first TextField will be updated as it has a one-way binding, which means from model to view.

Aggregation Binding

You can define aggregation binding either in the settings object in the constructor or by calling the bindAggregation method. Aggregation binding requires the definition of a template, which is cloned for each bound entry of the list. For each clone that is created, the binding context is set to the respective list entry, so that all bindings of the template are resolved relative to the entry. The aggregated elements are destroyed and recreated whenever the bound list in the data model is changed.

Controls for the visualization of large data sets, for example Table or RowRepeater, only create clones for the currently visible entries and not for all list entries by using a custom updateAggregation method.

To bind an aggregation, you create a template or provide a factory function, which is then passed when defining the aggregation binding itself. In the settings object, this looks as follows:

var oItemTemplate = new sap.ui.core.ListItem({text:"{name}"});var oComboBox = new sap.ui.commons.ComboBox({ items: { path: "/company/contacts", template: oItemTemplate }});

You can also define the aggregation binding by using the bindAggregation method of a control:

oComboBox.bindAggregation("items", "/company/contacts", new sap.ui.core.ListItem({text:"{name}"}));

Some controls have a typed binding method for aggregations that are likely to be bound by the application:

oComboBox.bindItems("/company/contacts", oItemTemplate);

To remove an aggregation binding, you can use the unbindProperty method. The aggregation binding is then removed automatically whenever a control is destroyed.

oComboBox.unbindAggregation("items");

For more information, see the API Reference.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 165

Page 166: Hana Cloud

Using Template Controls

For structured data with list entries with the same properties using template controls within the aggregation binding is recommended. A template is not necessarily a single control as in the examples above, but can be a tree of controls. For each list entry, a deep clone of the template is created and added to the bound aggregation.

var oMatrixLayout = new sap.ui.commons.layout.MatrixLayout();

var oRowTemplate = new sap.ui.commons.layout.MatrixLayoutRow({ cells: [ new sap.ui.commons.layout.MatrixLayoutCell({ content: new sap.ui.commons.Label({text:"Name:"}) }), new sap.ui.commons.layout.MatrixLayoutCell({ content: new sap.ui.commons.TextView({text:"{name}"}) }) ]});

oMatrixLayout.bindAggregation("rows", "/company/contacts", oRowTemplate);

Using Factory Functions

The factory function is a more powerful approach for creating controls from model data. The factory function is called for each list entry to create the controls necessary to represent the current entry. The developer can decide, whether it is the same control with different properties or even a completely different control for each entry.

The factory function gets the parameters sId. These parameters must be used as they identify the created control and the context object oContext, which allows accessing data from the list entry. It returns an instance of sap.ui.core.Element.

oContainer.bindAggregation("content", "/company/properties", function(sId, oContext) { var value = oContext.getProperty("value"); switch(typeof value) { case "string": return new sap.ui.commons.TextField(sId, { value: { path: "value", type: new sap.ui.model.type.String(); } }); case "number": return new sap.ui.commons.TextField(sId, { value: { path: "value", type: new sap.ui.model.type.Float(); } }); case "boolean": return new sap.ui.commons.CheckBox(sId, { checked: { path: "value" } }); }});

166P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 167: Hana Cloud

Initial Sorting and Filtering for Aggregation Binding

You can provide initial sorting and filtering when specifying the aggregation binding. Proceed as follows:

● Define a sorter and/or filters:

var oSorter = new sap.ui.model.Sorter("name", true); // sort descendingvar oFilter1 = new sap.ui.model.Filter("name", sap.ui.model.FilterOperator.StartsWith, "M");var oFilter2 = new sap.ui.model.Filter("name", sap.ui.model.FilterOperator.Contains, "Paz");var oFilter3 = new sap.ui.model.Filter("name", sap.ui.model.FilterOperator.BT, "A","G"); // name between A and G

● Hand the sorter and/or filters to the aggregation binding:

var oComboBox = new sap.ui.commons.ComboBox({ items: {path:"/company/contacts", template:oItemTemplate, sorter:oSorter, filters:[oFilter1,oFilter2,oFilter3]}});

You can also use the other aggregation binding possibilities (for example bindAggregation, bindItems) and provide the sorter and filters as parameters.

Manual Sorting and Filtering for Aggregation Binding

To sort/filter data manually after the aggregation binding is complete you can do so by getting the corresponding binding and calling the sort/filter function:

var oSorter = new sap.ui.model.Sorter("name", true); // sort descendingvar oFilter1 = new sap.ui.model.Filter("name", sap.ui.model.FilterOperator.StartsWith, "M");var oFilter2 = new sap.ui.model.Filter("name", sap.ui.model.FilterOperator.Contains, "Paz");var oFilter3 = new sap.ui.model.Filter("name", sap.ui.model.FilterOperator.BT, "A","G"); // name between A and G

// manual sortingoTable.getBinding("rows").sort(oSorter);

// manual filteringoTable.getBinding("rows").filter([oFilter1,oFilter2,oFilter3]);oComboBox.getBinding("items").filter([oFilter1,oFilter2,oFilter3]);

To get the binding of a control you have to know the name of the aggregation which is for example 'rows' for the table control.

For more information about the various sorting and filter methods and operators, see the documentation for Filter, Sorter, and Filter operations in the API Reference.

Element Binding

Binding an element allows to set the binding context of the element to the object referenced by the given binding path. Thus, all relative bindings within the control and all of its children are resolved relative to this object. For server-side models, the element binding triggers the request to the server to load the referenced object in case it is not yet available on the client.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 167

Page 168: Hana Cloud

Element bindings can also be defined relatively. In case of relative element bindings, the binding context is updated when the parent binding context is changed.

To define an element binding, use the bindElement method on a control:

oControl.bindElement("/company");oControl.bindProperty("value", "name");

Element binding is especially interesting for containers or layouts containing many controls that are all visualizing properties of the same model object.

var oMatrixLayout = new sap.ui.commons.layout.MatrixLayout();oMatrixLayout.bindElement("/company");oMatrixLayout.createRow( new sap.ui.commons.Label({text: "Name:"}), new sap.ui.commons.TextField({value: "{name}"}));

oMatrixLayout.createRow( new sap.ui.commons.Label({text: "Revenue:"}), new sap.ui.commons.TextField({value: "{revenue}"}));oMatrixLayout.createRow( new sap.ui.commons.Label({text: "Employees:"}), new sap.ui.commons.TextField({value: "{employees}"}));

Setting a New Context for the Binding (Master Detail)

You create a new binding context for an element that is used to resolve bound properties or aggregations relative to the given path. You can use this method if the existing binding path changes or has not been provided before, for example in master detail scenarios.

Below is a simple example:

var data = {clients:[{firstName:"Donald", lastName:"Duck"}]};...// create and set model herevar oLabel = new sap.ui.commons.Label("myLabel");oLabel.bindProperty("text", "firstName");oLabel.bindElement("/clients/0");

The bindProperty method binds the text value of the label to the firstName property in the model. As the path to this property in the model is not set, this will not resolve. To resolve the binding, you use the bindElement method which creates a new context from the specified relative path.

To remove the current binding context, call the unbindElement method on the label. By this, all bindings now resolve relative to the parent context again.

You can also use the bindElement method in conjunction with aggregation binding:

var data = {clients:[ {firstName:"Donald", lastName:"Duck"}, items: [ {name: "iPhone"}, {name:"iPad"} ] } ]};...// create and set model herevar oLB = new sap.ui.commons.ListBox("myLb", {height:"100px"});

168P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 169: Hana Cloud

var oItemTemplate = new sap.ui.core.ListItem(); oItemTemplate.bindProperty("text", "name");oLB.bindAggregation("items", "items", oItemTemplate);oLB.bindElement("/clients/0");

In this example, the ListBox is used to display the detailed data (items data) for a specified client. Another control can now be used to show the master data (client data) in the same way as in the first example with the label.

This example only works if the additional detailed data in the model which should be displayed in the ListBox (items in the example) is nested in the corresponding parent data (the client in the example). As you can see in the model, the items are contained in the client data.

You can also use a filtering function, for example in a table, to display detailed data for selected master data. In this case, nested data is not necessary in the model.

Using the Data Binding Type System

Data binding supports the definition of types which can be handed over when binding properties. These types define the data type for properties in the model. The values are then automatically formatted for display in the UI. In addition to this, the input values in UI controls are parsed and converted back to the defined type in the model. If an error occurs during formatting or parsing, the following exception occurs: sap.ui.model.FormatException / sap.ui.model.ParseException.

All types inherit from the abstract sap.ui.model.Type class. A subclass of this class is sap.ui.model.SimpleType. The currently available types inherit from SimpleType class.

You can generate the following parameters for each SimpleType in the constructor:

● format options: Format options define how a value is formatted and displayed in the UI.● constraints: Constraints are optional and define how an input value entered in the UI should look like.

During parsing the value is validated against these constraints. For example, a String type has a constraint for maxLength and minLength which are automatically validated when parsing the input values.

The following sections describe the available constraints and format options for each type.

Example: Using Data Types

The following example shows how to use data types:

A sap.ui.model.type.Float type is created with the formatting options minimum/maximum fraction digits equals 2 and a maximum value constraint of 10:

// creating of a float type with 2 format options and one constraintvar oFloat = new sap.ui.model.type.Float( { minFractionDigits: 2, maxFractionDigits: 2 }, { maximum: 10 });

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 169

Page 170: Hana Cloud

To use the defined data type for the binding, proceed as follows:

// specify the binding and the type directly in the control constructorvar oText = new sap.ui.commons.TextField({value: {path: "/sliderValue", type: oFloat}});// or alternatively do it afterwardsoText.bindValue("/sliderValue", oFloat);

Input parsing and output formatting are now carried out automatically. If, for example, the float value in the model is 2.3345, the text field displays the value 2.33. A user enters a value which is validated after user entry. To be valid, the entered value must be lower than 10.

Handling Wrong User Input

You can register a handler to validate, parse, and format issues by using the following functions of sap.ui.getCore():

● attachFormatError● attachParseError● attachValidationError● attachValidationSuccess

Simple Types

The following sections introduce the simple types that are currently available for data binding in SAPUI5.

NoteUse the following data types only with data binding.

● sap.ui.model.type.Integer● sap.ui.model.type.Float● sap.ui.model.type.String● sap.ui.model.type.Boolean● sap.ui.model.type.Date● sap.ui.model.type.Time● sap.ui.model.type.DateTime

The types use the below listed formatter classes. The formatters can, however, also be used standalone for formats, such as dates.

NoteThe formatter classes do not provide validation.

List of formatter classes:

● sap.ui.core.format.DateFormat● sap.ui.core.format.NumberFormat

sap.ui.model.type.Integer

The Integer type represents an integer value. The source value (value given in the model) must be given as a number and is transformed into the type of the bound control property:

170P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 171: Hana Cloud

● float: Value is rounded using Math.floor● integer: No transformation needed● string: Value is formatted or parsed according to the given output pattern

Examples how an Integer type can be initialized:

// The source value is given as Javascript number. Output is transformed into the type of the bound control property.// If this type is "string" (e.g. the value property of the TextField control) the used default output pattern parameters depend on locale and fixed settings.var oType = new sap.ui.model.type.Integer();

// The source value is given as Javascript number. Output is transformed into the type of the bound control property.// If this type is "string" (e.g. the value property of the TextField control) the given output pattern is used (parameters which are not specified are taken from the default pattern)

oType = new sap.ui.model.type.Integer({ minIntegerDigits: 1, // minimal number of non-fraction digits maxIntegerDigits: 99, // maximal number of non-fraction digits minFractionDigits: 0, // minimal number of fraction digits maxFractionDigits: 0, // maximal number of fraction digits groupingEnabled: false, // enable grouping (show the grouping separators) groupingSeparator: ",", // the used grouping separator decimalSeparator: "." // the used decimal separator});

The Integer type supports the following validation constraints:

● maximum● minimum

sap.ui.model.type.Float

The Float type represents a float value. The source value (value given in the model) must be given as a number and is transformed into the type of the bound control property:

● float: No transformation needed● integer: Value is rounded using Math.floor● string: Value is formatted or parsed according to the given output pattern

Examples how a Float type can be initialized:

// The source value is given as Javascript number. Output is transformed into the type of the bound control property.// If this type is "string" (e.g. the value property of the TextField control) the used default output pattern parameters depend on locale and fixed settings.

var oType = new sap.ui.model.type.Float();

// The source value is given as Javascript number. Output is transformed into the type of the bound control property.// If this type is "string" (e.g. the value property of the TextField control) the given output pattern is used (parameters which are not specified are taken from the default pattern)

oType = new sap.ui.model.type.Float({ minIntegerDigits: 1, // minimal number of non-fraction digits maxIntegerDigits: 99, // maximal number of non-fraction digits minFractionDigits: 0, // minimal number of fraction digits maxFractionDigits: 99, // maximal number of fraction digits groupingEnabled: true, // enable grouping (show the grouping separators)

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 171

Page 172: Hana Cloud

groupingSeparator: ",", // the used grouping separator decimalSeparator: "." // the used decimal separator});

The Float type supports the following validation constraints:

● maximum● minimum

sap.ui.model.type.String

The String type represents a string. The source value (value given in the model) must be given as a number and is transformed into the type of the bound control property:

● string: No transformation needed● integer/float: String is parsed accordingly● boolean: "true" or "X" are interpreted as true, false, and " " as false

The string type does not have any format options.

Example how a String type can be initialized:

// The source value is given as string. The length of the string must not greater than 5.var oType = new sap.ui.model.type.String(null, {maxLength: 5});

The String type supports the following validation constraints:

● maxLength (expects an integer number)● minLength (expects an integer number)● startsWith (expects a string)● startsWithIgnoreCase (expects a string)● endsWith (expects a string)● endsWithIgnoreCase (expects a string)● contains (expects a string)● equals (expects a string)● search (expects a regular expression)

sap.ui.model.type.Boolean

The Boolean type represents a string. The source value (value given in the model) must be given as boolean and is transformed into the type of the bound control property:

● boolean: No transformation needed● string: "true" or "X" are interpreted as true, "false" and "" as false

The Boolean type has no format or validation constraint options.

Example how a Boolean type can be initialized:

// The source value is given as boolean.var oType = new sap.ui.model.type.Boolean();

sap.ui.model.type.Date

The Date type represents a date (without time). It transforms a source value (given value in the model) into a formatted date string and the other way round.

172P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 173: Hana Cloud

The format patterns must be defined in LDML Date Format notation. For the output, the use of a style ("short, "medium", "long" or "full") instead of a pattern is preferred, as it will automatically use a locale-dependent date pattern.

Examples how a Date type can be initialized:

// The source value is given as Javascript Date object. The used output pattern depends on the locale settings (default).var oType = new sap.ui.model.type.Date();// The source value is given as Javascript Date object. The used output pattern is "yy-MM-dd": e.g. 09-11-27oType = new sap.ui.model.type.Date({pattern: "yy-MM-dd"}); // The source value is given as string in "yyyy/MM/dd" format. The used output style is "long". The styles are language dependent.// The following styles are possible: short, medium (default), long, full// This usecase might be the common one.oType = new sap.ui.model.type.Date({source: {pattern: "yyyy/MM/dd"}, style: "long"}); // The source value is given as string in "yyyy/MM/dd" format. The used output pattern is "EEEE, MMMM d, yyyy": e.g. Saturday, August 22, 2043oType = new sap.ui.model.type.Date({source: {pattern: "yyyy/MM/dd"}, pattern: "EEEE, MMMM d, yyyy"}); // The source value is given as timestamp. The used output pattern is "dd.MM.yyyy": e.g. 22.12.2010oType = new sap.ui.model.type.Date({source: {pattern: "timestamp"}, pattern: "dd.MM.yyyy"}); // The source value is given as string. The used input pattern depends on the locale settings (default). The used output pattern is "dd '|' MM '|' yyyy": e.g. 22 | 12 | 2010oType = new sap.ui.model.type.Date({source: {}, pattern: "dd.MM.yyyy"});

The Date type supports the following validation constraints:

● maximum (expects an date presented in the source-pattern format)● minimum (expects an date presented in the source-pattern format)

sap.ui.model.type.Time

The Time type represents a time (without date). It transforms a source value (given value in the model) into a formatted time string and the other way round.

The format patterns must be defined in LDML Date Format notation. For the output, the use of a style ("short, "medium", "long" or "full") instead of a pattern is preferred, as it will automatically use a locale dependent time pattern.

Examples how a Time type can be initialized:

// The source value is given as Javascript Date object. The used output pattern depends on the locale settings (default).var oType = new sap.ui.model.type.Time();// The source value is given as Javascript Date object. The used output pattern is "hh-mm-ss": e.g. 09-11-27oType = new sap.ui.model.type.Time({pattern: "hh-mm-ss"}); // The source value is given as string in "hh-mm-ss" format. The used output style is "short". The styles are language dependent.// The following styles are possible: short, medium (default), long, full// This usecase might be the common one.oType = new sap.ui.model.type.Date({source: {pattern: "hh-mm-ss"}, style: "short"}); // The source value is given as string in "hh/mm/ss/SSS" format. The used output pattern is "HH:mm:ss '+' SSS 'ms'": e.g. 18:48:48 + 374 msoType = new sap.ui.model.type.Time({source: {pattern: "hh/mm/ss/SSS"}, pattern: "HH:mm:ss '+' SSS 'ms'"}); // The source value is given as timestamp. The used output pattern is "HH 'Hours'

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 173

Page 174: Hana Cloud

mm 'Minutes'": e.g. 18 Hours 48 MinutesoType = new sap.ui.model.type.Time({source: {pattern: "timestamp"}, pattern: "HH 'Hours' mm 'Minutes'"}); // The source value is given as string. The used input pattern depends on the locale settings (default). The used output pattern is "hh:mm a": e.g. 06:48 PMoType = new sap.ui.model.type.Time({source: {}, pattern: "hh:mm a"});

The Time type supports the following validation constraints:

● maximum (expects an time presented in the source-pattern format)● minimum (expects an time presented in the source-pattern format)

sap.ui.model.type.DateTime

The DateTime type represents an exact point of time (date and time). It transforms a source value (given value in the model) into a formatted date+time string and the other way round.

The format patterns must be defined in LDML Date Format notation. For the output, the use of a style ("short, "medium", "long" or "full") instead of a pattern is preferred, as it will automatically use a locale-dependent date and time pattern.

CautionWhen talking about exact points in time, time zones are imported. The formatted output of the DateTime type currently shows the "local" time which equals the time settings of the machine on which the browser runs. If the source value is given as a Javascript Date object or as a timestamp, the exact moment is sufficiently defined. For string source values this value is interpreted in "local" time if it does not explicitly have a time zone. Currently, all accepted time zone notations must be based on GMT/UTC.

Examples how a DateTime type can be initialized:

// The source value is given as Javascript Date object. The used output pattern depends on the locale settings (default).var oType = new sap.ui.model.type.DateTime();// The source value is given as Javascript Date object. The used output pattern is "yyyy/MM/dd HH:mm:ss": e.g. 2011/04/11 09:11:27oType = new sap.ui.model.type.DateTime({pattern: "yyyy/MM/dd HH:mm:ss"}); // The source value is given as string in "yyyy/MM/dd HH:mm:ss" format. The used output style is "full". The styles are language dependent.// The following styles are possible: short, medium (default), long, full// This usecase might be the common one.oType = new sap.ui.model.type.Date({source: {pattern: "yyyy/MM/dd HH:mm:ss"}, style: "full"}); // The source value is given as string in "dd.MM.yyyy HH:mm:ss" format (no timezone given). The used output pattern is "MMMM d, yyyy, HH:mm:ss.SSS": e.g. August 22, 2043, 18:48:48.374oType = new sap.ui.model.type.DateTime({source: {pattern: "dd.MM.yyyy HH:mm:ss"}, pattern: "MMMM d, yyyy, HH:mm:ss.SSS"});// The source value is given as timestamp. The used output pattern is "dd.MM.yyyy HH:mm": e.g. 22.12.2010 13:15oType = new sap.ui.model.type.DateTime({source: {pattern: "timestamp"}, pattern: "dd.MMM.yyyy HH:mm"}); // The source value is given as string. The used input pattern depends on the locale settings (default). The used output pattern is "hh-mm-ss '/' yy-MM-dd": e.g. 06-48-48 / 43-08-22oType = new sap.ui.model.type.DateTime({source: {}, pattern: "hh-mm-ss '/' yy-MM-dd"}); // The source value is given as string in "dd.MM.yyyy HH:mm:ss X" format (timezone is defined in ISO8601 format, e.g. "+02:00"). The used output pattern depends on the locale settings (default).oType = new sap.ui.model.type.DateTime({source: {pattern: "dd.MM.yyyy HH:mm:ss X"}});

174P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 175: Hana Cloud

// The source value is given as string in "dd.MM.yyyy HH:mm:ss Z" format (timezone is defined in RFC822 format, e.g. "+0200"). The used output pattern depends on the locale settings (default).oType = new sap.ui.model.type.DateTime({source: {pattern: "dd.MM.yyyy HH:mm:ss Z"}});// The source value is given as string in "dd.MM.yyyy HH:mm:ss z" format (timezone is currently defined as e.g. "GMT+02:00", "UTC+02:00", "UT+02:00" or "Z" (shortcut for "UTC+00:00")).// The used output pattern depends on the locale settings (default).oType = new sap.ui.model.type.DateTime({source: {pattern: "dd.MM.yyyy HH:mm:ss z"}});

The DateTime type supports the following validation constraints:

● maximum (expects an dateTime presented in the source-pattern format)● minimum (expects an dateTime presented in the source-pattern format)

Data Types for Use Without Data Binding

The simple types in the previous sections are not intended to be used without data binding. But they use formatter classes, which can also be used standalone to format, for example, dates. The formatter classes do not provide validation.

You can use the following formatter classes:

● sap.ui.core.format.DateFormat● sap.ui.core.format.NumberFormat

sap.ui.core.format.DateFormat

The DateFormat class can be used to parse a string representing a date, time or datetime into a JavaScript date object and vice versa (also known as format).

The format pattern must be defined in LDML date format notation. The following options are available:

● style: Can be "short", "medium", "long" or "full" and will use a locale dependent pattern● pattern: A date pattern in LDML Date Format notation

In case both, style and pattern, are defined, the pattern is used and the style ignored.

Example how the DateFormat class can be used:

jQuery.sap.require("sap.ui.core.format.DateFormat");var oDateFormat = sap.ui.core.format.DateFormat.getDateTimeInstance({pattern: "dd/MM/yyyy HH:mm"}); //Returns a DateFormat instance for date and time//var oDateFormat = sap.ui.core.format.DateFormat.getInstance({pattern: "dd/MM/yyyy"}); //Returns a DateFormat instance for date//var oDateFormat = sap.ui.core.format.DateFormat.getTimeInstance({pattern: "HH:mm"}); //Returns a DateFormat instance for time

var oField = new sap.ui.commons.TextField();oField.setValue(oDateFormat.format(oDate)); // Set the formatted value on the text fieldoField.attachChange(function(){

//Parse the user input oDate = oDateFormat.parse(oField.getValue());});

sap.ui.core.format.NumberFormat

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 175

Page 176: Hana Cloud

The NumberFormat class can be used to parse a string representing a number (float or integer) into a Javascript number and vice versa (also known as format). The following format options are possible. For parameters which are not specified default values according to the type are used:

● minIntegerDigits: minimal number of non-fraction digits● maxIntegerDigits: maximal number of non-fraction digits● minFractionDigits: minimal number of fraction digits● maxFractionDigits: maximal number of fraction digits● groupingEnabled: enable grouping (show the grouping separators)● groupingSeparator: used grouping separator● decimalSeparator: used decimal separator

Example how the NumberFormat class can be used:

var fValue = 20001000.563; jQuery.sap.require("sap.ui.core.format.NumberFormat");var oNumberFormat = sap.ui.core.format.NumberFormat.getFloatInstance({ maxFractionDigits: 2, groupingEnabled: true, groupingSeparator: ",", decimalSeparator: "."}); //Returns a NumberFormat instance for float/*var oNumberFormat = sap.ui.core.format.NumberFormat.getIntegerInstance({ maxFractionDigits: 0, groupingEnabled: false}); //Returns a NumberFormat instance for integer*/

var oField = new sap.ui.commons.TextField();oField.setValue(oNumberFormat.format(fValue)); // Set the formatted value on the text fieldoField.attachChange(function(){ //Parse the user input fValue = oNumberFormat.parse(oField.getValue()); alert(fValue);});

Implementing a Custom Model

Context

To create a custom model implementation, proceed as follows:

Procedure

1. Extend the Model class and specify the binding modes that the model should support (for example, two-way, one-way, one-time).

2. Extend the Binding class to suit your specific binding or reuse the existing specific binding implementations PropertyBinding, ListBinding, and/or TreeBinding.

176P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 177: Hana Cloud

3. To enable the filtering functionality, use the Filter class with FilterOperator enum in your binding implementation.

4. To enable the sorting functionality, use the Sorter class in your binding implementation.

Results

You can find all necessary classes in the sap.ui.model namespace.

As a starting point, take a look at the JSONModel implementation in sap.ui.model.json.JSONModel.

OData Write Support

SAPUI5 supports the following operations and features for the ODataModel:

● write● create● remove● update● read● get metadata service document● Cross-site request forgery (XSRF) token support for the REST library● refresh

NoteAs the above mentioned features are experimental, changes in future versions of SAPUI5 may occur. Currently, all write operations have to be performed by the application and are triggered synchronously.

The default binding mode is sap.ui.model.BindingMode.OneWay. You can also set the binding mode to sap.ui.model.BindingMode.TwoWay.

Create Request

The create function triggers a POST request to an OData service which was specified during creation of the OData model.

The application has to specify the collection where to create the entry and the entry data payload.

To get the result of the request, the application can hand over callback handler functions. To recreate and update the bindings, a refresh is triggered automatically after the successful creation.

The following code triggers a new entry in the Products collection:

var oEntry = {};oEntry.Name = "IPad";

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 177

Page 178: Hana Cloud

oEntry.Price = "499$";oModel.create('/Products', oEntry, null, function(){ alert("Create successful"); },function(){ alert("Create failed");});

Delete Request

The remove function triggers a DELETE request to an OData service which was specified during creation of the OData model. The application has to specify the path to the entry which should be deleted. To update the bindings in the model, a refresh is triggered automatically after successful deletion.

A single parameter oParameters can be passed into the function and can carry all optional attributes, such as attributes for success and error handling functions as well as ETag attributes. ETags can be used for concurrency control if the OData service is configured to provide them. For more information, see the section about concurrency control and ETags in the OData documentation.

If an ETag is specified in oParameters, it will be used inthe If-Match-Header nstead of any ETag found in the metadata of an entry. If not, the ETag is retrieved from the entry's metadata. In fo ETag is found, no If-Match-Header will be used.

The following code delets the product entry with ID=1 from the Products collection of the data service:

oModel.remove('/Products(1)', null, function(){ alert("Delete successful"); },function(){ alert("Delete failed");});

Update Request

The update function triggers a PUT request to an OData service which was specified during creation of the OData model. See the ODataModel API for information about attribute use.

The application has to specify the path to the entry which should be updated with the specified updated entry.

After a successful request to update the bindings in the model, a refresh is triggered automatically.

The following code updates the price:

var oEntry = {};oEntry.Price = "599$";oModel.update('/Products(1)', oEntry, null, function(){ alert("Update successful"); },function(){ alert("Update failed");});

The flag bMerge has been introduced to also allow a MERGE request to perform a differential update.

178P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 179: Hana Cloud

Read Request

The read function triggers a GET request to a specified path which should be retrieved from the OData service which was specified during creation of the OData model.

The retrieved data is returned in the success callback handler function.

oModel.read('/Products(1)', null, null, true, function(oData, oResponse){ alert("Read successful: " + JSON.stringify(oData)); },function(){ alert("Read failed");});

Refresh

The Refresh function triggers a refresh for each binding to check if a value has been updated, or not. For a list binding a new request is triggered to reload the data from the server.

Additionally, if the XSRF token is not valid any more, a read request is triggered to fetch a new XSRF token from the server.

XSRF Token

To address the challenge of Cross Site Request Forgery an OData service might require XSRF tokens for change requests by the client application for security reasons. In this case the client has to fetch a token from the server and send it with each change request to the server.

The OData model fetches the XSRF token when reading the metadata and then automatically sends it in each write request header. If the token is not valid any more a new token can be fetched by calling the refresh function on the OData model.

Metadata

The getServiceMetadata function returns the parsed metadata document as a JavaScript object.

Experimental Two-Way Binding

NoteThis feature is experimental and may change in future versions of SAPUI5.

The two-way binding mode enables the application to update values of a single collection entry without triggering an immediate change request. create and delete operations are not collected and can be called by the application as described above.

If the two-way binding mode is enabled, the setProperty function of the OData model is called automatically to update the value in the specified entry upon user input. If an update to a property of another entry is performed

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 179

Page 180: Hana Cloud

and there is already an update to an existing entry pending, a rejectChange event is fired and no change to the property value is stored in the model. The application can register to this event. Thus, before updating a different entry, the application has to submit or reset existing changes of the current entry:

● To reset the current changes the application can call the resetChanges function.● To trigger the final update request for the modified entry the application should call the submitChanges

function.

Callback handlers for these functions can be handed over as parameters.

To enable the two-way binding for the OData model the default binding mode has to be changed as follows:

oModel.setDefaultBindingMode(sap.ui.model.BindingMode.TwoWay);

After the binding is done, the application should attach to the rejectChange event to handle the user modifications to different entries accordingly and, for example, allow or reject user input for a specific entry.

oModel.attachRejectChange(this,function(oEvent){ alert("You are already editing another Entry! Please submit or reject your pending changes!");});

The application can use the hasPendingChanges function to determine if there is a pending change.

The application can then decide (or let the user decide) when to submit or reject the changes:

var oUpdateBtn = new sap.ui.commons.Button({ text : "Update", style : sap.ui.commons.ButtonStyle.Emph, press : function(){ oModel.submitChanges(function(){ alert("Update successful");); },function(){ alert("Update failed");}); }});

var oCancelBtn = new sap.ui.commons.Button({ text : "Cancel", style : sap.ui.commons.ButtonStyle.Reject, press : function(){ oModel.resetChanges(); }});

The submitChanges function also has an optional parameter oParameters which currently can have an attribute for an ETag.

Calculated Fields for Data Binding

The calculated fields feature enables the binding of multiple properties in different models to a single property of a control. For example, the value property of a text field may be bound to a property firstName and a property lastName in a model. The application can access these values in a formatter function and can decide how they should be processed or combined together. If no formatter function is specified, the values are joined together by default. You can use the useRawValues property to specify if the parameter values in the formatter function are formatted according to the type of the property or not.

180P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 181: Hana Cloud

The multiple property bindings are stored in a CompositeBinding and can be accessed by calling the getBindings function. You can access the composite binding, for example, by using the getBinding('value') function of the control. The composite binding has no path, model, context, and type because it contains multiple property bindings containing the necessary information. A composite binding may, for example, store two property bindings which belong to different models and have different types.

If you have specified a formatter function, it is also available in the composite binding.

NoteCurrently, calculated fields work only from model to view, read only, and the values can be accessed via a formatter function.

There are several options to create multiple bindings for a control. The syntax is very similar to the normal single binding declaration.

Each binding is created by the specified parts and assigned information. A part must contain the path to the property in the model and may contain additional information for the binding, for example a type. If multiple parts exist, the binding mode is automatically set to one-way binding.

Constructor Declaration

1. Use binding objects to add additional parameters, for example the type:

oTxt = new sap.ui.commons.TextField({ value: { parts: [ {path: "/firstName", type: new sap.ui.model.type.String()}, {path: "/lastName"}, {path: "myModel2>/amount", type: new sap.ui.model.type.Float()} // path to property in another model ] }});

2. Use strings which only take the path:

oTxt = new sap.ui.commons.TextField({ value: { parts: [ "/firstName", "/lastName", "myModel2>/fraud" // path to property in another model ] }});

Bind Property Declaration

1. Use binding objects to add additional parameters, for example the type:

oTxt.bindValue({ parts: [

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 181

Page 182: Hana Cloud

{path: "/firstName", type: new sap.ui.model.type.String()}, {path: "/lastName"} ]});

2. Use strings which only take the path:

oTxt.bindValue({ parts: [ "/firstName", "/lastName" ]});

These samples also work with a relative binding path, when you use them as a template in an aggregation binding.

Custom Formatter Functions

The examples for constructor declaration and bind property declaration (see Calculated Fields for Data Binding) do not contain a formatter function. In this case, all values of the various parts are joined together as a string with a space seperator. To specify your own formatter, proceed as shown in the following example:

oTxt.bindValue({ parts: [ {path: "/firstName", type: new sap.ui.model.type.String()}, {path: "/lastName", type: new sap.ui.model.type.String()}, {path: "/amount", type: new sap.ui.model.type.Float()}, {path: "/currency", type: new sap.ui.model.type.String()} ], formatter: function(firstName, lastName, amount, currency){ // all parameters are strings if (firstName && lastName) { return "Dear " + firstName + " " + lastName + ". Your current balance is: " + amount + " " + currency; } else { return null; } }});

The values provided in the parameters of the formatter function are already formatted to the output type of the control, which is a string in this case (that is, the value property of text field is a string).

Custom Formatter Function with Raw Values

If you do not want the provided values in the formatter function being already formatted according to their type, you can set a flag to get the raw unformatted values. These values are also stored in the model. In this case, the types of the parts are ignored:

oTxt.bindValue({ parts: [ {path: "/firstName", type: new sap.ui.model.type.String()}, {path: "/lastName", type: new sap.ui.model.type.String()}, {path: "/amount", type: new sap.ui.model.type.Float()}, {path: "/model2>debts", type: new sap.ui.model.type.Float()} ], formatter: function(firstName, lastName, amount, debt){ // string, string, float, float if (firstName && lastName) { return "Dear " + firstName + " " + lastName + ". Your current

182P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 183: Hana Cloud

balance is: " + (amount - debts); } else { return null; } }, useRawValues : true});

1.3.4.3.5 Custom Data - Attaching Data Objects to Controls

To attach data to SAPUI5 controls, the method data() has been added to the base class sap.ui.core.Element. You can use the method to set and get data. The API is equivalent to jQuery.data().

You can also use the following other possibilities to attach data to SAPUI5 controls:

● Attaching data declaratively in XML views and JSON views● Using data binding● For strings only: Writing data to the HTML DOM as "data-*" attribute.

Setting and Retrieving Data

To set and retrieve data, use the following code:

myButton.data("myData", "Hello"); // attach some data to the Button

alert(myButton.data("myData"); // alerts "Hello"

var dataObject = myButton.data(); // a JS object containing ALL dataalert(dataObject.myData); // alerts "Hello"

Binding Data: Use in a List Binding

For list bindings, use the following code:

// create a JSONModel, fill in the data and bind the ListBox to this model

var oModel = new sap.ui.model.json.JSONModel();oModel.setData(aData); // aData is a data array consisting of elements like {question:"Some question?",answer:"Some answer!"}var ctrl = new sap.ui.commons.ListBox({select:giveAnswer}); // method giveAnswer() retrieves the custom data from the selected ListItemctrl.setModel(oModel);

// create an item template and bind the question data to the "text" property

var oItemTemplate = new sap.ui.core.ListItem();oItemTemplate.bindProperty("text", "question");

// create a CustomData template, set its key to "answer" and bind its value to the answer data

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 183

Page 184: Hana Cloud

var oDataTemplate = new sap.ui.core.CustomData({key:"answer"});oDataTemplate.bindProperty("value", "answer");

// add the CustomData template to the item template

oItemTemplate.addCustomData(oDataTemplate);

// bind the items to the "questions" (which is the name of the data array)

ctrl.bindAggregation("items", "questions", oItemTemplate);

You can find a productive example in the SAPUI5 test suite by searching for CustomData in sap.ui.core.

Use in XML Views

In XML views, CustomData objects can be written as normal aggregated objects. However, to reduce the amount of code and improve the readability, a shortcut notation has been introduced: You can directly write the data attributes into the control tags. You just need to use the following namespace for these attributes: myNamespace="http://schemas.sap.com/sapui5/extension/sap.ui.core.CustomData/1.

This namespace is intentionally different and more formal than the existing MVC namespaces which will also be adapted to this more formal naming scheme.

Use without Data Binding

The following example shows how you attach the string "just great" to a button:

#!xml

<core:View xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.ui.commons" controllerName="my.own.controller" xmlns:app="http://schemas.sap.com/sapui5/extension/sap.ui.core.CustomData/1"> <Button id="myBtn" text="Click to show stored coordinates data" app:mySuperExtraData="just great" press="alertCoordinates"></Button></core:View>

The string is returned at runtime by calling button.data("mySuperExtraData").

Use with Data Binding

You can use data binding with the following notation:

#!xml

<core:View xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.ui.commons" controllerName="my.own.controller" xmlns:app="http://schemas.sap.com/sapui5/extension/sap.ui.core.CustomData/1"> <Button id="myBtn" text="Click to show stored coordinates data" app:coords="{data}" press="alertCoordinates"></Button></core:View>

184P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 185: Hana Cloud

Use in JSON Views

To add custom data to an element in a JSON view, add the following code to the element properties (these examples include data binding):

customData: { Type:"sap.ui.core.CustomData", key:"coords", value:"{data}" // bind custom data }

To add multiple data elements, use an array:

customData: [{ Type:"sap.ui.core.CustomData", key:"coords", value:"{data}" // bind custom data }, { Type:"sap.ui.core.CustomData", key:"coords", value:"{data}" // bind custom data }]

In context, this looks as follows:

var json = { Type: "sap.ui.core.JSONView", controllerName:"my.own.controller", content: [{ Type:"sap.ui.commons.Panel", content:[{ Type:"sap.ui.commons.Button", text:"{actionName}", press: "doSomething", customData: { Type:"sap.ui.core.CustomData", key:"coords", value:"{data}" // bind custom data } }] }] };

Writing Data to the HTML DOM as DATA-* Attribute

It can be useful to write the custom data to the HTML DOM, for example to generate markers in the HTML from data binding which then can be used for data-dependent styling, or to create stable anchors in the HTML which can be used for automated tests.

A "data-" prefix is added to the key and the result is then written as attribute into the root HTML element of the control. The CustomData value is written as attribute value.

This only works when the key is a valid HTML ID and the value is a string (otherwise an error is logged). Note that HTML attribute names are case-insensitive and browsers may convert the key to lowercase.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 185

Page 186: Hana Cloud

NoteDo not write too much data into DOM.

In JavaScript the flag can be set like this:

myButton.data("mydata", "Hello", true); // attach some data to the Button and mark it as "write to HTML"

In XMLViews the aggregation has currently to be written in expanded notation to set the writeToDom flag:

<Button ... > <customData> <core:CustomData key="mydata" value="Hello" writeToDom="true" /> </customData></Button>

Resulting HTML:

<button ... data-myData="Hello" ... >

Now CSS can use attribute selectors to check presence or the value of the custom data attribute:

button[data-mydata="Hello"] { border: 3px solid red !important; }

1.3.4.3.6 Declarative Support

The SAPUI5 library can be extended to support declarative programming which allows you to define the UI within the HTML document as elements. For this, a plugin (sap.ui.core.plugin.DeclarativeSupport) can be included either as required or marked as a module in the initial bootstrap script tag. The plugin parses the document and converts its tags with special attributes into SAPUI5 controls.

Declarative support is aware of properties, associations, events, and aggregations in a SAPUI5 control manner. This means that you can specify them within the markup of the HTML document either as data attributes or as child elements.

The following sections provide an overview of the declarative support and introduce the use of declarative support in SAPUI5.

Example

The following example shows the concept by combining a sap.ui.commons.TextField with a sap.ui.commons.Button control. When you click the button, the value of the text field is displayed in an alert box:

<!Doctype HTML><html> <title>Declarative Programming for SAPUI5 - sample01</title>

<script id="sap-ui-bootstrap"

186P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 187: Hana Cloud

type="text/javascript" src="http://veui5infra.dhcp.wdf.sap.corp:8080/sapui5/resources/sap-ui-core.js" data-sap-ui-theme="sap_platinum" data-sap-ui-libs="sap.ui.commons" data-sap-ui-modules="sap.ui.core.plugin.DeclarativeSupport" > </script>

</head><body class="sapUiBody">

<div data-sap-ui-type="sap.ui.commons.TextField" id="message" class="my-button" data-value="Hello World"></div> <div data-sap-ui-type="sap.ui.commons.Button" data-text="Click me!" data-press="handlePress"></div>

</body></html>

Summary: Attributes Used by Declarative Support

The table summarizes the attributes used by declarative support and gives examples.

Attribute Description Example

data-sap-ui-type Type of control <div data-sap-ui-type="sap.ui.commons.Button"></div>

data-sap-ui-aggregation Defines the aggregation that shall be used for the element or child element

<div data-sap-ui-type="sap.ui.commons.Panel"><div data-sap-ui-aggregation="title" data-sap-ui-type="sap.ui.commons.Title" data-text="My Panel"></div></div>

data-sap-ui.default-aggregation

Sets or overrides the default aggregation of a control

<div data-sap-ui-type="sap.ui.commons.Panel" data-sap-ui-default-aggregation="title"><div data-sap-ui-type="sap.ui.commons.Title" data-text="My Panel"></div></div>

id Defines the ID property of a control <div data-sap-ui-type="sap.ui.commons.Button" id="myButton"></div>

class Adds a style class to the control <div data-sap-ui-type="sap.ui.commons.Button" class="myButton"></div>

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 187

Page 188: Hana Cloud

Enabling Declarative Support

To use declarative support you need to enable the declarative support in your HTML document by adding an attribute to the SAPUI5 bootstrap script tag. This is done as follows:

data-sap-ui-modules="sap.ui.core.plugin.DeclarativeSupport"

SAPUI5 then requires (loads) the plugin sap.ui.core.plugin.DeclarativeSupport. When started, the plugin parses and enhances special HTML tags in the HTML document. The complete bootstrap script tag for SAPUI5 (based on a CDN version) looks as follows:

<script id="sap-ui-bootstrap" type="text/javascript" src="http://veui5infra.dhcp.wdf.sap.corp:8080/sapui5/resources/sap-ui-core.js" data-sap-ui-theme="sap_platinum" data-sap-ui-libs="sap.ui.commons" data-sap-ui-modules="sap.ui.core.plugin.DeclarativeSupport" ></script>

Defining Controls

After you have enabled the declarative support, define controls in your HTML document as HTML tags with the following data attribute:

data-sap-ui-type="sap.ui.commons.Button"

This data attribute defines the SAPUI5 control that should be rendered in the HTML tag by using the HTML tag as its UI area. Rendering a button in the body of an HTML document without setting any property, association, event, or aggregation looks as follows:

<body> <div data-sap-ui-type="sap.ui.commons.Button"></div></body>

NoteMake sure that you close the tags properly. HTML5 does not support self-closing tags.

NoteAll attributes used to define properties, associations, events, or aggregations are data attributes except for attributes that exist in HTML, for example id or class. Data attributes are prefixed with data-*, for example data-text.

188P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 189: Hana Cloud

Declarative Support: Properties

To set a property, for example for a button, you define the property as a data attribute of the corresponding HTML tag. To add text to the button, add the attribute data-text to its HTML tag:

<div data-sap-ui-type="sap.ui.commons.Button" data-text="HelloWorld"></div>

NoteTo define a property with upper case characters, you have to "escape" them with a dash character, similar to CSS attributes. The following code gives an example:

<div data-sap-ui-type="sap.ui.commons.ApplicationHeader" data-display-logoff="false" data-display-welcome="false"></div>

As the name of the attributes of HTML tags are case-insensitive, the properties displayLogoff and displayWelcome of the ApplicationHeader control have to be "escaped" as data-display-logoff and data-display-welcome for the name of the attributes of the HTML tag. Keep this in mind when matching properties, associations ,or events as an attribute of the HTML tag.

The id attribute defines the ID of a control:

<div data-sap-ui-type="sap.ui.commons.Button" id="myButton"></div>

To add a CSS class to the control, use the class attribute:

<div data-sap-ui-type="sap.ui.commons.Button" class="my-button"></div>

Declarative Support: Associations

An association is defined as a data attribute of the HTML tag. Instead of passing the reference to another control you define the ID of another control. The following code gives an example:

<div data-sap-ui-type="sap.ui.commons.Label" data-text="Message:" data-label-for="message"></div><div data-sap-ui-type="sap.ui.commons.TextField" id="message"></div>

The code snippet defines the link between Label and TextField by using the ID of TextField as a value for the data-label-for attribute of the Label.

Declarative Support: Events

The value of the event data attribute contains the name of a JavaScript function which will be used as callback once the event has been triggered. The following code snippet gives an example how a change of TextField results in an alert with its new value when the focus is lost:

<script> function handleChange (oEvent) {

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 189

Page 190: Hana Cloud

alert (oEvent.getSource().getValue()); }</script>

<div data-sap-ui-type="sap.ui.commons.TextField" data-value="Change me!" data-change="handleChange"></div>

Currently, SAPUI5 only supports to specify the name of a callback function. You can define callback functions within any class, see the following code example:

<div data-sap-ui-type="sap.ui.commons.TextField" data-value="Change me!" data-change= "my.company.MyClass.handleChange"></div>

Declarative Support: Aggregations

Agrregation support is required to allow nested controls for layout containers and/or add elements to a control, for example, for ComboBox.

SAPUI5 uses the control's default aggregation as default. If, for example, the panel control has the default aggregation content, all child elements of the data-sap-ui-type="sap.ui.commons.Panel" element are added to this aggregation:

<div data-sap-ui-type="sap.ui.commons.Panel"> <div data-sap-ui-type="sap.ui.commons.Button" data-text="My Button 1"></div> <div data-sap-ui-type="sap.ui.commons.Button" data-text="My Button 2"></div> <div data-sap-ui-type="sap.ui.commons.Button" data-text="My Button 3"></div> <div data-sap-ui-type="sap.ui.commons.Button" data-text="My Button 4"></div></div>

The markup in the example above generates an instance of the sap.ui.commons.Panel control and adds implicit four buttons to the default aggregation content of the control.

You can also explicitly declare an aggregation. In general, an explicit aggregation is expressed with a meta HTML tag between the parent controls HTML tag and the HTML tags of the children. The following code adds four buttons explicitly to the "content" aggregation of the declared panel:

<div data-sap-ui-type="sap.ui.commons.Panel"> <div data-sap-ui-aggregation="content"> <div data-sap-ui-type="sap.ui.commons.Button" data-text="My Button 1"></div> <div data-sap-ui-type="sap.ui.commons.Button" data-text="My Button 2"></div> <div data-sap-ui-type="sap.ui.commons.Button" data-text="My Button 3"></div> <div data-sap-ui-type="sap.ui.commons.Button" data-text="My Button 4"></div> </div></div>

For aggregations with the cardinality "0..1" the "data-sap-ui-aggregation" attribute can be written directly to the control tag:

<div data-sap-ui-type="sap.ui.commons.Panel"> <div data-sap-ui-aggregation="title" div data-sap-ui-type="sap.ui.commons.Title" data-text="My Panel"></div></div>

The default aggregation of the declarative support is usually also the default aggregation of the control as defined in the control's meta information. However, when no default aggregation is set or another aggregation should be

190P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 191: Hana Cloud

used as a default, for example to avoid unnecessary meta tags, it can be useful to define a so-called default aggregration attribute on the parent controls HTML tag. This is done as follows:

data-sap-ui-default-aggregation="title"

With this, all children which are not included in the data-sap-ui-aggregation meta tag are added to the default aggregation. This is shown in the following example:

<div data-sap-ui-type="sap.ui.commons.Panel" data-sap-ui-default-aggregation="title"> <div data-sap-ui-type="sap.ui.commons.Title" text="My Panel"></div> <div data-sap-ui-default-aggregation="content"> <div data-sap-ui-type="sap.ui.commons.Button" data-text="My Button 1"></div> <div data-sap-ui-type="sap.ui.commons.Button" data-text="My Button 2"></div> </div>/div>

You can now apply this to the MatrixLayout as follows:

<div data-sap-ui-type="sap.ui.commons.layout.MatrixLayout" data-layout-fixed="false> <div data-sap-ui-type="sap.ui.commons.layout.MatrixLayoutRow"> <div data-sap-ui-type="sap.ui.commons.layout.MatrixLayoutCell"> <div data-sap-ui-type="sap.ui.commons.TextField" data-value="Hello World"></div> </div> <div data-sap-ui-type="sap.ui.commons.layout.MatrixLayoutCell"> <div data-sap-ui-type="sap.ui.commons.Button" data-text="Hello World"></div> </div> </div></div>

Or you can add ListItems to a ComboBox:

<div data-sap-ui-type="sap.ui.commons.ComboBox" data-value="Item 1"> <div data-sap-ui-type="sap.ui.core.ListItem" data-text="Item 1"></div> <div data-sap-ui-type="sap.ui.core.ListItem" data-text="Item 2"></div> <div data-sap-ui-type="sap.ui.core.ListItem" data-text="Item 3"></div> <div data-sap-ui-type="sap.ui.core.ListItem" data-text="Item 4"></div> <div data-sap-ui-type="sap.ui.core.ListItem" data-text="Item 5"></div></div>

Declarative Support: Data Binding

Data binding is supported seamlessly by the declarative support. Just add the model path in curly brackets and bind the model to the control (or parent control):

<div data-sap-ui-type="sap.ui.commons.Button" data-text="{/stringValue}" data-enabled="{model2>/booleanValue}"></div>

0..n aggregations can define templates to use for the aggregation binding:

<div data-sap-ui-type="sap.ui.commons.Carousel" data-content="{/buttons}"> <div data-sap-ui-type="sap.ui.commons.Button" data-text="{title}"></div></div>

In the example above, the button template is used for the carousel content data binding.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 191

Page 192: Hana Cloud

Related LinksData Binding [page 146]

Compiling Declarative HTML

The plugin only works for controls that are defined as declarative markup on startup time. To compile the declarative UI markup deferred, for example, when the markup is dynamically loaded and added to the DOM you can call the sap.ui.core.plugin.DeclarativeSupport.compile method, see the following code snippet:

<div id="button"> <div data-sap-ui-type="sap.ui.commons.Button" data-text="This button is added dynamically"></div></div>

<script> sap.ui.core.plugin.DeclarativeSupport.compile(document.getElementById("button"));</script>

1.3.4.3.7 Modularization and Resource Handling

The following sections provide information abour the modularization concepts and resource handling for SAPUI5.

Modularization and Dependency Management

The SAPUI5 framework has built-in support for modularizing comprehensive JavaScript applications. That means, instead of defining and loading one large bundle of JavaScript code, an application can be splitted into smaller parts which then can be loaded at runtime at the time when they are needed. These smaller individual files are called modules.

To load a module, the jQuery.sap.require function must be used. Assume the following page:

#!js

<!-- UI5 bootstrap tag --> <script id="sap-ui-bootstrap" src="./resources/sap-ui-core.js" data-sap-ui-libraries="sap.ui.commons"></script>

<script> jQuery.sap.require("sap.ui.commons.MessageBox");

function onPressButton() { sap.ui.commons.MessageBox.alert("Hello World!"); }

</script>

192P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 193: Hana Cloud

At first, the SAPUI5 framework initializes and then loads the sap.ui.commons.MessageBox module. Internally, the framework analyzes the module name and derives the module URL from it:

./resources/sap/ui/commons/MessageBox.js

The module script is then loaded from that URL and executed.

What is a Module

A module simply is a JavaScript file that can be loaded and executed in a browser. There are no rules or definitions what code belongs to a module, and what code does not. It is up to the developer what content to bundle into a single module. But typically, the content of a module has some topic in common. Either it forms a JavaScript class or namespace, or the contained functions address a specific topic, for example client to server communication, mathematical functions, and so on.

There is also no special syntax or structure defined for modules. However, there are some features that module developers should be aware of and that they can use:

Name: A module is loaded by calling jQuery.sap.require with the name of the module. So, all modules are identified by a name. Human readers often associate a module with the main JavaScript object declared in it. Therefore, the module names by convention are a hierarchical sequence of dot-separated identifiers (like sap.ui.core.Core). It is best practice to use all but the last identifier to group modules in a logical and/or organizational way (much like packages in Java) and to use the last identifier to give the module a meaningful, semantical name, for example, the 'topic' common to the code in the module.

Declaration: Modules can declare themselves by calling the static jQuery.sap.declare function with their name. This helps SAPUI5 to check at runtime whether a loaded module really contains the expected content (compare the required name against the declared name). As a side effect, jQuery.sap.declare will ensure that the parent namespace of the module name exists in the current global namespace (window). More details can be found in the API documentation of declare.

If a module does not contain a declaration, the framework assumes that the module has the expected content and automatically declares it with the name used for loading it. In some rare cases - which are explained below - a module declaration is mandatory.

Description: Furthermore, modules can contain a description which helps others to decide whether a module is useful for them, or not. By convention, any JavaScript comment preceeding a module's declaration (jQuery.sap.declare statement) is interpreted as its description. The configuration UI displays such descriptions next to the module name.

Dependencies: Last but not least, modules can use the jQuery.sap.require method to load other modules that they depend on. While jQuery.sap.require internally has the effect of a "loadModule" call, it can also be regarded as a dependency declaration (therefore its name 'require'). These dependency declarations can be evaluated at runtime (as explained above), but they can also be analyzed at built time or at runtime on the server.

Example:

A typical module that uses all of the above features might look like this (the module name is my.useful.SampleModule);

#!js

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 193

Page 194: Hana Cloud

/* * A short documentation of the module. This documentation is not evaluated at runtime, only during build time */ jQuery.sap.declare("my.useful.SampleModule"); // declaration of the module. Will ensure that the containing namespace 'my.useful' exists.

// list of dependencies of this module jQuery.sap.require("sap.ui.core.Core"); jQuery.sap.require("some.other.Module"); jQuery.sap.require("you.can.Also", "list.multiple.Modules", "if.you.Want"); ...

// create the 'main' object of the module my.useful.SampleModule = {};

Loading a Module

As mentioned already, modules are loaded by calling function jQuery.sap.require with the name of a required module. The framework then checks whether the named module is loaded already. If so, the function simply returns. Otherwise it tries to load and execute the module synchronously. If any of these two steps fails, an exception is thrown and execution of the calling module thereby is disrupted.

To summarize it: A call to jQuery.sap.require ensures that the required module is loaded and has been executed before execution of the caller continues (*). (*) this is only true as long as no cyclic dependencies occur.

When loading a module, its dot-separated name must be transformed to an URL. This is done by replacing all dots ('.') with slashes ('/') and appending the standard suffix '.js' to it. This transformed name is then appended to the UI5 resource root URL (a prefix of the URL where UI5 has been loaded from, see explanation of bootstrap). The resulting URL is then used to load the module as a text. If loading succeeds, the module is first declared with the original module name and then executed in a global context (window). If either loading the module or executing it fails, the module name is internally marked as "failed" and an exception is thrown indicating the cause for the failure. Any further tries to load the same module will fail immediately, reproducing the same error message.

Multiple Module Locations

It is a common use case for web applications that different modules are located in different locations (servers, web apps). Imagine for example that your web application is deployed as an individual web app and that it contains some very important modules to be loaded at runtime. But for administrative reasons, SAPUI5 and its provided modules have to be loaded from a content delivery network (CDN) or from a centrally deployed web app. As explained above, SAPUI5 by default will try to load any required modules from its resource root URL, namely from the centrally deployed web application. This would fail for the modules contained in your web application.

Such mixed location scenarios are supported with the jQuery.sap.registerModulePath function:

jQuery.sap.registerModulePath = function(sModuleNamePrefix, sURL);

It associates a module name prefix with an URL prefix. Any module whose name starts with the module name prefix will be loaded from the registered URL instead of the standard resource root URL. In the scenario

194P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 195: Hana Cloud

prethought above, this can be used to redirect the request for the application-specific modules to the corresponding web application:

#!js

<!-- bootstrap tag which implicitly defines the resource root as 'http://www.sap.com/sapui5/1.0/resources/' --> <script src="http://www.sap.com/sapui5/1.0/resources/sap-ui-core.js" ></script>

<script> // request will be mapped to http://www.sap.com/sapui5/1.0/resources/sap/ui/core/Core.js jQuery.sap.require('sap.ui.core.Core');

// redirect the 'my.webapp' package to the local web app jQuery.sap.registerModulePath('my.webapp', '/my-webapp/resources/my/webapp/');

// loads /my-webapp/resources/my/webapp/MyModule01.js jQuery.sap.require('my.webapp.MyModule01'); </script>

NoteThe registered URL above contains the transformed module name prefix 'my/webapp/'. While this seems to be an unnecessary redundancy in the registration, it allows a more flexible packaging of the modules. For example, a company might decide to deploy all its specific modules named 'my.company.*' to the central URL 'http://my.company/shared/' without packaging them into a two level hierarchy of subfolders:

jQuery.sap.registerModulePath('my.company', 'http://my.company/shared/');

However, when the standard build tools of the SAPUI5 framework are used, the full package name will be part of the runtime file hierarchy and the registration must contain the transformed package hierarchy as above.

Dependency Resolution Tools

The previous section contained some explanations how dependencies between modules are resolved on the client at runtime. During development, this is the typical use case. Modules can be modified in the development environment and can be deployed as individual entities to some runtime. When the client then is refreshed - and if caching is configured properly - it will reload only the modified modules.

In productive systems however, it might be desirable to bundle again several modules into one single file. This helps reducing the number of necessary roundtrips and can thereby help to reduce the impact of network latency. However, one doesn't want to loose the flexibility and transparency of the dependency management.

The SAPUI5 framework supports this with a dependency resolution tool. It analyzes a module file and all its dependencies and creates a new file containing the original module content, as well as any required modules. It automatically avoids double inclusion of modules. The tool can be used in two ways: Either via an Ant task at build time to create a merged super module which then can be referenced in any HTML page instead of the original file; or at runtime, then using a servlet on server side.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 195

Page 196: Hana Cloud

How to Avoid Duplicates

When the runtime dependency resolution is used, the runtime maintains a list of the loaded modules. Before a new module is loaded and executed, the list is searched for it and if found, the module is not loaded again. But when the server or build-time tool is used, it creates a bigger file potentially containing multiple modules. The runtime then can only check in advance whether that bigger module has been loaded already. It does not know about the contained modules and therefore can not avoid double-loading of them. To compensate this, the dependency resolution tool wraps any embedded module with a few lines of additional coding. These additional checks will be evaluated during execution of the merged module and will have the same effect as the original runtime checks in an unmerged scenario:

...

// code of enclosing module ...

// location of a jQuery.sap.require('xyz');

if ( !jQuery.sap.isDeclared('xyz') ) { // check whether module 'xyz' has been loaded already

jQuery.sap.declare('xyz'); // will only be added if the module 'xyz' doesn't contain a declaration

// original text of module 'xyz' ... }

... // further code of enclosing module ...

NoteThe generated wrapper coding will also contain a module declaration if the module doesn't contain one. The wrapper avoids double loading no matter whether a module has been loaded as an individual file or as part of a bigger, merged module. It is even possible to recursively merge files (merged module A includes a merged module B).

Why not Simply Concatenating Modules?

One might wonder why multiple modules can not simply be concatenated into a bigger module. Why have the modules to be parsed and to be nested according to the original jQuery.sap.require calls? The answer simply is that this makes the runtime behavior of the merged file more predictable. As soon as you look at concrete modules with complex (or even cyclic) dependencies, order of module execution becomes significant. The main promise of jQuery.sap.require that the caller continues only after the required module has been successfully loaded and executed can be hold only if the required module is embedded exactly at the place where the jQuery.sap.require call was located.

In cases where a use of the dependency resolution tool is not possible at all, one might indeed simply concatenate modules. But then the following two criteria must be ensured 'manually' by the developer:

196P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 197: Hana Cloud

● The order of the files must obey the dependencies. A module must not 'require' another module that is only merged later on.

● All merged modules must do a declaration with jQuery.sap.declare, otherwise the framework will not know that the modules have been loaded and potentially load them again.

Configurator Servlet

As mentioned already, one way of executing the dependency resolution tool is to call it via a servlet. Such a servlet has been included in the phoenix-cdn application that is part of our drop. By default, the servlet is configured to react on the URL http:// host:port /sapui5/download/configurator. It accepts several parameters

URL Parameter Default Description

modules None Mandatory: A comma separated, ordered list of module names that should be included in the resulting module. If the parameter occurs multiple times, the values will be concatened

out "sap-ui-custom.js" Name of the resulting module. The resulting module will contain a declaration with that name. When the servlet is used from the configurator Web UI, then the name will also be suggested in the download dialog.

minimize False Activates the JavaScript minimization for the output (experimental feature)

The Configurator WebUI, which is part of phoenix-cdn as well, uses the servlet to create a downloadable JavaScript file containg all selected modules.

But it is also possible to use the servlet directly from within an application page and to load UI5 and the required controls etc. in one step. The following HTML fragment shows an example (line breaks added for better readability):

<script id="sap-ui-bootstrap" data-sap-ui-theme="sap_platinum" type="text/javascript" data-sap-ui-libs="sap.ui.commons" src="/sapui5/download/configurator?modules=jquery-1.4.2,jquery.sap.global,sap.ui.core.Core,sap.ui.commons.Button,sap.ui.commons.ButtonRenderer,sap.ui.commons.layout.MatrixLayout,sap.ui.commons.layout.MatrixLayoutRow,sap.ui.commons.layout.MatrixLayoutCell,sap.ui.commons.layout.MatrixLayoutRenderer" > </script>

Special Cases

How to Load jquery.sap.require?

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 197

Page 198: Hana Cloud

Obviously, modules can only be loaded as soon as the jQuery.sap.require function is available. The implementation of this function is located in module 'jquery.sap.global' which in turn requires jQuery itself (located in module 'jquery-1.7.1'). At runtime, these two modules can not be loaded with 'jquery.sap.require' but must be loaded by some other mean. The SAPUI5 framework includes both modules in its bootstrap files sap-ui-core.js and sap-ui-core-lean.js. The first one also embeds the SAPUI5 core functionality and needs no further modules. The second one only contains the two bootstrap modules and a require statement for the core. It is better suited for the development scenario described above (loading the modules separately).

If you create a new bootstrap file with the configuration UI and decide to include the jquery.sap.global or jquery modules, they always will be the first modules in the created file, and they will always be embedded. This ensures the availability of jQuery.sap.require.

Cyclic Dependencies

Sometimes, the functionality in two modules A and B might be interdependent. That means module A requires module B to execute and module B requires module A. We stated above that jQuery.sap.require ensures that the execution of a calling module doesn't continue until the required module has been loaded and executed. Taking this serious, cyclic dependencies could not be resolved but would lead to an endless series of requests (A->B->A->B->...).

This situation can be avoided by a workaround: As soon as a module A has been loaded and is about to execute, it is regarded as declared. So, when this module A embeds another module B which has not been loaded, module B will be loaded and executed. If B now again requires A, then the dependency resolution runtime will find that A has been declared already (despite the fact that its execution has not been finished yet) and simply returns. This workaround helps to break the endless loop, but it doesn't re-ensure the original promise of jQuery.sap.require.

Cyclic modules have to deal with that gap on their own. There are several ways/best practices how to do this:

● Variant 1: Merge A and BIf the conflicts can not be resolved easily, or if the modules are so highly related that they will be used together most of the time, then merging them into one module is the most simple solution.

● Variant 2: Interlaced Execution of A and BThis variant makes use of the fact that the module loading takes place exactly at the source location where the jQuery.sap.require function is executed. Let's assume that the content of modules A and B can be structured as follows:

// Module A, Part A.1

// Module Section A.1, does not depend on Module B and provides all code that module B depends on.

jQuery.sap.require("B");

// Module Section A.2, might depend on code in Module Section B.1

// Module B, Part B.1

// Module Section B.1, does not depend on Module A and provides all code that module A depends on.

jQuery.sap.require("A");

198P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 199: Hana Cloud

// Module Section B.2, might depend on code in Module Section A.1

Further assume (WLOG) that module A is loaded first. Then section A.1 will be executed and will be available to the outside world before the require('B') is executed. During the require, the framework will detect that B is not available yet, will load and execute it. The execution starts with section B.1 which succeeds as it does not depend on A. When the execution of B reaches the require('A') statement, the framework detects that A has been loaded already and continues without loading A again. But remember, that the code from section A.2 is not available yet. The execution of B however continues and succeeds as - by assumption - B.2 does not depend on A.2. Now, the first require('B') succeeds and returns and section A.2 will be executed. And it might use the code from section B.1.

Procedure and result are similar in the case that B is loaded first.

Resource Handling

The resource handling of SAPUI5 is separated in two parts - a client-side and a server-side resource handling. Both are not dependent on each other. Furthermore they are complementary.

The server-side mechanism is not required. This is an optional component which improves the client-server interaction (server-side locale fallback instead of client-side with multiple requests) and especially is used for the Eclipse IDE development to support modularized development of SAPUI5 application and libraries.

Client-side Resource Handling

On the client-side SAPUI5 provides the following mechanism for resources:

● Modularization Concept (!Require/Declare for JavaScript files)● Localization Concept (Resource Bundles)

Both concepts are loading additional resources from a server where this server might be any kind of web server (simple, Java, ABAP, ...). It does not depend on any server side technology.

Server-side Resource Handling

For the Java server and also the integration into the Eclipse IDE SAPUI5 provides a resource handler. This resource handler is aligned with the concept of the JavaServer Faces - Resource Handler:

● The default implementation must support packaging resources in the web application root under the path resources/<resourceIdentifier> relative to the web app root.

● Resources packaged in the classpath must reside under the JAR entry name META-INF/resources/<resourceIdentifier>

The SAPUI5 resource handler extends this concept to support standard and test-relevant resources. Therefore we package our resources into the following paths:

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 199

Page 200: Hana Cloud

● resources/**Resources are all kind of JavaScript, CSS, Mimes, Resource Bundles, which are relevant for the runtime.

● test-resources/**Test resources are resources which are samples and only relevant for testing purposes e.g. the content of the SAPUI5 test suite.

Other additional features of the resource handler are:

● Theme fallback:If resources are not available for the current theme it automatically checks the base theme for such resources and returns this resource instead without returning a 404.

● Resource bundle fallback:Similar to the client-side mechanism for loading resource bundles but it negotiates the request on the server and returns the best found resource bundle instead without 404, e.g.:messagebundle_en_US.properties > messagebundle_en.properties > messagebundle.properties

Resource Servlet

For Java Servlet containers SAPUI5 provides a ResourceServlet which manages the access to SAPUI5 resources within the web application and the various UI libraries in the classpath. The following snippet shows how to enable the resource servlet for SAPUI5:

#!text/xml

<!-- ============================================================ --> <!-- SAPUI5 resource servlet used to handle application resources --> <!-- ============================================================ -->

<servlet>

<display-name>ResourceServlet</display-name>

<servlet-name>ResourceServlet</servlet-name>

<servlet-class>com.sap.ui5.resource.ResourceServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>ResourceServlet</servlet-name>

<url-pattern>/resources/*</url-pattern>

</servlet-mapping>

<servlet-mapping>

<servlet-name>ResourceServlet</servlet-name>

<url-pattern>/test-resources/*</url-pattern>

</servlet-mapping>

Before you can use it you need to make sure that the ResourceServlet is available in the classpath as JAR file.

200P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 201: Hana Cloud

Configuration

The resource handler is configured via context parameter which are defined in the web.xml. The following table gives an overview about configuratin parameters:

Key Description

com.sap.ui5.resource.USE_CACHE flag to enable resource cache or not (default: "true")

com.sap.ui5.resource.MAX_AGE max age of resources in millis (default: "604800000" - 1 week)

com.sap.ui5.resource.ACCEPTED_ORIGINS list of accepted origins, e.g. * or *sap.corp,vesapui5.dhcp.wdf.sap.corp (default: empty)

com.sap.ui5.resource.DEV_MODE flag to enable the development mode (default: "false")

com.sap.ui5.resource.TEMPLATE_PATH template for the resource listing (default: "/templates/listing.html")

com.sap.ui5.resource.VERBOSE verbosity of the resource handler (default: "false")

com.sap.ui5.resource.REMOTE_LOCATION location which is used to proxy requests to for resources not being located locally (default: empty)

com.sap.ui5.resource.PREFER_REMOTE_LOCATION flag to prefer resolving the resource from the remote location before fallback to the classpath (default: false)

Configuration parameters are added as context parameters to the web.xml.

Development Mode

When starting to develop SAPUI5 controls and modules being located inside the servlet paths resources/ or test-resources/ it makes simplifies this development process by disabling the caching of such resources as well as enabling the resource browsing. To activate the development mode you need to add the following context parameter.

#!text/xml

<!-- BEGIN: DEV MODE --> <context-param> <param-name>com.sap.ui5.resource.DEV_MODE</param-name> <param-value>true</param-value> </context-param> <!-- END: DEV MODE -->

Resource Browsing

In case of having the development mode turned on you can browse resources via the resource browser:

● %SERVER_URL%/resources/● %SERVER_URL%/test-resources/

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 201

Page 202: Hana Cloud

Tunneling a Remote Location

The ResourceServlet offers the opportunity to tunnel/proxy requests to another server providing SAPUI5 resources. This is the alternative instead for referring to SAPUI5 from remote location inside the bootstrap script tag to avoid cross domain issues. To activate this remote location tunneling/proxying you need to add the following context parameter to the web.xml of your application:

#!text/xml <context-param> <param-name>com.sap.ui5.resource.REMOTE_LOCATION</param-name> <param-value>http://%server%:%port%/sapui5</param-value> </context-param>

This will dispatch requests from resources/sap/ui/commons/Button.js to http://%server%:%port%/sapui5/resources/sap/ui/commons/Button.js.

If you are located behind a proxy and the remote location is outside your local network you can configure the proxy settings via the standard Java Networking and Proxy configurations by setting the system properties (for HTTP): http.proxyHost, http.proxyPort, http.nonProxyHosts, or (for HTTPS) https.proxyHost, https.proxyPort, https.nonProxyHosts of your Java runtime environment.

In general for the resources returned from the proxy the ResourceServlet is enabling caching. It by default uses the configured com.sap.ui5.resource.MAX_AGE to avoid to much load on the ResourceServlet.

Verify that a Resource was Retrieved from Remote Location

When in development mode it is possible to verify that a resource was retrieved from the desired remote location by checking the response header of the respective request. In this case the response header has an entry x-sap-ResourceUrl = remote resource URL, for example:

x-sap-ResourceUrl = http://%server%:%port%/sap/public/bc/ui5_ui5/resources/sap-ui-core.js

Resource Packaging

This section describes the resource packaing for web applications and Java modules which could be any kind of a JAR file (SAPUI5 UI library, ...) available in the classpath of the web application.

● For a web application this means you have to store the resources in the following way:

WebContent/ resources/ **/** test-resources/ **/**

● For the SAPUI5 UI libraries we store the resources in the following way:

META-INF/ resources/ **/** test-resources/ **/**

For custom JAR files you need to apply to this on your own.

202P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 203: Hana Cloud

OSGi Servlet Container

When running SAPUI5 as an OSGi Web Bundle and referencing the UI libraries as OSGi bundles you may need to know about a technical detail how SAPUI5 OSGi bundles are determined:

● In the OSGi servlet container we extend the ResourceServlet by using an OSGi fragment which is responsible to add the OSGi flavor for the determination of UI libaries. Now the ResourceServlet is aware about the OSGi bundles and can search within the OSGi Servlet Container for UI libraries.

● The MANIFEST.MF of UI library JAR files contains a special entry which is used for the determination:

x-sap-ui5-ContentTypes: UILibrary

This is used by the OSGiResourceServlet to determine the relevant UI libraries.

SAPUI5 Library Location Used for Testing

If the SAPUI5 bootstrap tag contains src="resources/sap-ui-core.js", the SAPUI5 runtime libraries from the Eclipse plugin are used.

If you want to test your SAPUI5 application in Eclipse against a different SAPUI5 Library location, for example on the ABAP server when running in the SAP NetWeaver UI AddOn scenario, you can configure the ResourceServlet. For that, open the web.xml file located in the <WebContent folder name>/WEB-INF folder and configure the parameter com.sap.ui5.resource.REMOTE_LOCATION and com.sap.ui5.resource.PREFER_REMOTE_LOCATION of the ResourceServlet where the placeholders {protocol}, {host name}, {port number}, {path to UI5 library} are to be exchanged by the real protocol, host name, port number and path to the SAPUI5 library, see Resource Handling, section Tunneling a Remote Location.

<servlet> <display-name>ResourceServlet</display-name> <servlet-name>ResourceServlet</servlet-name> <servlet-class>com.sap.ui5.resource.ResourceServlet</servlet-class> </servlet> ... <!-- force to use the remote location --> <context-param> <param-name>com.sap.ui5.resource.PREFER_REMOTE_LOCATION</param-name> <param-value>true</param-value> </context-param> <!-- add the remote location for the UI5 libraries --> <context-param> <param-name>com.sap.ui5.resource.REMOTE_LOCATION</param-name> <param-value>{protocol}://{host name}:{port number}/{path to UI5 library}</param-value> </context-param>

Cache Buster

A cache buster allows the application to notify the browser to refresh the resources only when the application resources have been changed. Otherwise the resources can always be fetched from the browser's cache.

When you want to cache your resources permanently, you simply need to change the URL in the SAPUI5 bootstrap tag from resources/sap-ui-core.js to resources/sap-ui-cachebuster/sap-ui-core.js.

The cache buster mechanism allows to always put the SAPUI5 resources into the browsers cache until a UI library or a web application has been changed. The default behavior of the SAPUI5 resource handler is either to cache the

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 203

Page 204: Hana Cloud

resources for a specific amount of time or alternatively in development mode it is using the 304/NOT MODIFIED mechanism to check the SAPUI5 resources for being up-to-date. Both mechanisms are not optimal in a final, productive scenario - that is the reason for the implementation of the cache buster mechanism. Applications, which want to use the cache buster mechanism have to explicitly decide to use it.

The cache buster mechanism is part of the resource servlet. In general requests to JavaScript resources can be handled via the cache buster mechanism. Typically this is used for the initial request for the bootstrap JavaScript:

#!text/html

<script type="text/javascript" id="sap-ui-bootstrap" src="resources/sap-ui-cachebuster/sap-ui-core.js" data-sap-ui-libs="sap.ui.core,sap.ui.commons,sap.ui.table" data-sap-ui-theme="sap_goldreflection"></script>

The bootstrap JavaScript will be included via the URL resources/sap-ui-cachebuster/sap-ui-core.js instead of resources/sap-ui-core.js.

Mechanism

The basic mechanism is implemented in the ResourceServlet. For the request to the bootstrap JavaScript it now serves a JavaScript file with the following content:

#!js

(function() { var sTimeStamp = '~20120716-0201~'; var sScriptPath = 'sap\x2dui\x2dcore.js'; var aScriptTags = document.getElementsByTagName('script'); for (var i = 0; i < aScriptTags.length; i++) { if (aScriptTags[i].src) { var iIdxCb = aScriptTags[i].src.indexOf('/sap-ui-cachebuster/'); if (iIdxCb >= 0 && aScriptTags[i].src.substring(iIdxCb + '/sap-ui-cachebuster/'.length) == sScriptPath) { var sBasePath = aScriptTags[i].src.substring(0, iIdxCb); sBasePath += '/' + sTimeStamp + '/'; window["sap-ui-config"] = window["sap-ui-config"] || {}; window["sap-ui-config"].resourceRoots = window["sap-ui-config"].resourceRoots || {}; window["sap-ui-config"].resourceRoots[''] = sBasePath; document.write('<script type="text/javascript" src="' + sBasePath + sScriptPath + '"></script>') break; } } }})();

This script basically ensures that the global SAPUI5 configuration variable (window["sap-ui-config"]) exists, without modifying any existing values. It defines the resource root of SAPUI5 (the location where SAPUI5 loads all JavaScript modules, controls and control related resources from). Finally, another script tag is added to the page that points to the real boostrap JavaScript. The new resource root and the request path to the bootstrap JavaScript now contain a timestamp. Additionally the cache headers of the reponses now look like the following:

Date: Mon, 16 Jul 2012 05:17:54 GMTExpires: Thu, 14 Jul 2022 05:17:54 GMTCache-Control: max-age=315360000, public

204P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 205: Hana Cloud

By default all cache buster resources will be cached for one year.

Request Flow

When using the cache buster mechanism, the first request must never be cached because it is being used to determine the timestamp / and to finally redirect to the correct script. The following list explains the flow:

● resources/sap-ui-cachebuster/sap-ui-core.js => NO_CACHE● resources/~201106210204~/sap-ui-core.js =>CACHE

Timestamp

If you are interested in the timestamp of the cache buster, you can grab it with the following request:

resources/sap-ui-cachebuster

The response is text/plain with such value: ~20120716-0201~

Application Cache Buster

The Application Cache Buster (short AppCacheBuster) is similar to the Cache Buster but is used for application resources.

Applications provide an index file (created on the fly) containing the last modified timestamps of all included files (scripts, properties – files which we load via XHR programmatically). Technically this file is a mapping between the request path (below the context path of the application) and the last modified timestamp.

The server in general caches all the above resources (not using the 304/not modified mechanism). For the index file we are using the 304/not modified mechanism to avoid to load when it has not been changed.

On the client-side we initially load this file of the application when enabled via configuration option sap-ui-appcachebuster and use this for the XHR requests. If the request path is contained in the above mentioned index file we simply add the timestamp as leading path segment to this request. If the timestamp doesn’t change the URL is unique and therefore it will be taken from cache. Once the file is modified the URL parameter will be changed and therefore loaded again from the backend.

The server has to delete the timestamp from this URL to lookup the file properly. For the Java applications SAPUI5 provides a AppCacheBusterFilter and for ABAP the logic is implemented in the ICF handler. Both backend implementations also generate the index file on-the-fly.

NoteThe Application Cache Buster does not work across application borders. If you require resources from another application they are not loaded via this mechanism.

Application Cache Buster: Index File

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 205

Page 206: Hana Cloud

Unlike the cache buster mechanism for runtime resources, the application files have an own timestamp for each file. Thus, the application provides the index file sap-ui-cachebuster-info.json. This file in JSON format includes all files that should use this mechanism. The index file looks as follows:

{ "mvc/MyMVC.view.js": "20120907134005", "mvc/MyMVC.controller.js": "20120907134005", "mvc/MyMVC.view2.js": "20120906113301", "mvc/MyMVC.controller2.js": "20120906113023"}

Application Cache Buster: Configuration

To activate the Application Cache Buster the configuration data-sap-ui-appCacheBuster="./" must be added to the bootstrap script of the application page:

<script id="sap-ui-bootstrap" src="resources/sap-ui-cachebuster/sap-ui-core.js" data-sap-ui-libs="sap.ui.core,sap.ui.commons,sap.ui.table" data-sap-ui-theme="sap_goldreflection" data-sap-ui-appCacheBuster="./"></script>

The parameter data-sap-ui-appCacheBuster is a string[] which means you can pass a list of base URLs for other applications. By default it should contain the base path of your local application.

These base URLs are used to load the index files. This allows to handle not only the local resources via the Application Cache Buster. Furthermore other applications could then also be handled.

Application Cache Buster: Request Flow

When using the Application Cache Buster mechanism, the first request must never be cached because it is being used to fetch the index file. The following list explains the flow:

1. http://myserver/myapp/sap-ui-cachebuster-info.json ⇒ NO_CACHE2. http://myserver/myapp/~201106210204~/mvc/MyMVC.view.js ⇒ CACHE

○ http://myserver/myapp/mvc/MyMVC.view.js ⇒ internally resolve to this URL

Enable the Filter for Java Applications

To enable the server-side part of the Application Cache Buster mechanism the following filter needs to be configured in the web.xml:

<!-- ============================================================== --> <!-- AppCacheBuster Filter --> <!-- ============================================================== -->

<filter> <display-name>AppCacheBusterFilter</display-name> <filter-name>AppCacheBusterFilter</filter-name> <filter-class>com.sap.ui5.resource.AppCacheBusterFilter</filter-class> </filter> <filter-mapping> <filter-name>AppCacheBusterFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

Application Cache Buster: Enhanced Concept

The first iteration of the Application Cache Buster only supports files which have been loaded via jQuery.ajax. The enhanced concept supports the transformation of URLs for jQuery.sap.includeScript,

206P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 207: Hana Cloud

jQuery.sap.includeStyleSheet, and properties of the type sap.ui.core/URI. This ensures that the Application Cache Buster mechanism takes care about most of the URLs in a general way. Additionally the enhanced concept allows to register components or base URLs which are considered by the Application Cache Buster. This base URL is used to load the index file with the timestamp information.

Registration of external URLs

If you do not specify all the applications in the bootstrap configuration, you can also register them during runtime. To register additional locations, use the following API:

sap.ui.core.AppCacheBuster.register("/sap/bc/my/other/component");

Avoid handling of specific URLs

To avoid handling of specific URLs, you can override the default behavior as follows:

sap.ui.core.AppCacheBuster.handleURL = function(sURL) { return sURL !== "my/specific/url";};

1.3.4.3.8 Control Devlopment Topics

The following sections introduce control development topics:

● Developing UI5 Controls in JavaScrip● Handling Events in Controls● Writing a Control Renderer● Focus Handling● Item Navigation● Right-to-Left Support

Developing UI5 Controls in JavaScript

The following sections explain how to create new controls in JavaScript on the fly, so-called notepad controls). For this basic development approach you do not need to define libraries or run generation steps. You can extend existing controls and create completely new controls.

This functionality is not restricted to controls: You can also create or extend arbitrary objects derived from sap.ui.base.Object.

Technically, the resulting controls are not different from controls developed with SAPUI5 tools.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 207

Page 208: Hana Cloud

Notepad Controls vs. Eclipse-based Controls

Notepad controls have the advantage that you create them very quickly without tools, build, or dependency overhead. You can create them, for example, inline within an application. All JavaScript can be in one file and the application CSS, which may be present anyway, contains the required styles. So notepad controls are a very light-weight approach, but still offering all the features of a real SAPUI5 control.

The control can, however, not be reused easily from different locations and applications: There is no formal way to address it and there is no package which you can reference to import the control. Also, if the control has to support multiple themes and you want to style it by using SAPUI5 theme parameters which are editable in the Theme Editor, if the right-to-left version of the styles should be generated automatically, the Eclipse-based tools offer everything with their integrated build. Checks are not run on a notpad control and no JSDoc documentation can be created.

If a control is supposed to be reused in different applications or by people who do not closely communicate with the control developer, and if a control is more complex than a very basic control, we recommend to consider formally creating a Control Library and using the SAPUI5 Eclipse to create the controls.

Basic Concept: Extend Method

The extend() method is available on all controls (and the base classes) and is used to define a new subclass. The following code creates a new control from scratch:

sap.ui.core.Control.extend(...)

The following code creates a new control which inherits from Button:

sap.ui.commons.Button.extend(...);

The function has the name and the definition of the new control type as parameters. The definition contains information about the control API, that is, the properties, aggregations, events and so on, as well as the implementation of the control methods. In addition to that it provides the function that creates the control's HTML structure.

NoteSAPUI5 creates some methods automatically, such as the getters and setters for properties and aggregations or methods for attaching/detaching event handlers. You can in fact develop a non-default implementation that provides more or other functionality.

A First Basic Example

The following code creates a simple control with a name property. The purpose of the control is to render the text "Hello <name>":

#!js

sap.ui.core.Control.extend("my.Hello", { // call the new Control type "my.Hello" // and let it inherit from sap.ui.core.Control metadata : { // the Control API properties : { "name" : "string" // setter and getter are created behind the scenes, // including data binding and type

208P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 209: Hana Cloud

validation } },

renderer : function(oRm, oControl) { // the part creating the HTML oRm.write("<span>Hello "); oRm.writeEscaped(oControl.getName()); // write the Control property 'name', with XSS protection oRm.write("</span>"); }});

The new control is ready for use now. It can be instantiated and displayed as usual:

#!js

new my.Hello({name:"UI5"}).placeAt("content");

Technical Background

A control is an object that defines the appearance and the behavior of a screen area.

A control has properties, such as "text" or "width". These properties modify the appearance or relate to the data displayed by the control. A control can aggregate other controls: It serves as a sort of container or layout control where the application can add child controls or as a composite control if the control adds child controls and just reuses available components. A control can also have associated controls that are not part or children of this control, but rather loosely related.

A control can fire well-defined events. The meaning of these events typically relates to the control's purpose and functionality and is on a semantically higher level than "click" or other browser events. Examples for such events are triggerSearch in a search field or collapse in a panel.

This information is defined in the control metadata which is the public API of the control and can be queried at runtime and also contains useful information for runtime features like data binding and type validation checks.

Control Base Class

sap.ui.core.Control is the base class of all SAPUI5 controls. Specific controls can either inherit from this base class or from another control to inherit and extend the functionality. sap.ui.core.Element is the base class of sap.ui.core.Control. Elements can be like parts of controls or rather configuration packages for parts of controls, but in general they are not meant for standalone use and do not have their own renderer. The controls that use these elements do the rendering, for example, a ListItem element is rendered by the ListBox control. Whatever this page documents about controls, it usually also applies to Elements (but not to the renderer).

Control Name

The control name is a string that consists of Library name and control name. For both names, you use letters and dots for separation where you should avoid dublicates regarding other JS entity namings within the same application. It is also possible that you omit the library name and call the control Square. You would generally do this if you there is no need for assigning the control to a library which shall also be available

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 209

Page 210: Hana Cloud

for developing other applications. When you write a control to be reused by others, a unique Library name is recommended: sap.byd.Square.

Control Metadata

For the creation of new controls, the metadata block defines the properties, aggregations, events etc. of the control. Depending on the control, not only the number of entries, but also their amount of information can be small or quite extensive.

For the use case class extension - where the classes do not inherit from control or Element but from a more generic class - these control-specific settings are not available. For more information, read chapter "Object Metadata and Implementation" below. Note that all the object metadata described there is also applicable for extending controls.

Properties

A property is defined by at least its name and its type. Additionally, the default value of the property can be defined. So the available settings are:

● type: The data type of the control property. Automatic type validation is done in the UI5 core. Examples for valid types are:

○ string for a string property (default)○ int or float for number properties○ int[] etc. for arrays○ sap.ui.core.CSSSize for a custom-defined type

● defaultValue: The default value this property should have when the application does not set a value. If no default value is given, the property initially has value undefined.

So property definitions can look like this:

#!js

properties: { "title" : "string", // a simple string property, default value is {{{undefined}}} "buttonText" : {defaultValue: "Search"}, // when no type is given, the type is {{{string}}} "showLogoutButton" : {type : "boolean", defaultValue : true}, // a boolean property where a default value is given "width" : {type : "sap.ui.core.CSSSize", defaultValue : "50px"} // a CSS size property where a default value is given}

From the technical point of view, you could also define the "group" (the category into which this property falls), but this has no impact outside of development tools which may want to display and group the properties of your control.

Once such a property is defined, the control automatically has the methods setShowLogoutButton and getShowLogoutButton, which are responsible for storing the data. You can give your own custom definition for either of them, you have to call the generic property setter/getter setProperty/ getProperty then.

210P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 211: Hana Cloud

Events

Events are specified by the event name only. In many cases there is nothing to configure about them, so just give an empty object:

#!js

events: { "logout": {}}

As an advanced feature, controls can enable events to be interrupted by the application, when usually the control would immediately execute an action. For example, if a Tab control fires a "close" event and wants to enable the application to cancel the closing. To do so, the control needs to set the enablePreventDefault property of the Event to "true" (and check the return value after firing the event):

#!js

events: { "close": {enablePreventDefault : true} }

For every defined Event, methods for registering, de-registering and firing the event are created, in this case: attachLogout, detachLogout, fireLogout.

Aggregations and Associations

Aggregations and associations are again defined by their name, along with an object that can have the following information:

● type: This should be a type which is subclass of Element or control (default is sap.ui.core.control)● multiple: Whether it is a 0..1 aggregation or a 0..n aggregation (default is "true", which means 0..n, for

aggregations and "false" for associations)● singularName: For 0..n aggregations, the aggregation name typically is plural, but certain methods are

created where the singular form is required (for example, addWorksetItem} for the "worksetItem' s'" aggregation).

If only the type needs to be set, you can just give it as a string instead of the configuration object.

One example:

#!js

aggregations: { "acceptButton" : "sap.ui.commons.Button", // if only type is given, no object is required "content" : {singularName: "content"}, // default type is "sap.ui.core.Control", // which is appropriate for generic containers "worksetItems" : {type : "sap.ui.ux3.NavigationItem", multiple : true, singularName : "worksetItem"} // a fully specified aggregation}

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 211

Page 212: Hana Cloud

Multiple methods are created, depending on the multiplicity, for example: getWorksetItems, insertWorksetItem, addWorksetItem, removeWorksetItem, removeAllWorksetItems, indexOfWorksetItem, destroyWorksetItems

If you want to mark one aggregation as default aggregation (in order to be able to omit the aggregation tag in XMLViews), you can do this by setting the defaultAggregation property to the name of the aggregation as follows:

aggregations: { "content": {singularName: "content"} // default type is "sap.ui.core.Control", multiple is "true"

},defaultAggregation: "content"

Methods

You can add any method to a new control by providing the implementation, without adding it to the metadata. By convention, all methods are public, exception here is if their name starts with an underscore, or if it is one of the special method types listed below.

Other controls and the application may only call public methods and the control needs to ensure they remain compatible. Though, there are no technical rules that prevent a call of private methods.

Public methods are the generated getter/setter methods for properties etc.

Control Implementation

After the metadata is defined, you can add any method implementations to your new control. In general, the method names can be chosen freely, but note that some method names must be avoided:

● Names of methods that are provided by a super class (or will be provided...). Your implementation overwrites their's, that's the deal with inheritance.

● set.../get.../insert.../add.../remove.../indexOf... may collide with setters/getters for properties or aggregations you defined

● attach.../detach.../fire may collide with methods created for events

As long as you do not introduce the respective property or so, you are of course safe to use a certain "set..." method name.

There are some method names you may use, but which have a special meaning:

● on...: Methods starting with "on" are event handlers that are automatically bound to browser events● init: Is the name of the initialization function called right after Control instantiation● renderer: Is a special name that holds either● the function that creates the Control's HTML or● a complete structure that contains this function and more (for more information see below)

212P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 213: Hana Cloud

Normal Methods

Any method, either public or private, is just appended to the implementation object. The convention is that private methods that may not be called from outside a Control start with an underscore. All other methods are considered public as long as they do not belong to the special method types listed below.

#!js

divide: function(x, y) { // a public method of the Control

if (this._checkForZero(y)) {

throw new Error("Second parameter may not be zero");

}

return x / y;

},

_checkForZero: function(y) { // private helper method

if (y === 0) {

return true;

}

return false;

}

init() Method

The init() method is invoked by the SAPUI5 core for each control instance right after the constructor. Use this to set up things like internal variables or sub-Controls of a composite. Note that any values given in the control constructor are NOT yet available! This is intentional to prevent the typical error where controls would only work fine when values are set initially, but not when values are changed later. This method is considered private and only to be called by the SAPUI5 core.

#!js

init: function() {

this._bSearchHasBeenTriggered = false;

this._oSearchButton = new sap.ui.commons.Button(this.getId() + "-searchBtn", {text: "Search"});

}

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 213

Page 214: Hana Cloud

Event Handler Methods

Methods that have a name starting with "on" are reserved for event handlers. For common events such as "click" or "keydown", browser event handlers for these methods are registered automatically by the SAPUI5 core. So it is sufficient to simple add a handler method, and it will automatically be called. Additionally, the SAPUI5 core fires events with a richer semantic meaning, so control developers do not need to check so many keycodes etc. The name of these events starts with "sap", they are defined in jquery.sap.events.js. One example for such an event is sapnext which is triggered by "arrow down" or "arrow right" (or "arrow left" in right-to-left mode). Therefore, multiple checks would be required to check whether the user wants to navigate to the next item. The sapnext event takes over all these checks. The "evt" object given to the handler method contains more information. These methods are considered to be private and may only be called by the UI5 core.

#!js

onclick: function(evt) {

alert("Control " + this.getId() + " was clicked.");

},

onsapnext: function(evt) {

// navigate to next item, an arrow key was pressed

...

}

Renderer Method / Object

This method is responsible for creating the HTML structure that makes up the control. It is different from the other methods, as it is a static one, so the "this" keyword is not available. Instead, a control instance and a RenderManager instance are given to the method. The RenderManager is used as a sort of "writer" - it is a collector for string fragments and takes care of efficiently concatenating them and placing them into the appropriate DOM position.

#!js

renderer: function(rm, oControl) { oRenderManager.write("<div>", oControl.getText(), "</div>");}

All the features and rules of writing the control Renderer in normal control development apply here as well. The control must, for example, only have one HTML element as root node and inside this node oRenderManager.writeControlData(oControl); must be called, so this root element can be marked as UI5 control root and the ID of the control is written.

The newly created renderer type will inherit from the renderer of the parent control. So if your new control extends TextField, the given function will be added to a class that inherits from sap.ui.commons.!TextFieldRenderer (and will have access to that one's other functions).

214P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 215: Hana Cloud

If an existing renderer should be used without modification, you can give the name of this renderer class:

#!js

renderer: "sap.ui.commons.ButtonRenderer"

However, a normal control renderer can also override or implement methods from its renderer superclass. Or just separate out some helper functions.

This is possible as well here, but in this case these methods need to be packed together into an object, so the extend method knows they should all go into the control renderer. The main rendering method is called "render" - just like in a normal control renderer. The keyword "this" actually refers to the Control Renderer type here, so it is used to access the other methods:

#!js

renderer: {

render: function(rm, oControl) {

rm.write("<div>");

rm.writeEscaped(this.square(oControl.getValue()));

rm.write("</div>");

},

square: function(value) {

return value * value;

}

}

Object Metadata and Implementation

For extending plain objects that are not elements or controls, only the following metadata is available (it is also available for extending controls, though!):

● "interfaces": an optional array of strings that denotes the implemented interfaces● "publicMethods": an optional list of methods that should be part of the public API. By default all methods that

do not start with an underscore are public.● "abstract": an optional flag to mark the type as abstract● "final": an optional flag to mark the type as final

Regarding the implementation, all methods given outside the metadata are attached to the new type. There is one reserved method name: "constructor". The function given under this name will be the constructor of the new class. While technically you can also define a constructor for new elements and controls, you should not do it. Your control may otherwise break in certain scenarios like with list bindings, or may break later when UI5 extends the constructor signature.

Examples for Creating New Controls

To create an entirely new control type, you extend the sap.ui.core.Control class. You define the control API and the implementation from scratch.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 215

Page 216: Hana Cloud

Simple "Square" Control

A "Square" control that is rendered as a red square and has some text written inside and pops up an alert when clicked, looks like this:

#!js

sap.ui.core.Control.extend("Square", { // call the new Control type "Square" and let it inherit // from sap.ui.core.Control

// the Control API: metadata : { properties : { // setter and getter are created behind the scenes, // incl. data binding and type validation "text" : "string", // in simple cases, just define the type "size" : {type: "sap.ui.core.CSSSize", defaultValue: "200px"} // you can also give a default value and more } },

// the part creating the HTML: renderer : function(oRm, oControl) { // static function, so use the given "oControl" instance // instead of "this" in the renderer function

oRm.write("<div"); oRm.writeControlData(oControl); // writes the Control ID and enables event handling - important! oRm.addStyle("width", oControl.getSize()); // write the Control property size; the Control has validated it // to be a CSS size oRm.addStyle("height", oControl.getSize()); oRm.writeStyles(); oRm.addClass("mySquare"); // add a CSS class for styles common to all Control instances oRm.writeClasses(); // this call writes the above class plus enables support // for Square.addStyleClass(...)

oRm.write(">"); oRm.writeEscaped(oControl.getText()); // write another Control property, with protection // against cross-site-scripting oRm.write("</div>"); },

// an event handler: onclick : function(evt) { // is called when the Control's area is clicked - no event registration required alert("Control clicked! Text of the Control is:\n" + this.getText()); } });

The control definition and implementation is finished now, but some styling remains to be done.

The visual appearance could have been written to the control HTML in the renderer method, just like the instance-specific width and height was written. But it is better to define style that is common to all control instances in a CSS file, or at least in a <style> tag, so it only needs to be written once and it can be easily modified by the application.

216P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 217: Hana Cloud

So we add a grey background, a red border and some alignment stuff:

#!css

<style> .mySquare { /* style the CSS class that has been written by the renderer method */ display: inline-block; /* enable squares to appear next to each other within one line */ border: 1px solid red; /* add some border, so the square can actually be seen */ background-color: #ddd; padding: 8px; text-align: center; -moz-box-sizing: border-box; /* consider padding+border part of the width/height */ box-sizing: border-box; }</style>

Use

This custom control can now be used like any SAPUI5 control:

#!js

var myControl = new my.Square({text:"Hello", size: "100px"});myControl.placeAt("content");

Simple Container Control

A container control that can hold arbitrary child controls and renders them in a row, with a colored box around each child, looks like this:

#!js

sap.ui.core.Control.extend("ColorBoxContainer", { // call the new Control type "Square" // and let it inherit from sap.ui.core.Control

// the Control API: metadata : { properties : { // setter and getter are created behind the scenes, // incl. data binding and type validation "boxColor" : "string" // the color to use for the frame around each child Control }, aggregations: { content: {singularName: "content"} // default type is "sap.ui.core.Control", multiple is "true" } },

// the part creating the HTML: renderer : function(oRm, oControl) { // static function, so use the given "oControl" instance // instead of "this" in the renderer function

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 217

Page 218: Hana Cloud

oRm.write("<div"); oRm.writeControlData(oControl); // writes the Control ID and enables event handling - important! oRm.writeClasses(); // there is no class to write, but this enables // support for ColorBoxContainer.addStyleClass(...) oRm.write(">");

var aChildren = oControl.getContent(); for (var i = 0; i < aChildren.length; i++) { // loop over all child Controls, // render the colored box around them oRm.write("<div>"); oRm.addStyle("display", "inline-block"); oRm.addStyle("border", "3px solid " + oControl.getBoxColor()); // specify the border around the child oRm.writeStyles(); oRm.write(">");

oRm.renderControl(aChildren[i]); // render the child Control // (could even be a big Control tree, but you don't need to care)

oRm.write("</div>"); // end of the box around the respective child }

oRm.write("</div"); // end of the complete Control } });

There is no additional CSS required, as the Control has no appearance on its own, but basically consists of its children and the boxes around them.

Use

This strange container control can now be used like any SAPUI5 container:

#!js

var btn = new sap.ui.commons.Button({text:'Hello World'}); var tf = new sap.ui.commons.TextField({value:'edit text here'});

var container = new ColorBoxContainer({ boxColor: "#ff7700", content:[ btn, tf ]}); container.placeAt('content');

Examples for Extending Existing Controls

The following sections are examples of extending existing controls.

218P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 219: Hana Cloud

Extendig the Button with an Additional Event

Let's build a new control, named "HoverButton" that is just like the normal button, but fires a "hover" event in addition when the mouse enters its area.

#!js

sap.ui.commons.Button.extend("HoverButton", { // call the new Control type "HoverButton" // and let it inherit from sap.ui.commons.Button metadata: { events: { "hover" : {} // this Button has also a "hover" event, in addition to "press" of the normal Button } }, // the hover event handler: onmouseover : function(evt) { // is called when the Button is hovered - no event registration required this.fireHover(); },

renderer: {} // add nothing, just inherit the ButtonRenderer as is; // In this case (since the renderer is not changed) you could also specify this explicitly with: renderer:"sap.ui.commons.ButtonRenderer" // (means you reuse the ButtonRenderer instead of creating a new view });

Use

Use this ToggleButton in an application just like a regular button - but you can now attach a handler to the "hover" event.

#!js

var myControl = new HoverButton("myBtn", { text: "Hover Me", hover: function(evt) { alert("Button " + evt.getSource().getId() + " was hovered."); } });

myControl.placeAt("content");

Extending the TextField Rendering

This example builds a new control type that inherits from TextField and has all its features, but changes the rendering to be very highlighted with yellow background.

The control API and even the "render" method can be inherited as is. You only overwrite the renderInnerAttributes method of the TextFieldRenderer:

#!js

sap.ui.commons.TextField.extend("HighlightField", { // call the new Control type

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 219

Page 220: Hana Cloud

"HighlightField" // and let it inherit from sap.ui.commons.TextField

renderer: { // note that NO render() function is given here! The TextField's render() function is used. // But one function is overwritten: renderInnerAttributes : function(oRm, oTextField) { oRm.addStyle('background-color', '#ffff00'); // this change could also be done with plain CSS!! // But you get the idea... } } });

Use

Use this HighlightField in an application just like a regular TextField. It has all the normal features and behavior. But it has the modified rendering.

#!js

var myControl = new HighlightField({value:"Highlighted editing"});myControl.placeAt("content");

Handling Events in Controls

Two types of events exist in SAPUI5 applications:

● Events fired by the browser; these events are well-known, for example "click" and "blur"● Events fired by SAPUI5 controls; these events are usually semantically richer and related to the control

functionality; for example a browser-level "click" on the respective icon in a panel header that triggers a "maximize" or "minimize" event

Applications can listen to both types of events.

The following sections describe how control implementations can use browser events (type 1) to implement their behavior and to eventually fire control events (type 2).

Registering for Browser Events

When a control needs to react on browser events, there are two ways to register for the events, the "standard" way and an "optimized SAPUI5" way:

● Explicitly register for browser events on certain DOM elements, typically using jQuery.bind() (using the respective browser methods like addEventListener would also be possible).The event registration must be done in the onAfterRendering method of the Control, so the event binding is always repeated after the control is re-rendered (new DOM elements are created and old ones are discarded). Furthermore, to prevent memory leaks, the event binding must be removed (with jQuery.unbind()) in the "onBeforeRendering" method and in the "exit" method (which is called before the control is destroyed).

220P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 221: Hana Cloud

○ Pro:ANY type of browser event can be handledWorks exactly like in any web page or jQuery-based web application

○ Con:Quite some code required to do the binding and unbinding of the event handlerRegistering many event handlers can affect performance

Example:

MyControl.prototype.onAfterRendering = function() {

this.$().bind("click", jQuery.proxy(this.handleClick, this)); // could also be: jQuery.sap.byId(this.getId).bind("click", jQuery.proxy(this.handleClick, this)); }

MyControl.prototype.onBeforeRendering = function() { this.$().unbind("click", this.handleClick); }

MyControl.prototype.exit = function() { this.$().unbind("click", this.handleClick); }

MyControl.prototype.handleClick = function(oEvent) { // do something... }

● Just implement the event handler for certain "common" event types, using a name convention for the handler method.SAPUI5 automatically registers event handlers for a list of commonly used event types on the root element of a complete tree of SAPUI5 controls. If the respective event occurs anywhere in the tree and the respective Control implements the on<eventName> method, this method is invoked as if it had been registered with jQuery.bind().

○ Pro:Saves Control codeSaves number of event handler registrations in the DOMSaves evet handler registrations and deregistrations executed on every re-rendering

○ Con:Only works for a certain (comprehensive) list of events

Example:

MyControl.prototype.onclick = function(oEvent) { // do something...}

As you can see from these examples, the SAPUI5 event handling functionality saves code.

List of Supported Browser Events

The following events are available to be handled by just implementing an "on<eventName>" method (list is also available via API, see JSDoc of jQuery.sap.ControlEvents):

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 221

Page 222: Hana Cloud

● click● dblclick● dragend● dragenter● dragleave● dragover● dragstart● drop● focusin● focusout● keydown● keypress● keyup● mousedown● mouseout● mouseover● mouseup● paste● select● selectstart

Pseudo Events

In addition to the native browser events listed above, SAPUI5 also creates so-called "pseudo events" which are semantically enriched, but can also be handled implementing an on<eventName> method. So they "feel like" browser events (but they cannot be used with jQuery.bind()).

These events help avoiding additional checks for modifier keys in the event handler or checking for certain keycodes.

The complete documentation of these events can be found in the JSDoc of jQuery.sap.PseudoEvents. The list is as follows:

● sapbackspace● sapbackspacemodifiers● sapbottom● sapcollapse● sapcollapseall● sapcollapsemodifiers● sapdecrease● sapdecreasemodifiers● sapdelayeddoubleclick● sapdelete● sapdeletemodifiers● sapdown

222P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 223: Hana Cloud

● sapdownmodifiers● sapend● sapendmodifiers● sapenter● sapentermodifiers● sapescape● sapexpand● sapexpandmodifiers● saphide● saphome● saphomemodifiers● sapincrease● sapincreasemodifiers● sapleft● sapleftmodifiers● sapnext● sapnextmodifiers● sappagedown● sappagedownmodifiers● sappageup● sappageupmodifiers● sapprevious● sappreviousmodifiers● sapright● saprightmodifiers● sapselect● sapselectmodifiers● sapshow● sapskipback● sapskipforward● sapspace● sapspacemodifiers● saptabnext● saptabprevious● saptop● sapup● sapupmodifiers

Writing a Control Renderer

For control rendering purposes, the following three classes are relevant:

● The control class - the control that is to be rendered● The RenderManager class - responsible for injecting the generated markup into the DOM and offering helper

functionality

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 223

Page 224: Hana Cloud

● The renderer class - the base class of all control renderers

Control Class sap.ui.core.Control

In general, a control is made up of its properties, events, aggregations, associations, and methods. Together, these parts define the behavior of a Control. The following information is relevant for the appearance and data of the control: properties, associations, and aggregations. This information can be accessed directly with get and set methods of the control during the render() method.

Property Access:

// var oValue = oControl.get<Property>();// for example for the 'text'-propertyvar oValue = oControl.getText();

1..1 Aggregation Access:

// var oAggregation = oControl.get<Aggregation>();// for example for content-aggregationvar oAggregation = oControl.getContent();

1..n Aggregration Access:

// var aAggregations = oControl.get<Aggregation>s();// for example for rows-aggregationvar aAggregations = oControl.getRows();

Association Access:

// var sAssociatedControlId = oControl.get<Association>();// for example labelFor-associationvar sAssociatedControlId = oControl.getLabelFor();

RenderManager Class sap.ui.core.RenderManager

The RenderManager is responsible for injecting the generated markup into the DOM. It takes a control, determines and loads the corresponding renderer, and finally delegates the rendering of the control to the renderer. It also offers helper functionality for rendering purposes as follows:

Method Description

write() Writes string information to the HTML

writeControlData() Writes the ID and the recognition data of the control to the HTML

renderControl() Converts the specified control into HTML representation and adds it to the HTML. Use this for rendering child controls.

For further details, see the JSDoc of the RenderManager.

224P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 225: Hana Cloud

Renderer Class sap.ui.core.Renderer

The Renderer implements the static render method that is called when a control is added to the DOM. The RenderManager executes the render method on the corresponding Renderer for the control to be rendered, and passes the reference to itself and the control.

The following code snippet shows the implementation of a simple renderer:

/** * This module provides the renderer for the MyControl control */

jQuery.sap.declare("sap.ui.myuilib.MyControlRenderer");

/** * @class MyControl renderer. * * @author SAP - TD Core UI&AM UI Infra * @version @version@ * @static */

sap.ui.myuilib.MyControlRenderer = {};

/** * Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}. * * @param {sap.ui.core.RenderManager} oRenderManager The RenderManager that can be used for writing to the RenderOutputBuffer. * @param {sap.ui.core.Control} oControl An object representation of the control that should be rendered */

sap.ui.myuilib.MyControlRenderer.render = function(oRenderManager, oControl) {

// write the HTML into the render manager oRenderManager.write("<span "); oRenderManager.writeControlData(oControl); oRenderManager.write(" class=\"sap-ui-myuilib-MyControlRenderer\" "); oRenderManager.write("></span>");

};

Prevention of Cross-Site Scripting (XSS)

You can find some basic facts about Cross-Site Scripting (XSS).

XSS in SAPUI5 Controls

You must ensure that an attacker cannot inject script code into an application page as it runs in a user's browser. From a controls perspective, this means prohibiting controls from writing any scripts to the page that comes from the application, or might have come from business data saved by a different user. This is achieved by a combination of two measures:

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 225

Page 226: Hana Cloud

● ValidationThe validation of typed control properties means that as soon as a control property has a type other than string, the Core validates the value against this type when the application sets it. In this way, an int is always guaranteed to be an int, and a sap.ui.core/CSSSize is a string representing a CSS size (and not containing a script tag). This is also the case for enumerations and control IDs. The control renderer can rely on this check when writing the HTML.

● EscapingEscaping of string control properties and any other values coming from the application. This is the responsibility of the control developer when creating the renderer. The RenderManager and the Core offer helper methods for this (see below).

Avoiding XSS for your New Renderer

To ensure maximum security for your new renderer, follow the steps described below:

● Use the type sap.ui.core/CSSSize instead of string (or sap.ui.core/string) for control properties that refer to a CSS size.The more general rule is to use the most specific type for control properties that is available.

● If the value of a string property is written to the HTML, it must be escaped using one of the helper methods:

○ For writing plainly to the HTML, use writeEscaped(oControl.getSomeStringProperty()) instead of just write(...).

○ For writing attributes, use writeAttributeEscaped("someHtmlProperty", oControl.getSomeStringProperty()) instead of just writeAttribute(...).

○ For any usages of string properties where the above is not possible, use jQuery.sap.escapeHTML(oControl.getSomeStringProperty()) to escape the string and then process it further.

● Carefully check the HTML coding you are writing and consider whether any application value might make its way to the HTML.

○ Check where the variable values come from (can the application set its value directly, or only decide which of certain hardcoded values are used?).

○ Parameters in method calls of controls are (currently) not validated by the Core, so values given there are candidates for extra escaping.

○ Always keep in mind that XSS can happen anywhere and anytime in CSS classes, or in styles, for example.

Focus Handling

Each of the controls provided by the SAPUI5 framework has its own behavior for focus handling, depending on the functionality that is provided by the control. The highest level of complexity is reached in the case of complex controls and their embedded content.

For custom development of controls, the core of the framework provides mechanisms for observing the moving focus in an application page and preserves this information for refocusing elements after (re-)rendering. Furthermore, the focus triggers event firing. Due to the high degree of flexibility in control rendering, it may be necessary to implement functionality tailored to the control's inner workings. The following sections provide some insights into how to tailor this functionality.

226P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 227: Hana Cloud

The framework provides helper functions for implementating focus handling.

Implementing Focus Handling When Developing Controls

The base class for all elements (Element.js) provides four methods to help you implement focus handling:

● Element.getFocusDomRef()● Element.focus()● Element.getFocusInfo()● Element.applyFocusInfo(oFocusInfo)

Element.getFocusDomRef()

Once a visible element is rendered, it has a Document Object Model (DOM) representation. The root DOM node can be accessed by using the method getDomRef() on the element. The root DOM node is the default focused DOM node. After rendering, the framework asks the control for its focus DOM node by using the getFocusDomRef() method. If the root DOM node does NOT represent the element that should have the focus, you have to return another DOM node by overriding the getFocusDomRef() method.

Element.focus()

The focus() method sets the focus on the element. This is done using the focus DOM node.

Element.getFocusInfo()

With some controls, it is even more difficult to apply the focus once the control has been re-rendered. Controls such as lists have their own internal focus handling, which sets the focus on the different items. A data table moves the focus over a matrix of cells. The requirement is that a control can apply the focus to its exact previous position after re-rendering. To provide this functionality, you override the getFocusInfo() method, and serialize the focus state into a JSON object and return it. Before rendering, the render manager calls this method for the element instance and stores this information for future use. After rendering, it calls the method applyFocusInfo() (see next method) and passes back this serialized object. The cursor position of a TextField control, for example, can also be stored in such an object.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 227

Page 228: Hana Cloud

Element.applyFocusInfo(oFocusInfo)

The applyFocusInfo() method applies the focus to the element after re-rendering. You use this method if different behavior is expected for the element. Note that the default implementation sets the focus as it is implemented in the focus() method (see above).

Example

In our example, a control usually sets the focus on the second child node of its root node. In this case, you would simply override the getFocusDomRef() method.

sap.ui.commons.<SampleControl>.getFocusDomRef = function() { return this.getDomRef().firstChild.nextSibling;}

Another control generally sets the focus back to the element that previously had the focus. Therefore, it overrides the methods getFocusInfo and applyFocusInfo.

sap.ui.commons.<SampleControl>.getFocusInfo = function() { return {id:this.getId(),idx:this.<myFocusElementIndex>};}

sap.ui.commons.<SampleControl>.applyFocusInfo = function(oFocusInfo) { var oDomRef = this.getDomRef(); if (oDomRef) { this.<myFocusElementIndex> = oFocusInfo.idx; this.focus(); }}

Convenience Functionality

In addition to the automatic focus handling provided by the interaction between the render manager and the element instance, further focus-related functionality is available in sap.ui.util.Dom:

Dom.focus(oDomRef)

focus(oDomRef) can be used to focus a particular DOM element. This could be useful in the abovementioned custom focus handing scenario, for controls that cannot be handled by the default behavior of the focus() method or delegates such as ItemNavigation.

228P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 229: Hana Cloud

Dom.hasFocus(oDomRef)

hasFocus(oDomRef) focuses a particular DOM element. It returns true if focusing could be performed and false if not, for example, because the element status was invisible.

NoteMethod naming may change in the future.

Dom.refocus(oDomRef)

refocus(oDomRef) refocuses a particular DOM element. This might be necessary for screen readers, for example, if the element is not read correctly.

Dom.getActiveElement()

getActiveElement() returns the active element (the currently focused element) of the document, if there is one. This information is also used by automatic focus handling during the re-rendering as described above.

Item Navigation - Supporting Keyboard Handling in List-like Controls

One common pattern for keyboard navigation is the item navigation in lists. The UI development toolkit for HTML5 therefore provides a helper class sap.ui.core.delegate.ItemNavigation that implements this functionality. It is intended to be used as a delegate for the keyboard events occurring inside the using control.

Each control that needs the ability to navigate with arrow keys over a one dimensional list of DOM nodes can use this delegate.

The delegate hooks into the browser events for arrow up/down/left/right, page up/down and home/end keys. With a list of DOM nodes provided by the control it sets the focus to the right DOM node in the list while handling the events.

In order to use this item navigation handling, the control needs to provide a DOM node that surrounds all DOM nodes of the items as well as a list of all the DOM nodes of the items themselves. The surrounding DOM node should initially get the focus when the control is entered to ensure the ItemNavigation delegate can do proper focus handling.

Via the methods setCycling the developer can choose whether the focus automatically moves to the top after the end of the list was reached. The page up/down keys will only work if the control developer sets a page size via setPageSize method on the delegate.

Some controls also have one currently selected item in the list that initially should get the focus when the control is entered (again). With the setSelectedIndex method the control can specify such a preselected item for the delegate. If no selected index is given the first item will get the focus when entering the control.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 229

Page 230: Hana Cloud

If the control needs to be triggered before it will be focused by the item navigation, it can handle the events BeforeFocus respectively AfterFocus, to do e.g. preparation tasks for the controls visibility etc.

Using this delegate will save your control about 100 lines of JavaScript code for keyboard handling.

If you like you can still react on the events handled by the delegate in your control.

Integrating the ItemNavigation in your Control

A delegate should be applied in the onAfterRendering hook of a control and besides that should be applied only once:

sap.ui.commons.ListBox.prototype.onAfterRendering = function () { //Collect the dom references of the items var oFocusRef = this.getDomRef(), aRows = oFocusRef.getElementsByTagName("TR"), aDomRefs = []; for (var i=0;i<aRows.length;i++) { aDomRefs.push(aRows[i].firstChild); } //initialize the delegate add apply it to the control (only once) if (!this.oItemNavigation) { this.oItemNavigation = new sap.ui.core.delegate.ItemNavigation(); this.addDelegate(this.oItemNavigation); }

// After each rendering the delegate needs to be initialized as well.

//set the root dom node that surrounds the items this.oItemNavigation.setRootDomRef(oFocusRef);

//set the array of dom nodes representing the items. this.oItemNavigation.setItemDomRefs(aDomRefs);

//turn of the cycling this.oItemNavigation.setCycling(false);

//set the selected index this.oItemNavigation.setSelectedIndex(this.getSelectedIndex());

//set the page size this.oItemNavigation.setPageSize(this.getVisibleItems()); };

Ensure that the delegate is also correctly removed after the control is destroyed. Otherwise memory will leak because DOM nodes are still referenced by the delegate.

sap.ui.commons.ListBox.prototype.destroy = function() { if (this.oItemNavigation) { this.removeDelegate(this.oItemNavigation); this.oItemNavigation.destroy(); } };

Right-to-Left Support in Controls

Right-to-left support is defined as follows:

230P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 231: Hana Cloud

● Unicode defines the directionality of characters which the browser must take into account when arranging characters as words.

● The HTML "dir" attribute overrides the overall directionality of blocks (and influences the text alignment if not explicitly set). In detail there are many more effects, e.g. parentheses are mirrored and viewed as a "word" on their own, which changes their position.

● The HTML "lang" attribute does NOT influence text directionality.● document.dir can be used (browser support is there, it can be set in the bootstrap already, but webkit seems

to reset this to LTR, if set too early).● There is a <BDO> HTML tag which turns off the bidirectional algorithm, i.e. the character order is not reversed

if RTL and LTR words are mixed.● CSS 2.1 has also a "direction" property.

This means in a nutshell:

● Each character inherently belongs to a RTL or LTR script (defined by Unicode). Some characters like parentheses and dots have no inherent directionality. Browsers know all of this.

● For single "words" (characters sequences with same directionality) the browser knows the text direction, and does it "right" automatically, handling them as sort of blocks that get their internal text direction only from the used characters.

● These words/sequences/"runs" are separated by the direction-neutral characters like parentheses and dots - and obviously when character directionality changes.

● The direction in which these blocks are put next to each other depends on the base direction.● The default base direction of HTML is left-to-right, but can be inverted by setting the attribute "dir='rtl'", either

on the <html> tag or on any subregion which should have a different base direction.● This base direction also determines the default text alignment, the order of columns in tables and the

presentation of some direction-neutral characters: opening parentheses are still opening parentheses when RTL mode is switched! This means they render horizontally flipped.

● The algorithm for ordering words/runs/blocks according to the base direction only covers one level of mixed directionality. To achieve deeper nesting, spans with dir attribute can be used o define a subcontext with different base direction.

● While (as said above) words/runs internally always have the text direction implied by the used characters, this behavior can also be overridden (using the <bdo> tag or via CSS unicode-bidi:bidi-override) when the order of characters must follow the base direction regardless of the inherent character direction. E.g. because the characters do not form a word but are really just a list of characters, such as in a part number.

● The "lang" attribute defining the document language does not have any influence on directionality.

SAPUI5 Theming Concept - Right-to-Left Support

The UI development toolkit for HTML5 (SAPUI5) theming concept defines RTL support to be achieved as follows:

● All controls are styled for the LTR case in their "normal" CSS files● Images are put into/below the "img" subfolder● The CSS generator includes an RTL flipping algorithm (inherited from previous SAP UI technologies, proven

over many years, similarly also used in the Open Source community, see CSSJanus):

○ border-left: is converted to border-right:, padding: 1px 2px 3px 4px; is converted to padding: 1px 4px 3px 2px;, float:left; is converted to float:right; etc. The assumption and experience is that this automated conversion does almost the whole job.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 231

Page 232: Hana Cloud

○ Most CSS properties, including CSS3 ones are supported● CSS generation also mirrors all images inside the "img" folder, as this has been found to be the right thing in

most casesSome images should not be mirrored for RTL. The RTL version of those images must then be put into the "img-RTL" folder with the same location and name. In this case the image reference in the CSS is modified to point to this image.

● A control should NOT write any special CSS classes to "notify" the CSS that RTL is turned onIn CSS the <HTML> tag's dir attribute can be checked to provide specific RTL style.

NoteThe written style is still mirrored in the actual RTL case.

Example:

html[dir=rtl] .sapUiBtn { color: red; }

However, this should only be required in rare cases. If you find yourself writing this kind of style more than 1-3% of the time, you should have another look at what SAPUI5's automatic CSS mirroring offers.

Programmatic Access to RTL

Some controls need to provide specific coding in case of RTL mode, e.g. because they are positioning or animating elements programmatically, not via CSS.

The SAPUI5 RTL configuration can be read by calling

var bRtl = sap.ui.getCore().getConfiguration().getRTL();

Impact on Applications

The text direction is LTR by default, but can be set using the various known configuration switches:

● URL parameter sap-ui-rtl=true● Configuration object: window["sap-ui-config"].rtl = true;● Script tag configuration: data-sap-ui-rtl="true"

SAPUI5 takes care of setting the overall page direction to "RTL". All UI5 content will then be displayed in RTL mode. For self-written controls and content you need to test. If manual style adoptions are required, you need to provide style specifically for the RTL case by using html[dir=rtl].

232P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 233: Hana Cloud

Steps

If SAPUI5 is configured to RTL mode, the core:

1. sets dir="rtl" on the HTML tag

○ The W3C officially recommends using the HTML attribute instead of the CSS properties, for example, directionality is a matter of content, not of presentation, and because the CSS properties may even be ignored.

○ Using the <HTML> tag (not the BODY tag) is recommended as well2. loads the respective library-RTL.css files

1.3.4.3.9 Best Practice for Building Mobile Applications

The Best Practices for Building Mobile Applications provide recommendations how to achieve a clear structure and architecture for SAPUI5 applications. The concepts described in the following sections are applied to the Shopping Cart Demo App. You can use its source code to understand the concepts described in the Best Practices.

Caveats

Technically, you can code the whole application in one single HTML file. The simple "Hello World" application is built like this to make the basic functionality easy to understand. But when you create more complex applications, a clear architecture is the key for efficient development and maintainability.

If several possible options exist, for example with regard to the file structure, the granularity of views, or the use of the MVC concept, and the Best Practices use a specific option, this does not mean that the other options are wrong. In fact, other options may suit specific applications even better and some decisions may depend on project experience or team setup.

Nevertheless, this document intends to provide valuable suggestions for a good application structure. Keep in mind, though, that it does not represent the only possible or correct way to build SAPUI5 applications.

The Best Practices contains sections that refer to concepts or controls which are only available in the sap.m mobile library, but most suggestions also apply to desktop applications, or are at least similar for desktop applications.

Overview

The figure below shows the components and dependencies based on the Shopping Cart demo application. The Shopping Cart demo application is a SAPUI5 Mobile application consisting of six pages. The pages are created by using one view and a controller each.

The pages are complemented by an application view and a controller for handling the navigation between views, including the handling of back/forward buttons in the browser. The view content construction in the views and the functionality, navigation, and eventing in the controllers are separated.

For loosely-coupled communication the EventBus is used. There are no direct dependencies between the views, and the EventBus events are only used for navigation and parameter handover between pages.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 233

Page 234: Hana Cloud

Two data models exist:

● "Product", containing the available goods● "Cart", containing the items put into the shopping cart

In addition to these two models, two additional models contain the resources used by the application: one for images and one for translated texts, see Localization and Image Model.

The application is launched from within Application.js (the “App Bootstrap”), which creates the data models and the root/app view. The Formatter utility class is used, but the example does not contain custom controls.

The index.html page itself only contains minimal code for configuring locations and loading the Application.js, see index.html.

As the architecture of an application depends on the size, nature, and structure of the respective application, the example will not fit all applications, but should at least give a rough idea.

File Structure

The following assumptions are made with regard to the file structure:

● As no resource folder is used, the SAPUI5 core/libs can be stored anywhere, that is in a local resource folder or somewhere else.

● As the app is not reused in other apps, it is not necessary to model namespaces in the views/controller paths.

The suggested application structure looks as follows:

The <webapp_root_folder> contains the following namespaces:

234P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 235: Hana Cloud

● Application.js● css folder: Contains all CSS files and the related images, that is style.css and more stylesheets, if required● ext folder: Contains all reused third party java script● i18n folder: Contains all property files for localization, for example:

○ i18n.properties○ i18n_de.properties○ i18n_en.properties

● model folder● util folder: Contains all helper classes● view folder: Contains all view and controller files go here; all file names shall start with an upper case letter● img folder: Contains all image files (png, jpg, gif, …)● <someNamespace>: Contains all on-the-fly controls defined in the application, for example,

<controlName>.js● index.html

Depending on the application, not all resources may be required.

“someNamespace” is, for example, salesorders or a nested namespace, for example sap/hcm/hiring. This namespace is reflected in the package names of the controls, for example var btn = new salesorders.MyButton(); or new sap.hcm.hiring.CustomButton();.

You can use these namespaces also for views, controllers and helper classes, but this depends on the application. The localResources or registerModulePath statements need to be adapted accordingly, see index.html.

index.html

The index.html entry page for an application should have the following structure and content:

● HTML5 DOCTYPE● Meta tag instructing Internet Explorer (IE) to use the newest rendering mode; for SAPUI5 Mobile this is done

in preparation for future IE support, for SAPUI5 desktop application this information is required to make sure IE does not use a compatibility mode

● Charset settings; usually UTF-8, but may need to be adapted to the actual charset● Application <title>● SAPUI5 bootstrap script tag for loading SAPUI5 and the required control libraries and theme● Any application CSS stylesheet links; the SAPUI5 theme stylesheets are inserted directly after the bootstrap

tag, so loading the application stylesheets here guarantees that they can more easily override SAPUI5 styles● Script tag starting the application● HTML body where the SAPUI5 content will be rendered

Of course, specific applications may require additional script tags to load external files or some HTML structure within the body or a script tag before loading UI5 to configure the UI5 runtime. This suggestion here does not say such extensions are not allowed.

Example index.html file

<!DOCTYPE html><html> <head>

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 235

Page 236: Hana Cloud

<meta http-equiv="X-UA-Compatible" content="IE=edge"/> <meta charset="UTF-8">

<title>XYZ</title>

<script id="sap-ui-bootstrap" src="XYZ" data-sap-ui-theme="XYZ" data-sap-ui-libs="XYZ"> </script>

<link rel="stylesheet" type="text/css" href="css/style.css">

<script> // Tell UI5 where to find application content sap.ui.localResources("util"); // paths starting with "util" will be resolved relative to the index.html location sap.ui.localResources("view"); jQuery.sap.registerModulePath('ApplicationBase', 'ApplicationBase'); // this file will be loaded directly from the same directory jQuery.sap.registerModulePath('Application', 'Application');

// Launch application jQuery.sap.require("Application"); var oApp = new Application({root : "content"}); // instantiate your application and mark the HTML element with id "content" as location for the UI </script>

</head> <body class="sapUiBody" id="content"> </body></html>

Application.js

The first code to be executed at runtime is the Application.js. The init function is executed right away and triggers tasks that can be executed without having the DOM available, for example loading JSON files from the server. The main function is only called after the DOM is ready. This is the point in time when you instantiate the app view and controller and place the view in the DOM.

Example for Application.js

jQuery.sap.declare("Application");jQuery.sap.require("ApplicationBase");

ApplicationBase.extend("Application", {

init : function() { // set global models var model = new sap.ui.model.json.JSONModel("model/data.json"); var imgModel = new sap.ui.model.json.JSONModel("model/img.json"); sap.ui.getCore().setModel(model); sap.ui.getCore().setModel(imgModel, "img"); }, main : function() { // create app view and put to html root element var root = this.getRoot(); sap.ui.jsview("app", "view.App").placeAt(root); }});

236P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 237: Hana Cloud

Navigation Handling and Events

This section is intended for SAPUI5 Mobile, in particular for applications using the sap.m.App or sap.m.NavContainer control which handles navigation between pages. However, it can also be used for SAPUI5 applications where views trigger a parent to display different views.

We recommend to use the SAPUI5 EventBus to inform other views about navigation requests.

The following naming shall be applied:

● Channel name: "nav"● Event name for forward navigation to another page: "to"● Event name for backward navigation to the previous page: "back"

// navigate to another pagevar bus = sap.ui.getCore().getEventBus();bus.publish("nav", "to", { id : "Product"});

// navigate to the previous pagevar bus = sap.ui.getCore().getEventBus();bus.publish("nav", "back");

When navigating to another page you often need to pass some information to the target page. This information shall be put to the data of the event. The navTo function of the app controller then passes the data to the app control. It can then be accessed in the onBeforeShow event, which is called on the pages of the app control, that is, the view containing the page.

Navigation to another page:

var bus = sap.ui.getCore().getEventBus();bus.publish("nav", "to", { id : "Product", data : { context : evt.getSource().getBindingContext() }});

Receiving the onBeforeShow event in the target view:

sap.ui.jsview("view.Product", { ... onBeforeShow : function(evt) { this.getController().onBeforeShow(evt); }, ...

Handling the event in the target's view controller

sap.ui.controller("view.Product", { ... onBeforeShow : function(evt) { if (evt.data.context) { this.getView().setBindingContext(evt.data.context); } }, ...

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 237

Page 238: Hana Cloud

History Handling

History handling is one of the most difficult topics in implementing a mobile application. Android and Blackberry devices have a physical back button which triggers for both web and hybrid apps a back navigation in the browser history. For an example of the overall concept and realization, see Demo App: Navigation.

In the architecture example in this Best Practices, the code for history handling is contained in the app controller, including the subscription to history changes:

sap.ui.controller("view.App", {

onInit : function() { // init history mgmt jQuery.sap.require("jquery.sap.history"); jQuery.sap.history({ routes: [{ path : "page", handler : jQuery.proxy(this.historyPageHandler, this) }], defaultHandler: jQuery.proxy(this.historyDefaultHandler, this) }); ...

The app controller sets the history for forward navigation:

sap.ui.controller("view.App", {

... navTo : function(id, writeHistory, navType, data) {

...

// write history if (writeHistory === undefined || writeHistory) { jQuery.sap.history.addHistory("page", {id: id}, false); }

On opening a dialog, a virtual history has to be added. This is not handled in the app controller, but in the related view or controller:

jQuery.sap.history.addVirtualHistory();sap.m.MessageToast.show("Product added to your shopping cart");

Instance Manager

When you open dialogs and popovers, they automatically register themselves in the instance manager. This allows you to easily check for open dialogs or popovers when navigating back, and to close them without maintaining references yourself. The following code shows the navTo function of the app controller:

navTo : function(id, writeHistory, navType, data) { ... // navigate on app var app = this.getView().app; if (navType === jQuery.sap.history.NavType.Back) { if (sap.m.InstanceManager.hasOpenDialog()) { sap.m.InstanceManager.closeAllDialogs();

238P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 239: Hana Cloud

} else { app.backToPage(id); } } ...

Localization

We recommend to use data binding and the sap.ui.model.resource.ResourceModel as a named model for localization. This facilitates the use of translation keys instead of actual texts.

You can also use ResourceBundles, but they require code execution for every translated text set to a control.

For more information, see Use of Localized Texts in Applications.

The following guidelines apply:

● Use i18n as model name● Use only one global property file that contains all texts used in the views.● Group view-specific texts with a prefix; to avoid redundancies, do not apply a prefix to texts which are reused

across view boundaries

Example:

var oModel = new sap.ui.model.resource.ResourceModel({bundleName:"i18n", bundleLocale:"en"});

// set the resource model as global model with the name "i18n" sap.ui.getCore().setModel(oModel, "i18n");

var oControl = new sap.ui.commons.Button({ text : "{i18n>MY_BUTTON_TEXT}"});

Image Model

When referencing images in an application it is more convenient to collect all access paths in one central place instead of having them everywhere in the code. To achieve this, you store them in a JSON file, make this file available with a global JSON model named "img", and bind the controls against this model.

The following code snippet shows how image access paths are stored in a JSON file:

{ "icon" : { "ui5" : "img/SAPUI5Icon.png", "cart" : "img/cart_TabButtonItem.png" }}

The following code snippet shows how images are made available with a global JSON model:

ApplicationBase.extend("Application", { init : function() {

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 239

Page 240: Hana Cloud

var imgModel = new sap.ui.model.json.JSONModel("model/img.json"); sap.ui.getCore().setModel(imgModel, "img"); ...

The following code snippets show how the controls are bound against img model:

this.page = new sap.m.Page({ title : "Shopping Cart", icon : "{img>/icon/ui5}", ...

This approach even allows to switch all images to a different set at runtime with one line of code, for example, to provide differently colored image sets for different SAPUI5 themes.

Utilities

When developing an application, you need to reuse JavaScript coding in multiple views and controllers. You can reuse code by putting the code into separate files which are stored in the util folder. To dynamically load this code at runtime, the SAPUI5 modularization concept is used, see Modularization and Dependency Management.

An example for this is the reuse of a formatter in multiple data bindings. The formatter code is defined in util/Formatter.js as follows:

jQuery.sap.declare("util.Formatter");

util.Formatter = { price : function(value) { jQuery.sap.require("sap.ui.core.format.NumberFormat"); var numberFormat = sap.ui.core.format.NumberFormat.getFloatInstance({ maxFractionDigits: 2, groupingEnabled: true, groupingSeparator: ".", decimalSeparator: "," }); return numberFormat.format(value) + "\u20AC"; } };}

This is a view using the formatter in a data binding:

jQuery.sap.require("util.Formatter");

sap.ui.jsview("view.Home", {

createContent : function(oCon) { ... this.productList = new sap.m.List({}); this.productList.bindAggregation("items", { path : "/products", template : new sap.m.StandardListItem({ title : "{name}", info : { path : "price", formatter : util.Formatter.price } }) ...

240P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 241: Hana Cloud

1.3.4.3.10 Using the Model View Controller Concept in Mobile Apps

For SAPUI5 Mobile applications, you can use the same Model View Controller concept as for Desktop apps, see Model View Controller (MVC) Approach.

You can choose the granularity of Views freely, for example, one view per page. The following sections illustrate the use of the MVC concept in Mobile applications to decouple the different application parts. The following sections are not intended as a best practice document, but rather to illustrate the interaction of views. For a more complex example, see Best Practice for Building Mobile Applications.

An MVC Demo Application

To illustrate the MVC use, we build a simple Mobile application consisting of two pages. The following three views are used:

● One XML view for the app control which forms the root level of the application● One XML view for the home page● One JSView for the detail page

The home page displays a list of countries. By tapping any of the countries, you navigate to the detail page with more information about the selected country.

NoteThe app control holds its child controls in the pages aggregation. This does not mean that only sap.m.Page controls can be aggregated: The demo application puts the views into the aggregation. Therefore, calling app.getPages() returns the directly aggregated views and not an sap.m.Page control.

The following figure depicts the overall structure of the application. The homePageView is displayed initially and the detailPageView is displayed when drilling down to details. The appView only holds the sap.m.App control for page navigation. It has no visible user interface, but is always rendered as a sort of invisible frame containing the application.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 241

Page 242: Hana Cloud

The HTML Page

The App_with_rootView.html page launches the application:

● It loads SAPUI5.● It ensures that all resources starting with sap.m.mvc, that is, the views and controllers are loaded from

locations relative to the HTML page.● It instantiates the root view and places it into the content div element.

Example for the HTML page:

<script id="sap-ui-bootstrap" src="../../../../resources/sap-ui-core.js" data-sap-ui-theme="sap_mvi" data-sap-ui-libs="sap.m" ></script>

242P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 243: Hana Cloud

<script> // let UI5 know that certain package (the one containing the Views/Controllers) is available locally (next to the HTML file) sap.ui.localResources("sap.m.mvc");

// define View and place it onto the HTML page sap.ui.xmlview("appView", "sap.m.mvc.App").placeAt("content"); // all other initialization will be done by the App controller

</script>

The Root (App-) View

Although the root view and controller could be omitted by putting some code into the HTML file, this example shows how view are embedded into others to use MVC as much as possible.

The concept is simple: One sap.m.App control aggregates two sap.m.Pages. The first page is displayed initially:

<core:View controllerName="sap.m.mvc.App" xmlns="sap.m" xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns:html="http://www.w3.org/1999/xhtml">

<App id="theApp"> <mvc:XMLView id="homePageView" viewName="sap.m.mvc.HomePage"></mvc:XMLView> <mvc:JSView id="detailPageView" viewName="sap.m.mvc.DetailPage"></mvc:JSView> </App>

</core:View>

The viewName elements define the view type and the location, from which the respective view is loaded. The AppView also defines a controllerName, so a controller is loaded and attached as well.

The Root (App-) Controller

The root controller handles the following actions:

● It loads the data from a JSON file by using an AJAX call and initializes the overall JSONModel.● It handles the page navigation by listening to events published by the views and triggers the appropriate

navigation on the app control by using the EventBus.

When the user taps a list item on the homePageView, it publishes a to event in the nav channel. The root controller then executes the navToHandler method. After loading the view, if necessary, the root controller calls this.app.to(data.id, data.data.context) to trigger the navigation to the second page and to hand over the bindingContext, which contains information about the item the user selected on the initial page.

This leads to a horizontal slide animation. This is the default setting, but other animations can be chosen as well.

The back navigation is handled similarily, but is more simple, as no data needs to be passed. The app control keeps track of the page stack and automatically navigates back to the homePageView, using an inverse animation.

sap.ui.controller("sap.m.mvc.App", {

onInit : function() { var view = this.getView();

// Data is fetched here jQuery.ajax("Data.json", { // load the data from a relative URL (the

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 243

Page 244: Hana Cloud

Data.json file in the same directory) dataType: "json", success: function(data){ var oModel = new sap.ui.model.json.JSONModel(data); view.setModel(oModel); } });

// remember the App Control this.app = view.byId("theApp");

// subscribe to event bus var bus = sap.ui.getCore().getEventBus(); bus.subscribe("nav", "to", this.navToHandler, this); bus.subscribe("nav", "back", this.navBackHandler, this); },

navToHandler : function(channelId, eventId, data) { if (data && data.id) { // lazy load view if (this.app.getPage(data.id) === null) { jQuery.sap.log.info("now loading page '" + data.id + "'"); this.app.addPage(sap.ui.jsview(data.id, "sap.m.mvc." + data.id)); } // Navigate to given page (include bindingContext) this.app.to(data.id, data.data.context); } else { jQuery.sap.log.error("nav-to event cannot be processed. Invalid data: " + data); } },

navBackHandler : function() { this.app.back(); }});

The HomePage Controller

The HomePage controller handles the tap on a list item by publishing the event to the nav channel and hands over the relevant view (DetailPage) and the context of the tapped list item.

sap.ui.controller("sap.m.mvc.HomePage", {

listItemTriggered: function(evt) { // Option 1: using custom data attached to the ListItem // The ID (abbreviation) of the country is available as a custom data object and... // ...we could use it to fetch detail data // ...or we could hand it over to the detail page with .to("detailPage", {id: id}); var id = evt.oSource.data("id"); // this id remains unused in this example, though!

// Option 2: // In case of data binding we can get the binding context (a sort of pointer to the data object to which the clicked ListItem is bound) var bindingContext = evt.oSource.getBindingContext(); // evt.oSource is the ListItem

// The EventBus is used to let the Root Controller know that a navigation should take place. // The bindingContext is attached to the data object here to be used in the Root Controller's event handler.

244P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 245: Hana Cloud

var bus = sap.ui.getCore().getEventBus(); bus.publish("nav", "to", { id : "DetailPage", data : { context : bindingContext } }); }});

The HomePage View

The HomePage view contains the content, which is displayed initially. It contains a full screen page control which displays a list of countries. The list is made from a StandardListItem template using SAPUI5 data binding. For each country in the data, one list item is created and displayed.

When you tap a list item, the attribute tap="listItemTriggered" calls the listItemTriggered method of the HomePage controller.

<core:View controllerName="sap.m.mvc.HomePage" xmlns="sap.m" xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns:html="http://www.w3.org/1999/xhtml">

<Page id="homePage" title="Countries"> <List items="{/countries}"> <StandardListItem title="{name}" description="{short}" type="Navigation" tap="listItemTriggered"> <customData> <!-- this is an OPTIONAL way to bind additional data to each list item; when the item is tapped, this data is read in the Controller --> <core:CustomData key="id" value="{short}" /> </customData> </StandardListItem> </List> </Page>

</core:View>

The DetailPage View

To give an example for other view types as well, the detail page of this example is build as a JSView. As usual for JSViews, the createContent method constructs the user interface of the view which contains one sap.m.Page control containing a List and a VBox layout. The List displays the details for the selected country. By using data binding it is ensured that the correct country data is displayed without actively fetching this data.

Triggering Back Navigation

While the semantics of the button on the left hand side of the page header is different between platforms ("back" button on iOS, "up" button on Android), the sap.m.Page only offers a navigation button and it is up to the application whether there is a difference between "up" and "back" on the respective page or whether it follows the platform guidelines and respects the difference.

In our example, "up" is the same as "back" and we only display this button with the label Countries (appears only on iOS). When the button is tapped, the method backTriggered of the view controller is called. The second array entry is the context of this method: When the method is executed, "this" is the controller.

var oPage = new sap.m.Page({ title:"Details",

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 245

Page 246: Hana Cloud

showNavButton:true, navButtonText: "Countries", navButtonTap:[oController.backTriggered,oController]});

An application can also take shortcuts, for example, by directly calling app.back() if the "app" object is known inside the view. This demo application, however, wants to demonstrate maximum decoupling.

Handling the Navigation Event

Pages, or rather children of NavContainer/App controls such as this detail view, are informed about navigation activities. You can attach delegates to these pages for preparation and cleanup work. These delegates are also informed about the navigation activities. For more information, see Navigation and Lifecycle Events in the App and the NavContainer.

To updates the data binding every time before it is displayed, the detail view registers for beforeShow and sets the binding context which has been passed by the root controller as payload data of the to(…) call, which triggered the detail page navigation.

this.addEventDelegate({ onBeforeShow: function(evt) { this.setBindingContext(evt.data); // evt.to is actually this View (the navigation target). This should be "this" in the future to be more intuitive... }}, this); // give this (= the View) as additional parameter to make it available inside the delegate's functions as "this" object

The beforeFirstShow event can be used in a similar way by the application to lazily construct the UI only when it is actually required due to the user navigating to this page. Currently, the view UI creation in createContent is executed on application startup.

The Entire View Code

sap.ui.jsview("sap.m.mvc.DetailPage", {

getControllerName: function() { return "sap.m.mvc.DetailPage"; },

/** * Creates the UI of this View * * @returns {sap.ui.core.Control} */ createContent: function(oController) {

var oPage = new sap.m.Page({ title:"Details", showNavButton:true, navButtonText: "Countries", navButtonTap:[oController.backTriggered,oController] });

246P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 247: Hana Cloud

// create the page content structure jQuery.sap.require("sap.ui.core.format.NumberFormat"); var oList = new sap.m.List({headerText: "Country Details", items: [ new sap.m.DisplayListItem({label:"Capital:",value:"{detailInfo/capital}"}), new sap.m.DisplayListItem({label:"Population:",value:{ path:"detailInfo/population", formatter:function(iValue){ var oFormatter = sap.ui.core.format.NumberFormat.getIntegerInstance({ // format the population count groupingEnabled: true, groupingSeparator: "." }); return oFormatter.format(iValue); } }}), new sap.m.DisplayListItem({label:"Currency:",value:"{detailInfo/currency}"}), new sap.m.DisplayListItem({label:"Area:",value:{ path:"detailInfo/area", formatter:function(iValue){ var oFormatter = sap.ui.core.format.NumberFormat.getIntegerInstance({ // format the area groupingEnabled: true, groupingSeparator: "." }); var formattedNumber = oFormatter.format(iValue); return formattedNumber + " sq km"; } }}) ]}); oPage.addContent(oList); var oFlagArea = new sap.m.VBox({ alignItems: sap.m.FlexAlignItems.Center, items: [ new sap.m.Label({text:"Flag:"}), new sap.m.Image({src:"{detailInfo/flagUrl}",decorative:true,densityAware:false}) ] }); oPage.addContent(oFlagArea);

this.addEventDelegate({ onBeforeShow: function(evt) { this.setBindingContext(evt.data); // give this (= the View) as additional parameter to make it available inside the delegate's functions as "this" object } }, this);

return oPage; }

});

The DetailPage Controller

The DetailPage controller only contains the method for publishing the back event to the nav channel of the EventBus. The root controller listens to this event and triggers back navigation.

sap.ui.controller("sap.m.mvc.DetailPage", {

backTriggered: function() { var bus = sap.ui.getCore().getEventBus();

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 247

Page 248: Hana Cloud

bus.publish("nav", "back"); }

});

Run the Application

To launch and inspect the MVC demo app, see Demo App: Model View Controller (MVC).

1.3.4.3.11 Navigation and Lifecycle Events in the App and the NavContainer

Mobile apps are often composed of several pages and the user can drill-down to detail pages and go back up again. This is often visualized by horizontal slide animations.

SAPUI5 supports this pattern by providing the sap.m.App control, which handles the navigation between the pages.

sap.m.App inherits the navigation capabilities from the sap.m.NavContainer control. Thus, both controls are equal with regard to navigation and navigation events. The following sections refer to the sap.m.NavContainer, but the same also applies to the sap.m.App control.

A mobile application can control the navigation flow centrally and directly trigger the initialization or refresh of the pages. To support modularization of the app, however, it may also be beneficial to control the navigation flow non-centrally. In this case, code which constructs a page is also the code that handles, for example, the data load in this page.

To support this, SAPUI5 provides two types of events:

● Events fired by the App/NavContainer whenever it navigates, see Events Fired Centrally by the App/NavContainer

● Events fired on the pages when they get shown or hidden by navigation, see Events Fired on the Pages

Events Fired Centrally by the App/NavContainer

When NavContainer.to(…) or NavContainer.back(…) are called, the NavContainer triggers events and the application can register for this events. The navigate event is fired before the transition animation starts, and the afterNavigate event is fired when the animation has been completed.

The events contain a lot of information about the page that is left and the target page of the navigation, as well as what kind of navigation is happening.

Example:

app.attachNavigate(function(evt) { var isBack = !evt.getParameter("isTo"); // there are several types of back animation, but we want the general direction only alert("Navigating " + (isBack ? "back " : "") + " to page " + evt.getParameter("toId"));});

248P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 249: Hana Cloud

For more information, see

Events fired on the Pages

Events fired on the pages allows a decentral reaction to navigation. The NavContainer fires events to its child controls regardless of whether they are displayed or hidden.

NoteAlthough this documentation calls them "pages" and a sap.m.Page control may be the typical child of a NavContainer, any full screen control can be used, for example, a sap.m.Carousel control or a custom control. Thus, the event is not fired by the child control, but by the NavContainer on the child control (whatever type it is). This causes the different registration compared to normal control events.

Before the navigation animation starts, the NavContainer fires the following events:

● beforeHide on the page which is about to be left● beforeFirstShow on the page which is about to be shown; this event is only fired if the respective page has

not been opened before● beforeShow on the page which is about to be shown

These events can be used to create or update the user interface of the new page and to stop any activity, such as animations or repeated data polling, on the page which is left.

After the navigation has been completed and the new page has covered the whole sccreen, the following events are fired:

● afterShow on the page which is now shown● afterHide on the page which has been left

You can destroy the hidden page, and the now active page can start its activity.

You can use the addEventDelegate function to register to these events. This function is available on every control.

page1.addEventDelegate({ onBeforeShow: function(evt) { // page1 is about to be shown; act accordingly - if required you can read event information from the evt object }, onAfterHide: function(evt) { // ... }});

For more information, see

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 249

Page 250: Hana Cloud

Passing Data when Navigating

When you use the to(…) and back(…) methods of the NavContainer to trigger navigation, you can also give an optional payload data object. This object is then available in the events described in the Events Fired on Pages section above, for example, beforeShow and afterShow, see Events Fired on the Pages. You can also use this mechanism to decouple page implementations.

Example:

app.to("detailPage", {id:"42"}); // trigger navigation and hand over a data object // this data object could also be a binding context when dealing with data binding...

// and where the detail page is implemented:myDetailPage.addEventDelegate({ onBeforeShow: function(evt) { var idToRetrieve = evt.data.id; // ...now retrieve the data element with the given ID and update the page UI }});

When you navigate back to a page, it receives the original data object which has been given when you first navigated to the page, but you can also give an additional data object with the back navigation.

For more information, see

Example Application

The example application for the Model View Controller concept illustrates the use of the navigation events and how they help in modularizing an application. You can launch it from

1.3.4.3.12 Adapting to Platform and Form Factors

The SAPUI5 Mobile library target devices run different operating systems and have very different screen sizes and pixel densities. SAPUI5 does some adaptations automatically. In addition to that, the application can further adapt to the current device.

The following sections give an overview of the adaptations done by SAPUI5 and what adaptations the application can provide additionally.

250P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 251: Hana Cloud

Built-in Adaptation of SAPUI5 Mobile

Platform-dependent Styling

The sap_mvi ("Mobile Visual Identity") theme delivered with the SAPUI5 Mobile library provides three different visual styles which closely mimic the native look of the Apple iOS, the Android, and the Windows Phone platform. Compared to the native visuals they are adapted to match the SAP color scheme with black and golden color accents.

● The iOS design has the typical Apple gradients and rounded corners, but is tinted in black and grey with golden accents.

● The Android design is using the Android 4.0 ("Ice Cream Sandwich") design with rather flat elements with no gradients or rounded corners. While the ICS design already uses black color, the MVI theme adds golden accents while maintaining Google's original blue style in the interactive controls

● The Windows Phone design mimics the typical chrome-less visuals, but does not adapt the entire interaction to feel 100% native.

The controls look very much like the native UI controls on these platforms, so the user immediately recognizes them.

NoteFor BlackBerry 10 the Android look and feel is currently used.

Other Platform-dependent Adaptations

In addition to the visual design, the SAPUI5 Mobile library provides further platform adaptations. To a certain degree, controls automatically adapt to the native UI concepts and user experience without any effort on application side.

The following list gives examples:

● The sap.m.Page control by default creates a header which looks different on both platforms even though there is only one single Page API:

○ On iOS, the navigation button is the typical Apple back button with a label and an arrow shape on the left hand side and the header title is positioned in the center.

○ On Android, the navigation button appears as an arrow with no label; an optional icon is displayed next to it and the header title is displayed left-aligned.

○ On Windows Phone, no back navigation button is available. Instead, the phone's hardware button is used for back navigation.

● When used in a bar on Android, the sap.m.SegmentedButton looks like a tab.● The sap.m.Dialog appearance not only differs between operating systems, but also between form factors:

○ On Android, it is a bright popup with buttons filling the whole popup footer.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 251

Page 252: Hana Cloud

○ On iPad, it is a popup with dark header and buttons in the left and right side of the header.○ On iPhone, it looks like on iPad, but covers the full screen and is sliding in from the bottom.

The SplitApp Control - Adapting Automatically to Different Form Factors

You can use the sap.m.!SplitApp control to implement multi-page scenarios that automatically adapt to the available screen size: On phones, only one page is displayed, and on tablets, especially in landscape orientation, two pages are displayed simultaneously.

For more information, see SplitApp - Hello World.

Options for further Adaptation

In addition to the adaptations done automatically by SAPUI5, the application can apply further platform adaptations. To facilitate these adaptations, SAPUI5 provides a variety of detection mechanisms.

Mobile vs Desktop

It is getting more and more difficult to detect for the application whether it runs on a desktop or on a mobile device: Some Desktop computers support touch operations, keyboards can be attached to tablets, and you can detach laptop screens to use them as tablets.

Depending on your own definition of the distinction between desktop and mobile, you can detect touch capabilities, for example, by checking the following:var isTouchDevice = jQuery.support.touch;Based on this check, SAPUI5 provides also the following flag:var runningOnDesktop = jQuery.device.is.desktop;Other possibilities include checking the screen size or whether certain APIs or features are available.

Phone vs Tablet

The distinction between phone and tablet is also becoming more and more difficult as the phone sizes are growing and almost approach tablet sizes.

The current definition is that a device is a phone rather than a tablet as long as size of the screen is smaller than 600 pixels. This definition is used by the jQuery.device.is.tablet flag.

var runningInTablet = jQuery.device.is.tablet;The flag also contains additional information, such as:

252P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 253: Hana Cloud

● iphone, ipad: Flags whether the application runs on either of them● Desktop, phone: Alternatives to "tablet" (the distinction between desktop and tablet is made by checking

touch capabilities)

For more information, see

In the CSS, you can use CSS media queries to check screen sizes.

iOS vs Android and Version Information (as JavaScript API)

The jQuery.os object contains information about the operating system:

● os: Operating system as string ("ios", "android", "winphone", or "blackberry")● ios, android, winphone, blackberry: Boolean flags for the respective platform● version: Operating system version as string● fVersion: Operating system version as float

For more information, see

iOS vs Android vs Windows Phone vs BlackBerry - and Version Information (for CSS styling)

SAPUI5 also adds platform and browser version information to the root element (the <html> element of the page). There are different three information packages:

● The CSS class "sap-ios", "sap-android", "sap-winphone", or "sap-bb" (for BlackBerry) is added for easy platform-dependent styling.

● The attribute "data-sap-ui-browser" is added, providing more information about browser and version.● The attribute "data-sap-ui-os" is added, providing more information about operating system and version.

You can use the CSS class directly in cascades, the other two need attribute selectors which can also be used to match substrings:

.sap-ios .myControl { color: red; /* make my control red on Apple devices only */}

html[data-sap-ui-browser*=msf] .myControl { background-color: blue; /* Control should have a blue background whenever Mobile Safari is running... */}

html[data-sap-ui-os="iOS5.0"] .myControl { background-color: green; /* ...but when running on an Apple device with version 5.0 of the operating system, it should rather be green */}

For more information, see Platform Attribute for Mobile.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 253

Page 254: Hana Cloud

Orientation and Change of Orientation

The jQuery.device.is object contains information about the page orientation:

● landscape: Flag indicating whether the current orientation is landscape● portrait: Flag indicating whether the current orientation is portrait

For more information, see

If the orientation is changed, because the user rotates the device, the browser fires the orientationchange event. In some cases, this event seems to be delayed, and, therefore, the sap.m.App control fires its own orientationChange event based on the browser's window resize event:

myApp.attachOrientationChange(function(evt) { if (evt.getParameters().landscape) { // do something... }});

In CSS, you can use CSS media queries to check this.

1.3.4.3.13 Platform Attribute for Mobile

A platform attribute is added to the HTML tag when running on mobile devices. This attribute provides information about the current platform and version.For an application running on an iPad3, for example, the attribute value is "iOS5.1".

NoteSAPUI5 Mobile currently only supports iOS, Android, Windows Phone 8 and Blackberry 10.

In addition to that, SAPUI5 adds a platform-dependent CSS class to the HTML tag of the page. This enables control or application developers to create platform-dependent styling for their controls or applications.

Technical Details of the Platform Attribute

The following list provides additional information about the platform attribute:

● When the SAPUI5 bootstrap script file is loaded, a check is performed to see if the application is running on a mobile platform. If this is the case, the attribute and CSS classes are added to the HTML tag.

● The platform attribute value has the following connotation: Operating system + version, for example iOS6.0, Android4.1.1, bb10.0.9.2372, winphone8.0. Operating system can have the following values:

○ iOS (Apple devices)○ Android (Android devices)○ bb (BlackBerry)

254P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 255: Hana Cloud

○ winphone (Windows Phone)

The version numbers are separated by dots.The possible values for the CSS class are:

○ sap-ios (Apple devices)○ sap-android (Android devices)○ sap-bb (BlackBerry)○ sap-winphone (Windows Phone)

● The platform attribute or CSS class is used as follows:Example for providing a different font on Android devices; you can specify your font by directly using the CSS class "sap-android".

.sap-android{ font-family: Roboto;}

Example for providing a different font when running on Android 2.x:

html[data-sap-ui-os^='Android2'] .sap-android{ font-family: "Droid Sans";}

1.3.4.3.14 Split App - Hello World

As tablets such as iPad or Google Nexus7 provide more space compared to smartphones, porting existing mobile apps to tablets leads to a lot of unused space.

A common pattern to address this is called Master-Detail" pattern, which is also often used in native iOS and Android development. Good examples are the native Settings and E-Mail applications of iOS and Android tablets. This pattern can be used with the SplitApp control.

The figure shows the basic idea of the pattern. The app is divided into two views, the Master and the Detail view. The Master view presents a list of items and is used as the main navigation within the application. The Detail contains detail information for the selected item.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 255

Page 256: Hana Cloud

Whereas the selection of an item on a mobile devices navigates the user to the detail page, the user can see the list of items and the detail view at the same time on a tablet device.

If the tablet device is used in protrait mode it has less available width space. For this, the SplitApp? control provides three different modes for displaying the master and detail view in portrait mode:

● ShowHideModeThis is the default mode. This mode hides the Master view automatically when the user turns the device into portrait mode. To display the Master view, the user swipes right on the Detail view or uses the button which is be placed on the header of the Detail view.The Master view slides in from the right hand side. The user can choose another list item which will update the Detail view and automatically hides the Master view again.

● PopoverModeThis mode places the Master view inside a popover which can be opened via the button in the header of the Detail view.

● StretchCompressModeThis mode displays the Master view in both, the portrait and the landscape mode. In portrait mode, the Detail view has less space available.

In landscape mode, all three modes described above display the Master view.

If you run a SplitApp on a mobile device, it automatically behaves like a standard mobile application. The following figure shows the difference:

256P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 257: Hana Cloud

As only one page per screen can be displayed, the Master and Detail view are automatically displayed on separate pages and the standard page navigation is applied.

The following section explains how a SplitApp application is build, see The First SplitApp.

The First SplittApp

To develop a SplitApp application, use the sap.m.SplitApp control instead of the sap.m.App control which is used for smartphone applications only:

var oSplitApp = new sap.m.SplitApp("mySplitApp", {});

You can add pages to the SplitApp control, but you have to decide to which view you want to add them:

oSplitApp.addDetail() or oSplitApp.addMaster();

Before you can do this, you need some basic pages, two for the Master and two for the Detail view:

var oDetailPage1 = new sap.m.Page("detail1", { title : "Detail 1", content : [ new sap.m.Label({ text : "this is Detail 1" }) ]});

var oDetailPage2 = new sap.m.Page("detail2", { title : "Detail 2", content : [ new sap.m.Label({ text : "this is Detail 2" }) ]});

To implement a basic navigation for selection of the Detail view, the two Master view pages need a list. As we only need to navigate or drill down inside the Master view, a simple StandardListItem with type Navigation is sufficient.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 257

Page 258: Hana Cloud

If the user taps on a list item, we navigate to Master view page 2. To do this, call the toMaster() method with the page you want to navigate to. In the example this is master2.

var oMasterPage1 = new sap.m.Page("master1",{ title : "Master", content : [ new sap.m.List({ items : [ new sap.m.StandardListItem({ title : "To Master 2", type : "Navigation", tap : function() { oSplitApp.toMaster("master2"); } })] }) ]});

The second Master view page is the leaving point of the master navigation: Depending on the item the user selects, the Detail view is updated. An example for this is an e-mail application with a list e-mails in the Master view and the content of the e-mail in the Detail view.

As we do not want to further navigate within the Master view, the list mode is set to SingleSelectMaster.

To update the Detail view, we have to listen to the list's select events, so we can decide on which detail page to show. Depending on the selected list item, either the detail1 page or the detail2 page is displayed. The method is called toDetail.

var oMasterPage2 = new sap.m.Page("master2",{ title : "Master2", navButtonTap : function() { oSplitApp.backMaster(); }, content : [ new sap.m.List({ mode:"SingleSelectMaster", select: function(oEv) { if(oEv.getParameter("listItem").getId() == "listDetail2") { oSplitApp.toDetail("detail2"); }else { oSplitApp.toDetail("detail1"); } }, items : [ new sap.m.StandardListItem("listDetail2",{ title : "To Detail 2" }), new sap.m.StandardListItem("listDetail",{ title : "To Detail 1" }) ] }) ]});

To enable the SplitApp to run on mobile devices, some additional information needs to be added to the pages. Also, the navigation back to the Master view page has to be available from both Detail view pages.

In the next step, the pages are put into the SplitApp control:

//add the master pages to the splitapp controloSplitApp.addMasterPage(oMasterPage1).addMasterPage(oMasterPage2);

//add the detail pages to the splitapp controloSplitApp.addDetailPage(oDetailPage1).addDetailPage(oDetailPage2);

258P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 259: Hana Cloud

Then set the initial Master view and Detail view page:

oSplitApp.setInitialDetail("detail");oSplitApp.setInitialMaster("master");

Define the page transition type you want to use, see Navigation and Lifecycle Events in the App and the NavContainer.oSplitApp.setDefaultTransitionNameDetail("fade");Finally, place the SplitApp control in the HTML body tag:

oSplitApp.placeAt("body");

To test the other two SplitApp modes, use the setMode method to set them:

oSplitApp.setMode("PopoverMode");//oroSplitApp.setMode("StretchCompressMode");

1.3.4.3.15 Layouting with FlexBox

User interfaces often have to adapt to different screen sizes. Therefore, building user interfaces in a way that a single layout reliably fits the available screen real estate is challenging. The FlexBox control allows to develop layouts which adjust to the available space and avoid unused space or overflow. FlexBox controls can be nested to create more complex layouts.

The two main uses of a FlexBox control are:

● Two-dimensional layouting● Flexible layouts

Getting Started With FlexBox

To use a flexible box layout, create a FlexBox control and add any kind of controls to it, either by using the addItem method (see option 1), or the items aggregration of a configuration object (see option 2).

Option 1

var oMyFlexbox = new sap.m.FlexBox();oMyFlexbox.addItem( new sap.m.Button({text: "Button 1"}) );oMyFlexbox.addItem( new sap.m.Button({text: "Button 2"}) );

Option 2

var oMyFlexbox = new sap.m.FlexBox({ items: [ new sap.m.Button({text: "Button 1"}), new sap.m.Button({text: "Button 2"}) ]});

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 259

Page 260: Hana Cloud

The following figure gives an example how the result looks like if used inside a mobile app page. The necessary code is not shown here.

Layout properties

Some properties that affect the layout need to be set in the FlexBox control. Other properties can be attached to the controls which are placed inside the FlexBox by means of the layoutData aggregation. The layout direction, for example is set in the FlexBox as follows:

var oMyFlexbox = new sap.m.FlexBox({ items: [ new sap.m.Button({text: "Button 1"}), new sap.m.Button({text: "Button 2"}) ], direction: "Column"});

The order is attached to the button inside a FlexItemData object as follows:

var oMyFlexbox = new sap.m.FlexBox({ items: [ new sap.m.Button({ text: "Button 1", layoutData: new FlexItemData({order: 2}) }), new sap.m.Button({text: "Button 2"}) ]});

260P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 261: Hana Cloud

NoteThe FlexBox control is a wrapper for the flexible box layout properties in CSS. The control renderer sets the CSS properties (including prefixed versions where necessary) on the appropriate HTML elements. The actual layouting is done by the browser.

The controls that you place in the FlexBox control are each wrapped in a DIV or LI element, depending on the renderType property. All elements are placed inside another DIV or UL container, again depending on the renderType. The outermost element represents the so-called flex container while its child elements are flex items. The HTML structure resulting from all of the examples above looks as follows:

<div class="sapMFlexBox">

<div class="sapMFlexItem">

<button id="__button1">Button 1</button>

</div>

<div class="sapMFlexItem"> <button id="__button2">Button 2</button>

</div></div>

NoteThe layoutData properties that you can attach to a control are applied to its wrapper element with sapMFlexItem class. This is because browsers currently only support these properties on some elements, for example DIV.

The two additional controls HBox and VBox are FlexBoxes that are fixed to horizontally or vertically layout their children.

Important FlexBox Layout Concepts

The following sections contain information about important concepts for FlexBox layouts.

Main Axis and Cross Axis

A FlexBox layout has a direction in which child elements are laid out. The default direction is Row and rows are laid out horizontally in reading direction. This defines the main axis. The cross axis in this case is vertical.

You can change the layout direction property to Column, which results in a vertical main axis and a horizontal cross axis. This is important for the align properties.

Note

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 261

Page 262: Hana Cloud

If browsers support vertical text flows, the direction of a row can also be vertical. For now this is not an issue and can be ignored.

In addition to Row and Column, the flex direction can be set to RowReverse and ColumnReverse which will reverse the layout direction.

Two-Dimensional Alignment

You can determine where the flex items are aligned in a FlexBox layout. For the alignment you use the following two properties: justifyContent and alignItems. The justifyContent property sets the alignment along the main axis while alignItems acts on the cross axis.

Both properties accept the values Start, Center and End. This results in nine possible combinations, for example

● justifyContent = End and alignItems: Start places the items in the upper right corner of a horizonzal FlexBox● If you set the direction property to Column, the main axis would be vertical. Combined with justifyContent =

End and alignItems: Start, the items are placed in the lower left corner.● By reversing the main axis with direction = ColumnReverse the layout starts from the bottom. In this case,

justifyContent = End refers to the top of the FlexBox.● justifyContent has the additional value SpaceBetween?. This setting places the first and the last item at the

extremes of the main axis. Any other items will be distributed evenly between these two.

For alignItems two additional values exist: Baseline and Stretch. Baseline takes the first line of text of each flex item and aligns their baselines. This can be useful if different font sizes are used. Stretch makes the flex items take up the whole space along the cross axis of the FlexBox. This is useful if all items should have the same size regardless of the amount of content.

Flexibility

You can let the browser handle the distribution of elements. This ensures that they always fill the available space along the main axis. To do this, set a flexibility factor on the flex items.

The property to control the flexibility is called growFactor. It is set on a flex item object by means of FlexItemData on the layoutData aggregation. The flex layout algorithm determines the "natural" width of the flex items. If there is space left, this space is distributed among the flex items according to their relative growFactor. If, for example, a horizonzal flex container is 300px wide and contains two elements of 100px each, 100px would remain. If the growFactor for both flex items is set to 1, both get 50px extra, thus making them 150px wide. If the growFactor is set to 3 for one item and to 1 for the other item, the first item gets additional 75px (¾ of 100px) of the remaining space and the second item 25px (¼ of 100px). If the growFactor is set to its default value of 0, the item is inflexible and both items would keep their width of 100px.

NoteThe the flex algorithm distributes the remaining space, and not the whole space in the FlexBox. Therefore, the resulting widths of the items are not necessarily proportional to the growFactor.

262P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 263: Hana Cloud

To achieve a proportional width according to the growFactor, set the width of all items to 0 via CSS. The sum of the "natural" widths of all items is then also 0. The remaining space, however, now equals the full space of the FlexBox. This space is then distributed based on the growFactor. For the example above with growFactor set to 3 and 1, setting the the width of the flex items to 0 via CSS results in a width of 225px (¾ of 300px) for the first item and 75px (¼ of 300px) for the second item.

CautionOnce you set a growFactor for any item, the flex layout algorithm ignores the justifyContent property of the FlexBox because the items take up all available space anyway. There would be no difference between the different values.

For more examples of FlexBox use, see Demo App: FlexBox.

1.3.4.3.16 Working with Lists

List

List can have the following properties:

● modeThis property defines in which way the left area of a list item will appear. You can show a single selection, multi selection, delete buttons, or none of these.The mode property can have the following values:

○ None (default)○ SingleSelect (on the right side)○ SingleSelectLeft (on the left side)○ SingleSelectMaster (without select control for use cases like the split app, by default the !

includeItemInSelection = true)○ MultiSelect○ Delete

● includeItemInSelection (default: false)This property defines the tap handling of a list item. By default, you can select an item by tapping the radio button or check box. To use the whole list item tap for selecting an item, change the property value to 'true'. This property is only relevant in selection mode.

● showUnread (default: false)This property decides whether an 'unread' indicator is added to each list item. When active, it shows a blue bubble for unread list items.

● showNoData (default: true)If set to 'true', a text is shown to the user if a list has no content . The default text is 'No data'. You can use the noDataText property to change the default text.

● noDataText (default: 'No data')

Swipe For Action

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 263

Page 264: Hana Cloud

A user can swipe left on a list item to bring in a control, for example a button, and initiate an action for this item. This control is defined through the swipeContent aggregation of the list and will be displayed on the right or center of the list item. For more information, see Swipe List for Action.

List Events

For selection, deletion and swiping in lists, events are needed. The selection mode fires a 'select' event and the deletion mode a 'delete' event. A swipe left fires a 'swipe' event. These events contain information about the list item that caused the event.

● select (listItem)● delete (listItem)● swipe (listItem), see Events

Rerendering

A list including all its list items is rerendered when the data of a bound model is changed. Due to the limited hardware resources of mobile devices this can cause delays for lists with many list items. Therefore, we do not recomment the use of a list for these use cases.

ListItemBase

All SAPUI5 list items inherit from ListItemBase. It contains the navigation, selection and event features.

Five different types are available, which determine the way a list item is interacting. A list item has a content area (main area) which may fire a tap event and a navigation area on the right hand side, which may fire a tap or a detailTap event. The "type" property for each list item defines the events which are fired. This needs to be configured because it also decides the visual feedback a list item gives when touched.

NoteBy default, a list item does not fire an event unless it is configured with a type that defines how events are fired. An exception to this ActionListItem.

The following table shows the different combinations of list item types and events:

type tap event detailTap event icon active feedback

Inactive (default) -- -- -- --

Active yes -- -- yes

Navigation yes -- > yes

Detail -- yes (>) --

DetailAndActive yes yes (>) yes (only content)

ListItemBase has a 'unread' indicator property (default: false), which shows a blue bubble. This has to be enabled in the showUnread property. For the selections on each list item a selected property (default: false) exists. Another feature is the counter property (default: null), which shows integer numbers except zero. If the number is zero, the counter will be hidden.

● unread (default: false)● selected (default: false)

264P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 265: Hana Cloud

● counter (default: undefined)

ActionListItem

The ActionListItem inherits all features from the ListItemBase and provides the following additional feature:

A text can be set, which will be center aligned.

text

this is a simple list item for triggering actions.

CustomListItem

This is a simple list item for triggering actions.

The CustomListItem inherits all features from the ListItemBase and provides following additional feature:

content can be aggregated.

The CustomListItem can be used for all list items SAPUI5 does not provide. You can build your own content and aggregate it.

Custom HTML

An easy way to cover simple CustomListItems is to add an HTML control, in which you can write your HTML either directly, or if you use a model and data binding, you can use a formatter to integrate it between the HTML.

Example: We have a model with first name, last name, age, and city properties. We create a CustomListItem, add a HTML control to the list item content and than write a formatter with our HTML code:

var myCustomListItem = new sap.m.CustomListItem({ content: new sap.ui.core.HTML({ content: { parts: [ {path: "firstName"}, {path: "lastName"}, {path: "age"}, {path: "city"} ], formatter: function(firstName, lastName, age, city) { return "<div><div class='myStyleClass'>Name: " + firstName + " " + lastName + "</div><div>Age: " + age +"</div><div>City: " + city +"</div></div>"; } }}), type : 'Navigation' //({type} if provided by the model) tap : myTapEvent});

CautionThis approach only works when you use JavaScript for the UI. When using a declarative model, such as XML Views, use an on-the-fly control, see Developing UI5 Controls in JavaScript.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 265

Page 266: Hana Cloud

DisplayListItem

The DisplayListItem inherits all features from the ListItemBase and provides the following additional features:

● label - for setting a label● value - for setting a value

InputListItem

The InputListItem inherits all features from the ListItemBase and provides following additional features:

● label - for setting a label● content - for content aggregation; you can set one of the following controls: Input button, radio button,

checkbox, slider, select, search

StandardListItem

The StandardListItem inherits all features from the ListItemBase and provides following additional features:

● title - for setting a title● descripton - for adding a description● icon - for adding an icon on the left hand side, which can be showen with or without an inset; the property

contains the icon source path to the location where all images for all device resolutions are stored● activeIcon - the property contains the icon source path for images that are shown while the list item is tapped● iconInset - default is 'false': Image takes the whole list item height; when set to 'true', the icon is rendered as

an inset● iconDensityAware - when set to 'false', no checks for other resolutions are made; use this option if you do not

want to provide icons with a specific resolution

1. An icon on the left side which can be shown with or without an inset.

2. A title can be set.

3. A description can be set.

● title● description● icon (Icon source path where all the images for each device resolution can be found.)● activeIcon (Icon source path for images which should be shown while the list item is tapped.)● iconInset (Default: false images takes the whole list item height, true for an inset.)● iconDensityAware (If you won't provide specific device resolution icons, set it to false. Therefore no checks fpr

other resolutions are made.)

266P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 267: Hana Cloud

Swipe for Action in Lists

If a user swipes left on a list item, you can bring in a control, for example a button, to initiate an action for this item. The button is displayed on the right hand side on center of the list item. An example is shown in the following figure.

Aggregation

This control is defined by the swipeContent aggregation of the list. You can add any control as swipeContent, but keep in mind that your content cannot be higher than a list item, see the following examples:

● Button swipeContent

var list1 = new sap.m.List({ swipeContent : new sap.m.Button({ text : "Approve", type : "Accept", tap : function() { /* ...approving code goes here... */

// we are done hide the swipeContent from screen list1.swipeOut(); } }) }), ...

● Control combination as swipeContent

new sap.m.List({ swipeContent : new sap.m.HBox({ items : [ new sap.m.Image({ src : "images/edit.png", tap : ... }), new sap.m.Image({ src : "images/delete.png", tap : ... }) ] }), ...

Events

List provides a swipe event when a user swipes left to bring in a control on the right hand side of the list item. This event is fired before the swipeContent is shown and contains the following three important parameters:

● listItem : List item that fired the swipe event

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 267

Page 268: Hana Cloud

● swipeContent: Specifies the swipeContent control to show on the right hand side of a list item● srcControl: Specifies the control that fired the swipe event

This means that you can dynamically change the swipe content according to the respective list item. If a list item, for example, has not yet been approved, the Approve button is shown. After approval or if it is already approved, the Disapprove button is shown. See the following example:

var list1 = new sap.m.List({ swipeContent : new sap.m.Button({ text : "Approve", type : "Accept", tap : function() { /* ...approving code goes here... */

// we are done hide the swipeContent from screen list1.swipeOut(); } }) }), swipe : function(e) { // register swipe event var oSwipeListItem = e.getParameter("listItem"), // get swiped list item from event oSwipeContent = e.getParameter("swipeContent"); // get swiped content from event

// Check swiped list item if it is already approved or not if (oSwipeListItem.data("approved")) { // List item is approved, change swipeContent(button) text to Disapprove and type to Reject oSwipeContent.setText("Disapprove").setType("Reject"); } else { // List item is not approved, change swipeContent(button) text to Approve and type to Accept oSwipeContent.setText("Approve").setType("Accept"); } }, ...

Swipe events can be cancelled. The built-in controls which are working with swipe left events like Switch or Slider cancel a swipe event by default. If you also want to disable swipe events for your custom use case, you can call the preventDefault method of the event object. This is shown in the following example:

new sap.m.List({ swipe : function(e) { // get which control inside the list item fired swipe event var oSrcControl = e.getParameter("srcControl");

// check if the event is coming from Input if (oSrcControl instanceof sap.m.Input) { e.preventDefault(); // cancel swipe } }, ...

Methods

List provides the following two swipe methods:

● swipeOut( [callback] ): After swipeContent is shown, the user can interact with the control, for example tap it. After this interaction, for example on tap event, you can use this method to hide swipeContent from the screen. Per default, swipe for action works on auto hide mode. This means that if a user tries to tap inside the list but outside the swipeContent, then the swipeContent hides automatically.

268P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 269: Hana Cloud

After you call this method, swipeContent hides with animation and if you need to run code after the animation you can simply add a callback function to this method as a first parameter.

● getSwipedItem(): This method returns the currently swiped list item. When no item is swiped, null is returned. The swipeContent events, for example tap, are a good place to use this method to get information for which list item swipeContent is shown.

The following example shows a delete scenario:

var list3 = new sap.m.List({ swipeContent : new sap.m.Button({ text : "Delete", type : "Reject", tap : function() { var oSwipedItem = list3.getSwipedItem(); // Get which list item is swiped to delete list3.removeAggregation("items", oSwipedItem); // Remove this aggregation to delete list item from list list3.swipeOut(); // we are done, hide the swipeContent from screen } }), ....

Properties

The swipeDirection property for lists is used to configure the direction of the swipe event. This property accepts an enumeration from sap.m.SwipeDirection? with the following values.

● LeftToRight?: Swipe from left to right● RightToLeft?: Swipe from right to left● Both: Both directions (left to right or right to left)

The default value is Both, but in some use cases we recommend to change this property, for example to prevent swipe conflicts.

1.3.4.3.17 Triggering Phone, SMS and E-Mail

With SAPUI5 for Mobile you can easily trigger native mobile phone applications such as e-mail, telephone, and text messages. You can set predefined values for the application so that a user does not need to enter this information themselves. When personal information is displayed, for example phone numbers and e-mail addresses, you can initiate a phone call or e-mail with just one tap.

API for Triggering Telephone, Text and E-Mail Applications

The URLHelper API contains the following triggers for telephone, texts, and e-mail applications. For more information, see the API documentation under

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 269

Page 270: Hana Cloud

Trigger Telephone Application

sap.m.URLHelper.triggerTel( [Telephone Number] ); //Telephone number is optional

Trigger Text Application

sap.m.URLHelper.triggerSms( [Telephone Number] ); //Telephone number is optional

Trigger E-mail Application

sap.m.URLHelper.triggerEmail( [Destination Email], [Subject], [Default Message Text], [CC], [BCC] ); // All parameters are optional

Redirect To Custom URL

sap.m.URLHelper.redirect( URL ); //URL is required and can be used for custom protocols (e.g http, ftp, ...)

Examples for Triggering Telephone, Text and E-Mail Applications

Sample data used in the examples:

var person = { name : "John Smith", tel : "+49 62227 747474", sms : "+49 173 123456", email : "[email protected]", website : "http://www.sap.com"};

You can trigger an external application at any time, but it is usually triggered as a reaction to a UI control throwing an event. The next sections illustrate some of the most typical use cases.

Click Button To Trigger Phone Call

The following button can be used to place a call. The figure shows, how the button looks like.

270P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 271: Hana Cloud

new sap.m.Button({ text : person.tel, icon : "images/action.png", /* Depends where your images are located */ tap : function() { sap.m.URLHelper.triggerTel(person.tel); }});

Click Image To Trigger E-mail

The following code snippet gives an example for triggering an e-mail application. You can also set the subject and message of the e-mail application:

new sap.m.Image({ src : "images/website.png", /* Depends where your images are located */ tap : function() { sap.m.URLHelper.triggerEmail(person.website, "Info", "Dear " + person.name + ","); }});

Inside List

DisplayListItem with active feedback is the most popular use case for the following example.

new sap.m.DisplayListItem({ label : "Sms", value : "( " + person.sms + " )", type : "Active", tap : function() { sap.m.URLHelper.triggerSms(person.sms); }});

To use any other control inside the list, use InputListItem?:

new sap.m.InputListItem({ label : "Website", content : new sap.m.Button({ text : person.website, tap : function() {

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 271

Page 272: Hana Cloud

sap.m.URLHelper.redirect(person.website); } })});

Notes

● iOS does not trigger a phone call if the phone number contains "*" or "#".● You can add multiple recipients for a text message in Android phones by separating recipient numbers with

";".● According to RFC 2368 you can set multiple subscribers for the e-mail application by separating each with ",";

however, this still depends on the application. Outlook, for example, uses ";" as separator.● You can use the sap.m.URLHelper.redirect method to use custom URL schemes:

○ For iOS: http://developer.apple.com/library/safari/#featuredarticles/iPhoneURLScheme_Reference/Introduction/Introduction.html

○ For Android: http://developer.android.com/guide/appendix/g-app-intents.html○ URI schemes: http://en.wikipedia.org/wiki/URI_scheme

● If you just want to get a URI back without a redirect, you can use normalize methods which have the same parameter as trigger methods, for example:

/* * These methods do not redirect but return URI scheme back as string. * All parameters are optional */sap.m.URLHelper.normalizeTel( [Telephone Number] );sap.m.URLHelper.normalizeSms( [Telephone Number] );sap.m.URLHelper.normalizeEmail( [Destination Email], [Subject], [Default Message Text], [CC], [BCC] );

1.3.4.3.18 Scrolling in SAPUI5 Mobile

Because of limited size of mobile devices, scrolling is an essential topic in mobile user experience. Smooth and easy scrolling is important for user acceptance of mobile applications.

In general, application programmers do not need to take care of scrolling when using the sap.m control library. Scrolling is provided automatically by the following controls:

● sap.m.Page● sap.m.Dialog● sap.m.Popover● sap.m.ScrollContainer

However, if you create a custom scrollable control, read the following sections.

272P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 273: Hana Cloud

Scrolling: Implementation Details

Unfortunately, scrolling support in mobile browsers is very weak and inconsistent. Only the newest platforms and browsers start to support partially usable scrolling functionality.

Hence, SAPUI5 embeds the open source livrary iScroll4 that takes care of scrolling in the application. Though the library is globally available in a SAPUI5 application, programmers should not call it directly. The sap.ui.core.delegate.ScrollEnablement delegate provides all functionality and smooth integration of iScroll4 into the SAPUI5 library.

For more information, see

Do not use nested scrolling

We do not recommend to use nested levels of scrolling, for example, when a page with enabled vertical scrolling contains a scroll container that has vertical scrolling too. Such combinations may lead to behavior that is unexpected both for programmers and users.

Implement a custom scroll container

A custom control that needs to provide a scrollable area for its content should implement the following steps:

1. Instantiate a sap.ui.core.delegate.ScrollEnablement delegate, at best in the .onAfterRendering callback.

2. Implement a .getScrollDelegate method that returns the current instance of the delegate to other controls.

3. Destroy the ScrollEnablement delegate on exit.

Example:

myCustomScroller.prototype.onAfterRendering = function() { if(!this._oScroller){ jQuery.sap.require("sap.ui.core.delegate.ScrollEnablement"); // attach a scroller to the scrollable container DOM element this._oScroller = new sap.ui.core.delegate.ScrollEnablement(this, this._scrollContainerId, { horizontal: false, vertical: true }); }};

myCustomScroller.prototype.getScrollDelegate = function() { return this._oScroller;};

myCustomScroller.prototype.exit = function() { if(this._oScroller){ this._oScroller.destroy(); this._oScroller = null; }};

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 273

Page 274: Hana Cloud

NoteThough the SAPUI5 library includes also a Zynga scroller, it is an experimental alternative to iScroll4 that is not supported in SAPUI5 and may be used for testing only. The configuration parameter oConfig.zynga=true of the scrolling delegate should therefore not be used.

Interaction with the scroll containers

There are cases, when an embedded control controls scrolling of the parent container, if required. These are

● a sap.m.ScrollContainer inside a sap.m.Page may block parent scrolling, if it scrolls in the same direction itself;

● a sap.m.TextArea control in edit mode blocks parent scrolling, so that the user can scroll text contents during input;

● a sap.m.GrowingList control scrolls parent container to update positions of visible items after the new items have been loaded from the server.

When using a sap.m.FlexBox with fitContainer set to true inside of a page, the enableScrolling property of the page needs to be set to false for the FlexBox to fit the viewport.

Scrolling: Pull to Refresh

The SAPUI5 mobile library supports the "pull down to refresh" functionality that allows users to refresh lists or page content with fresh data from server. To implement it, create a sap.m.PullToRefresh control and put it as the first control into a page or a scroll container that contains the list that needs to be refreshed.

Example:var pullToRefresh = new sap.m.PullToRefresh({ description: getLastUpdatedTime(), refresh: function(){ pullToRefresh.setDescription("loading from server..."); // request new data from server getNewData({ // when data comes from server onSuccess: { pullToRefresh.hide(); pullToRefresh.setDescription(getLastUpdatedTime()); redrawList(); } }); }; The application should request new data on the refresh event and call the hide method when the data is received and the list is refreshed. You can provide a URL to a custom logo image with customIcon or switch display of logo of by setting showIcon to false. The first line of text "Pull to refresh" is standard and cannot be changed. However, you may set an optional description text to display, for example, the last update time.

Note: PullToRefresh control is part of the scroll area and therefore its height is reflected in the scroll bar calculation and display. The user can see that the page can be scrolled down to reveal the pull-down area.

274P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 275: Hana Cloud

Carousel

Pull to Refresh does not work with a Carousel if both are contained in a page: in order to make Pull to Refresh work, the page has to enable scrolling which leads to problems with the Carousel (Carousel not visible). Suggested Workaround: Add a sap.m.PullToRefreshinstance to each page that you add to your Carousel.

1.3.4.3.19 Running in Web Containers

Note the following information for running mobile applications in Web containers:

Device Ready Event

The hybrid web container takes some time to initialize itself. During the initialization, it blocks sending AJAX requests. This means that the JavaScript code stops once an AJAX request is sent and does no further code execution. This leads to a UI freeze effect.

As the oData model in SAPUI5 uses AJAX requests internally, the oData model initialization must be done after the hybrid container is ready not avoid blocking the user interface.

Hybrid containers fire a special event when the initialization is completed. This event is called deviceready in PhoneGap. Therefore, moving the code where the oData model is created and setting to the core object or any other controls' model property to the deviceready event listener, fixes this issue.

Example:

<script><!-- put the following code in the beginning of the application code -->function appReady(){ sap.ui.getCore().setModel(new sap.ui.model.odata.ODataModel(<ODATA_URL>, false));}<!-- bind to the deviceready event -->document.addEventListener("deviceready", appReady, false);</script>

Cross Domain Restriction

If you load data from an external server or service using AJAX, the external domain has to be configured inside the hybrid web container to make the AJAX request go through the cross domain restriction. We have integrated our demo applications into PhoneGap and here are our findings after doing the integration:

● AndroidThere is no cross domain restriction any more if the AJAX code runs inside the webview in Android which means we can load data using AJAX from everywhere. This is what we found but in the PhoneGap documentation, it says the domain still needs to be configured in one XML file.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 275

Page 276: Hana Cloud

● iOSThere's still this restriction in Webview in iOS, the domain that will be visited using AJAX should be added to a while list file in order to enable this to go through the restriction. For the detailed information about this white list file, please see the reference here.

1.3.4.3.20 Using Images in Mobile Applications

When using images in mobile applications, note the following.

Supporting Different Pixel Densities

Some mobile devices, starting with iPhone4 and iPad3, have a display with a very high density of pixels (four pixels where older models would only have one pixel). They are called "retina displays" by Apple to suggest they are as crispand clear as the eye can see. They use four physical pixels to display one logical CSS pixel, so images can be displayed much sharper when given twice as large as usually required because internally the device can use much more pixels to display all details of the image. Browsers on those displays do this automatically when images are scaled down.

So some devices support higher resolution images while others do not. We therefore recommend that SAPUI5 application developers provide image resources for all relevant densities to provide a very crisp and clear display of images on devices with "retina display".

The sap.m.Image control automatically chooses the right density, depending on the device on which it is displayed. If an image of a certain density is not available, the image control falls back to a default image, which should be provided as well.

NoteThe image control is also used implicitly by other mobile controls, for example

● Button● Segmented Button● Standard List Item

CautionIf you do not have higher resolution images you should set the densityAware property to false to avoid unnecessary roundtrips.

276P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 277: Hana Cloud

Example

Assume the following controls are displayed on a device with high-density screen (window.devicePixelRatio is 2):

new sap.m.Image({ densityAware: false, // tell the image control that there are no different optimized image variants src : "first.png" // therefore Image control will directly load first.png })

new sap.m.Image({ src : "second.png" // Image control will first look for [email protected], then fall back to second.png})

The first image control has been told that there are no image files for the different densities, so it will directly load "first.png". This image looks as good as other images on retina displays.

The second image control will first attempt to load [email protected] which should be twice as large as the normal image and would be scaled down for display, so it looks absolutely crisp on retina displays. If this file does not exist, it will fall back to "second.png", but this fallback will cause an additional server request.

Naming Conventions

Density related images are loaded if you provide an image name with density awareness in following format is provided:

[imageName]@[densityValue].[extension]

Currently, we support the densities 1.5 and 2. The follwing example shows a set of images with different densities:

● detail.png (default)● [email protected][email protected]

[email protected] (not supported any more, will use the standard image for such low density device)

1.3.4.3.21 Message Handling

The following guidelines for message handling are recommended. We recommend to invest care and energy in good message content:

● Provide short and crisp error messages to the user.● A message should always contain a 'Call for Action'.● To achieve the above you need to map error messages from a backend system.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 277

Page 278: Hana Cloud

● Focus on the most common error situations and improve the messages there.● For the rest simply state that a 'Backend' or 'Database' error has occurred. The user cannot handle this

anyway and no further details are required. If technically feasible, ease the process of receiving support from IT, for example submit the issue and related information to support or at least provide contact information.

● It is a must to detect all problems related to network connectivity and indicate them as such.

Messages Related to a Page

For showing messages to the user that are related to the currrent page you have two options depending on the importance of the message.

Message Dialog:

● A message dialog interrupts the user's workflow by blocking the current page and needs to be closed by the user.

● Use a message dialog if the message is important and must be acknowledged by the user.● The easiest way of showing a message dialog is to use the sap.m.MessageBox.● If you want full control of the content you can also use sap.m.Dialog control and set the type to

sap.m.DialogType.Message.● On iOS, a special visual design is applied to the dialog. On Android and Blackberry, the message dialog has the

same design as the standard dialog.

278P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 279: Hana Cloud

Message Toast:

● A message toast is an overlay that disappears after some time or if the user taps somewhere else. It does not block the user.

● Use this pattern if the message is less important and the user should not be blocked in his work.● You can open a message toast easily with sap.m.MessageToast.

Messages Related to Elements of a Page

For showing messages to the user that are related to a specific element of a page there is no dedicated UI control available in sap.m in this version. We recommend to use the sap.ui.core.HTML control to show these error messages 'somewhere close to the input' or use some kind of overlay. Consider that the user will have the on screen keyboard open which might hide messages. Putting the message above an input field could help.

You can set the ValueState of the sap.m.Input control to 'Error' to indicate that the content is not correct.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 279

Page 280: Hana Cloud

Multiple Messages

SAPUI5 Mobile does not support multiple messages at the same time. Mobile Designs recommend to be 'more sparse' with messages, that is, only show one message at a time. This can also be achieved by combining and reducing multiple messages.

1.3.4.3.22 Navigation Using Browser History

HTML 5 offers features, such as HTML pages that fetch data asynchronously and update the UI dynamically without reloading the page. However, the browser history back/forward buttons do not work any more because the URL of the application always stays the same.

This may be acceptable as a back button can be provided directly in the App which can be used instead of browser's back button. For some mobile platforms, however, such as Android, the user is used to using the physical back button to do back navigation inside an application. Thus, the back in the application is no option of choice for SAPUI5 Mobile.

What does the physical back button do?

If an application runs on a mobile device with a physical back button, tapping on the back button has the same effect as tapping on the browser back button. If no history state in browser history exists, it quits the browser application. This is also valid when application runs in a WebView using a hybrid container as long as the container does not interfere with the default behavior of the back button.

How should we support the physical back button?

An applications built with SAPUI5 Mobile runs through pages. After navigating to a new page, the user expects to go back to the previous page when tapping on the physical back button. This behavior assumption requires the following:

● Forward navigation to a new page must add a browser history state.● Back navigation to a previous page must ne triggered using the browser history.

With tje jQuery plugin jQuery.sap.history.js, a new history state can be added by changing the hash of the current URL with serialized state data which is sufficient to restore the current state when doing back navigation. jQuery.sap.history.js also provides an API for navigating back one or several steps through the browser history states.

For forward navigation (also called "to" navigation) and backward navigation (also called "back" navigation), two ways of triggering exist:

● "TO" navigation

280P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 281: Hana Cloud

○ triggered by controls, for example, tapping on a button to navigate to a new page○ triggered by browser history, that is, tapping on the browser forward button

● "Back" navigation

○ triggered by controls, for example, tapping on the back button in a page's header to go back to previous page

○ triggered by browser history, that is, tapping on the browser back button or the physical back button

The image below illustrates how the four options for trigger handling:

The following sections describe the four options:

"TO" triggered by controls

When "TO" navigation is triggered by controls, a new history state needs to be added to the browser history with the new page information. Later, when doing a back navigation, a history state is popped out from browser history and we can decide which page we go back to by checking the information saved with the history state.

"TO" triggered by browser history

"TO" navigation can also be triggered by tapping on the browser forward button. We don't need to add a new history state because the history state has been added to browser history already. By checking the saved information with this history state, we know which page we go forward to.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 281

Page 282: Hana Cloud

"BACK" triggered by controls

In order to support the physical back button, we are required to do every back navigation through the browser history. Thus when back navigation is triggered by a control, we ask the browser history to go back one or several steps by calling the provided API in jQuery.sap.history.js. The following behaviors are the same as Back triggered by browser history.

"BACK" triggered by browser history

When back navigation is triggered by browser history either the browser back button or the physical back button on mobile device is tapped, a history state is popped out from browser history. By checking the saved information with history state, we can navigate to the specified page.

Advanced Support for Popups

1.3.4.3.23 Mobile Events

The following is the same for mobile events and Desktop events:

● When running on mobile or touch devices, the application has still the possibility to access to all native browser events, including the touch-related ones.

● Handling of control events fired by SAPUI5 is also the same as on desktop PCs.● When implementing SAPUI5 controls, some browser events can be handled very easily by implementing a

method named on<eventName>, so all the bind/unbind effort is avoided. This is equally possible on mobile.

Basically the whole concept of events is identical.

Additional Events for Mobile Applications

The difference between mobile and desktop events is that on mobile devices additional events are available within control implementations. They are introduced in the following sections.

Additional Mobile Browser Events

On touch-enabled platforms the following events are also provided within UI5 controls to be handled in on<eventName> methods:

282P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 283: Hana Cloud

● touchstart● touchend● touchmove● touchcancel

Additional Mobile Pseudo Events

jQuery mobile event handling is used in SAPUI5 when running on touch-enabled devices. From the basic browser events it creates semantically richer events. Some of them are also provided automatically in SAPUI5 controls:

● swipe● tap● swipeleft● swiperight● scrollstart● scrollstop

For more information, see the jQuery mobile documentation.

Simulation of touch events on non-touch platforms

For testing or demonstration purposes, the events listed above can also be simulated on non-touch devices. When this simulation is enabled, the touch events will also be triggered by mouse interaction.

NoteDue to technical constraints the simulation cannot be perfect, so it may not be used in productive code.

To enable the simulation mode, set the SAPUI5 configuration parameter xx-test-mobile to 'true', for example by appending the URL parameter sap-ui-xx-test-mobile=true.

Events also available in Desktop Apps

This section lists all events that are available in control implementations in all SAPUI5 applications:

Browser Events

● click● dblclick

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 283

Page 284: Hana Cloud

● focusin● focusout● keydown● keypress● keyup● mousedown● mouseout● mouseover● mouseup● select● selectstart● dragstart● dragenter● dragover● dragleave● dragend● drop● paste

Pseudo Events

The "pseudo events" can be used in on<eventName> methods inside controls like browser events, but are created by SAPUI5 and typically have enriched semantics:

For the detailed meaning of each event, see

● sapdown● sapdownmodifiers● sapshow● sapup● sapupmodifiers● saphide● sapleft● sapleftmodifiers● sapright● saprightmodifiers● saphome● saphomemodifiers● saptop● sapend● sapendmodifiers● sapbottom● sappageup● sappageupmodifiers

284P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 285: Hana Cloud

● sappagedown● sappagedownmodifiers● sapselect● sapselectmodifiers● sapspace● sapspacemodifiers● sapenter● sapentermodifiers● sapexpand● sapbackspace● sapbackspacemodifiers● sapdelete● sapdeletemodifiers● sapexpandmodifiers● sapcollapse● sapcollapsemodifiers● sapcollapseall● sapescape● saptabnext● saptabprevious● sapskipforward● sapskipback● sapprevious● sappreviousmodifiers● sapnext● sapnextmodifiers● sapdecrease● sapdecreasemodifiers● sapincrease● sapincreasemodifiers● sapdelayeddoubleclick

1.3.4.3.24 Styling and Theming Mobile Controls

CSS is used in mobile applications to provide the visuals of controls, just like for Desktop controls. The main differences are:

● The mobile browsers supported by SAPUI5 are all based on Webkit. This allows using advanced CSS3 features which are not available in all supported desktop browsers.

● "em" and "rem" should be used for dimensions.

Using LESS Features like Theme Parameters

When controls are created with Eclipse tool support, the CSS files are processed by the "LESS" Open Source CSS preprocessor. Just like in desktop control CSS files, LESS features, in particular variables or "theme parameters", can be used.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 285

Page 286: Hana Cloud

1.3.4.3.25 Testing the SAPUI5 Application in Eclipse

To test applications locally in Eclipse, the following two options exist:

● SAPUI5 application preview, see Test in SAPUI5 Application Preview● Java Web Server, see TEst Your SAPUI5 Application on a Java Web Server

If you have created a SAPUI5 application for a mobile target device, this application can only run in a WebKit browser. You can, however, use the mentioned options for testing your application locally in Eclipse and copy and paste the URL into a WebKit browser.

If your application has to access resources on a back-end system (OData), you must enable the back-end access for local testing. If you deploy the SAPUI5 application project on the ABAP Server, you can test the application on the ABAP Server.

Prerequisites

You have installed the SAPUI5 application development feature in your Eclipse installation.

You have created a SAPUI5 application using the SAPUI5 application development tools, see Developing Applications Using SAPUI5 Tools.

Test in SAPUI5 Application Preview

You access the SAPUI5 application preview using the Web App Preview, provided with the embedded Jetty server. You can quickly check on your application and open it in the default browser.

Prerequisites

NoteJetty provides an internal web preview used in the SAPUI5 application preview. As of the Juno release of Eclipse, this features needs to be installed explicitely.

Procedure

1. To test the new application with the application preview in an embedded Jetty server, right-click the HTML file or the project node and choose Run As Web App Preview . Everything is configured automatically.

2. To refresh after having changed a file of your SAPUI5 application, choose Refresh on the left hand side of the preview editor to refresh the SAPUI5 preview.

286P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 287: Hana Cloud

3. To check the files of your SAPUI5 application project in an external browser, choose Open in external browser on the right hand side of the preview editor. This function opens the external browser which is specified in the Eclipse preferences under General Web Browser . This is usually the default browser of your PC. For other external browsers, you can also copy the URL from the text field of the editor to the external browser.

Open in External Browser

Test Your SAPUI5 Application on a Java Web Server

Prerequisites

To test the application in a Java Web Server environment, ensure that the corresponding Server Adapter Eclipse Plugin is installed.

Procedure

To test the new application, right click the new project and choose Run As ... Run on Server . Select a server (for example, Apache Tomcat), and choose Finish.

Related LinksSet up Tomcat to test SAPUI5 applications [page 288]To test on a Java web server, you can install an Apache Tomcat.

Use a SimpleProxyServlet for Testing to Avoid Cross-domain Requests [page 288]If you are testing locally in your Java Eclipse environment and you want to access an OData service in the ABAP system, a proxy is needed to ensure the same origin policy. In an SAPUI5 application project you can use a SimpleProxyServlet for local testing.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 287

Page 288: Hana Cloud

Set up Tomcat to test SAPUI5 applicationsTo test on a Java web server, you can install an Apache Tomcat.

Prerequisites

The recommended versions of Tomcat are 6.0 or higher.

Procedure

1. Download Tomcat from the respective web site. You can either install the Windows Service Installer, or download and unzip the zip file (you can find the startup script in the bin folder).

2. To deploy your application, choose one of the following options:

○ Without EclipseTo deploy SAPUI5 on Tomcat without Eclipse, you can set up a Tomcat user with manager privileges (see the Tomcat documentation) and use the tomcat manager application for deployment. We recommend, however, to just move your war file into the webapps folder inside the tomcat directory. Tomcat takes care of the deployment, but a restart may be necessary.If you run Tomcat without Eclipse, set the environment variable JAVA_HOME to JDK6

○ In EclipseTo run web applications in Eclipse, you need to register the Tomcat web server.

1. Open the Java EE perspective in Eclipse.2. Open the Servers view, for example by choosing CTRL+3 and then entering Servers).

3. To open the New Server wizard, choose New Server from the context menu.

4. Choose Apache Tomcat 7.0 and add a new server runtime by pointing to the folder in which you have unzipped the Tomcat installation files. Finish the wizard. You should now see Tomcat v6.0 server in the Servers view.

5. Open the configuration overview by double clicking the Tomcat v6.0 server in the Servers view. Select the Serve modules without publishing server option.

Use a SimpleProxyServlet for Testing to Avoid Cross-domain RequestsIf you are testing locally in your Java Eclipse environment and you want to access an OData service in the ABAP system, a proxy is needed to ensure the same origin policy. In an SAPUI5 application project you can use a SimpleProxyServlet for local testing.

CautionBe aware that due to security reasons the SimpleProxyServlet is restricted to local testing purposes only. It can only be used for local host scenarios (accessing Gateway services to avoid cross-domain issues) and will not work when deployed on an application server. For productive use, refer to a mature proxy servlet.

NoteIf you have issues with accessing HTTPS systems via the ResourceServlet or the SimpleProxyServlet it may be necessary to import the root certificate into the Java keystore.

288P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 289: Hana Cloud

.

Ideally, all OData service URLs should be in one file to make the exchange easier - either in the index.html, or in one separate .js file which needs to be included. The application is responsible for exchanging the URLs before checking in and after checking out to SAPUI5 Repository. You can also use the helper function getServiceUrl for which also the application is responsible. See the following example:

#!java<script>//var serviceUrl = "/mypath/myservice"; //url when running on the ABAP system//var serviceUrl = "proxy/mypath/myservice"; //url when running locally in Eclipsevar serviceUrl = getServiceUrl("/mypath/myservice");function getServiceUrl(sServiceUrl) { //for local testing prefix with proxy //if you and your team use a special host name or IP like 127.0.0.1 for localhost please adapt the if statement below if (window.location.hostname == "localhost") { return "proxy" + sServiceUrl; } else { return sServiceUrl; }}</script>

As parameter for the getServiceUrl helper method, use the URL of the OData service document without {protocol}://{host name}:{port number}, for example: /mypath/myservice.

NotePlace the script tag before the script that calls the view (sap.ui.view).

Intranet Servers

The SimpleProxyServlet allows proxy requests to an arbitrary server in the intranet.

The proxy URL that is used in the coding looks like this: proxy/<service url>.

Open the web.xml file located in the <WebContent folder name>/WEB-INF folder and configure the parameter com.sap.ui5.proxy.REMOTE_LOCATION of the SimpleProxyServlet where the placeholders {protocol}, {host name}, {port number} are to be exchanged by the real protocol, host name and port number:

#!xml

<servlet> <servlet-name>SimpleProxyServlet</servlet-name> <servlet-class>com.sap.ui5.proxy.SimpleProxyServlet</servlet-class> </servlet>

<servlet-mapping> <servlet-name>SimpleProxyServlet</servlet-name> <url-pattern>/proxy/*</url-pattern> </servlet-mapping>

<context-param> <param-name>com.sap.ui5.proxy.REMOTE_LOCATION</param-name> <param-value>{protocol}://{host name}:{port number}</param-value> </context-param>

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 289

Page 290: Hana Cloud

Internet Servers

The SimpleProxyServlet can be configured for proxy requests to internet servers in the same way as for intranet servers. Additional proxy settings may be necessary.

As the SimpleProxyServlet automatically uses the proxy settings from your Eclipse this can be configured in Eclipse under Window Preferences , and select General Network Connections . Here you can specify the proxy entries and the proxy bypass.

For example, set Active Provider to Manual, Schema=HTTP, Host=proxy, Port=8080 under proxy entries and localhost, *.sap.corp as Host under proxy bypass.

Simple Proxy Servlet - Restriction Regarding DELETE Requests

The simple proxy servlet currently does not support the sending of HTTP DELETE requests with content. This is due to restrictions of the Java SE functionality that is used. If an HTTP DELETE request with content is sent, an HTTP 500 result status is sent with the description: "The HttpUrlConnection used by the SimpleProxyServlet doesn't allow to send content with the HTTP method DELETE. Due to spec having content for DELETE methods is possible but the default implementation of the HttpUrlConnection doesn't allow this!"

For practical purposes, this restriction should have only minor effects. This is because:

● When applying a REST-like programming style, an HTTP DELETE request would use the URL to transmit which objects should be deleted, but not the content.

● When building your own protocol that uses the content of the HTTP request, you typically use HTTP POST.

1.3.4.3.26 UI development toolkit for HTML5 Test Suite

The test suite is an integral part of the UI development toolkit for HTML5 (SAPUI5) core library and is, thus, automatically available for applications using SAPUI5. To start the test suite, add the URL path 'resources/testsuite' to your application URL, for instance http://localhost:8080/demokit/resources/testsuite for the 'demokit' application.

Content of the Test Suite

The test suite provides functionality related to inspecting and trying all aspects of SAPUI5 controls. It consists of the following screen areas:

● Test pages tree on the left top screen area: Different test pages for controls etc. can be selected here.● Preview area on the center top screen area: The page selected in the test pages tree is rendered here and can

be used and tested.● Control tree on the right top screen area: The hierarchy of the development toolkit controls is displayed here;

you can select controls in the tree, which will then be highlighted in the preview area.

290P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 291: Hana Cloud

● Property sheet on the right bottom screen area: Once you have selected a control in the test pages tree, its properties are displayed on the property sheet and can also be modified. Choose Apply Changes after modifying.

● Event log on the center bottom screen area: Trace output as well as all control events are displayed here.● Settings preview on the left bottom screen area: Here you can adjust how the page is rendered. You can, for

example, select one of the themes delivered with SAPUI5, or enter the name of a theme, which you created.

Using the SAPUI5 DiscoveryServlet to Automatically Find Test Cases

SAPUI5 automatically detects test cases for controls by means of the DiscoveryServlet. To use this service, the application must configure the servlet in its web.xml as follows:

#!xml<!-- ============================================================= -->

<!-- SAPUI5 discovery servlet used to find available UI test cases -->

<!-- ============================================================= -->

<servlet> <display-name>DiscoveryServlet</display-name> <servlet-name>DiscoveryServlet</servlet-name> <servlet-class>com.sap.ui5.discovery.DiscoveryServlet</servlet-class> <load-on-startup>1</load-on-startup></servlet>

<servlet-mapping> <servlet-name>DiscoveryServlet</servlet-name>

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 291

Page 292: Hana Cloud

<url-pattern>/discovery/*</url-pattern></servlet-mapping>

The servlet discovers all HTML files located inside the test-resources/<ui-library-name> folder of the web application and all resources inside the modules (JAR files) where the location is META-INF/test-resources/<ui-library-name>.

1.3.4.3.27 Localized Texts

The framework concepts for text localization in SAPUI5 are aligned with the general concepts of the Java platform. The main components of the concept are:

● Identifying languages/locales, see Identifying the Language Code/Locale● Storing and accessing texts in multiple languages (resource bundles), see Resource Bundles● Using localized texts in the application, see Use of Localized Texts in Applications

Identifying the Language Code / Locale

For the identification of languages, the framework uses a language code of type string. Currently, SAPUI5 accepts the following two syntax forms:

● The Java Locale syntax that combines a lower case ISO 639 alpha-2 or alpha-3 language code with an ISO 3166 alpha-2 country code. Both codes are combined with an underscore. An arbitrary sequence of variant identifiers (also separated by underscores) can be appended as a third component.Example: en_US, zh_TN_Traditional

● Language codes according to the defacto standard BCP 47 (see IETF BCP-47). Most modern browsers use these codes for language identification. As of JDK 1.7 the Java locale class supports them as well.Example: bs-Cyrl-BA, i-klingon

Current Language Code / Locale

SAPUI5 has the notion of a current language. It is determined from the following sources of information. The sources are ordered increasingly by priority and the last available user language/locale wins:

1. Hard-coded UI5 default locale ('en')2. Potentially configured user language (window.navigator.userLanguage)3. Potentially configured browser language (window.navigator.browserLanguage)4. General language information from the browser (window.navigator.language)5. Locale configured in the application coding (jsdoc:symbols/sap.ui.core.Configuration)6. Locale configured via URL parameters

You use the configuration API to retrieve the resulting current language as follows:

var sCurrentLocale = sap.ui.getCore().getConfiguration().getLanguage();

292P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 293: Hana Cloud

NoteThe syntax of the returned value depends on the syntax used for configuration. If the information source is one of the browser language properties, the returned language most likely is in BCP-47 format. If it is configured as a URL parameter, the user might have choosen the JDK Locale syntax.

NoteIn the Internet Explorer (IE), none of the window.navigator.* properties reflects the settings of the Language Preference dialog in IE. Instead, IE returns the language of the OS installation as browserLanguage and the language from the OS regional settings as userLanguage. As a result, the settings in the Language Preference dialog cannot be taken into account for the current language of SAPUI5. This is often confusing for developers and a known shortcoming in IE. The only way to circumvent this is an additional server request where IE provides the corresponding setting in theAccept-Language header. As this technique requires a backend component and SAPUI5 must be able to run without any server component, such a request is not implemented yet.

Resource Bundles

Resource bundles are a collection of *.properties files. All files are named with the same base name (prefix identifying the resource bundle), an optional suffix that identifies the language contained in each file, and the fixed .properties extension. The language suffixes are formed according to the older JDK locale syntax. By convention, a file without a language suffix should exist and contain the raw untranslated texts in the developer's language. This file is used if no more suitable language can be found.

A resource bundle file is a Java properties file (as described in the Javadoc of class java.util.Properties). It contains key/value pairs where the values are the language-dependent texts and the keys are language independent and used by the application to identify and access the corresponding values.

When a localized text is needed, the application uses the SAPUI5 APIs to load the properties file that matches the current language best. The same applies to any other localized data that can be represented as a string, for example, a date formatter string. To retrieve a text from the properties file, the application uses the (language-independent) key. If no text can be found for this key, the next best matching file is loaded and checked for the text. Finally, if no file matches, the raw file is loaded and checked.

The resource bundle sap.ui.commons.message_bundle consists of the following individual files:

● sap.ui.commons.message_bundle.properties: Contains the raw texts form the developer, determines the set of keys

● sap.ui.commons.message_bundle_en.properties: Contains English texts (without a specifc country)● sap.ui.commons.message_bundle_en_US.properties: Contains texts in American English● sap.ui.commons.message_bundle_en_UK.properties: Contains texts in British English

Use of Localized Texts in Applications

SAPUI5 provides the following options to use localized texts in applications:

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 293

Page 294: Hana Cloud

● Using the jQuery.sap.resources module● Using data binding

Using jQuery.sap.resources

You can use the JavaScript module jQuery.sap.resources to access localized texts. The module contains APIs to load a resource bundle file from a given URL and for a given locale.

To make sure that the jQuery.sap.resources module is loaded, you have to require it as follows:

jQuery.sap.require("jquery.sap.resources");

You can then use the jQuery.sap.resources function to load the resource bundle from the given URL, that is, the bundle name, and for a given locale. When no locale is specified, a default locale (en) is used. The following code snippet shows the use of the jQuery.sap.resources function to return a jQuery.sap.util.ResourceBundle:

var oBundle = jQuery.sap.resources({url : sUrl, locale: sLocale});

For more information, see jQuery.sap.resources in the API Reference.

The resource bundle jQuery.sap.util.ResourceBundle provides access to the localized texts that are contained in the resource bundle. You can use the getText method to access the texts in the loaded bundle by means of their key. This is shown in the following code snippet:

var sText = oBundle.getText(sKey);

Localization Test Page

The test suite provides a test page that shows how to use localized texts. This section only provides a short overview how the jQuery.sap.resources module is used there.

For a localized Web page you need the .html page itself and the .properties files of the required languages, in this example English and German.

The resource bundle i18n.properties is the English fallback version, which is the default version.

welcome=Welcome {0}. Please enter a new contact:lastname=Last Name:firstname=First Name:street=Street:zip=ZIP:city=City:

The resource bundle i18n_de.properties contains the texts in German. The following code snippet shows the content of this file:

welcome=Willkommen {0}. Bitte geben Sie einen neuen Kontakt ein:lastname=Nachname:firstname=Vorname:

294P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 295: Hana Cloud

street=Straße:zip=PLZ:city=Ort:

The localization test page uses these texts to display a welcome message and a form to enter the address of a person. The coding of the test page looks as follows:

01: jQuery.sap.require("jquery.sap.resources");

02:

03: var sLocale = sap.ui.getCore().getConfiguration().getLanguage();

04: var oBundle = jQuery.sap.resources({url : "res/i18n.properties", locale: sLocale});

05:

06: var oMatrixLayout = new sap.ui.commons.layout.MatrixLayout();

07: oMatrixLayout.setLayoutFixed(false);

08: oMatrixLayout.createRow(

09: new sap.ui.commons.TextView({text: oBundle.getText("welcome", ["Administrator"])})

10: );

11: oMatrixLayout.getRows()[0].getCells()[0].setColSpan(2);

12: oMatrixLayout.createRow(

13: new sap.ui.commons.Label({text: oBundle.getText("lastname")}),

14: new sap.ui.commons.TextField()

15: );

16: oMatrixLayout.createRow(

17: new sap.ui.commons.Label({text: oBundle.getText("firstname")}),

18: new sap.ui.commons.TextField()

19: );

20: oMatrixLayout.createRow(

21: new sap.ui.commons.Label({text: oBundle.getText("street")}),

22: new sap.ui.commons.TextField()

23: );

24: oMatrixLayout.createRow(

25: new sap.ui.commons.Label({text: oBundle.getText("zip")}),

26: new sap.ui.commons.TextField()

27: );

28: oMatrixLayout.createRow(

29: new sap.ui.commons.Label({text: oBundle.getText("city")}),

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 295

Page 296: Hana Cloud

30: new sap.ui.commons.TextField()

31: );

32: oMatrixLayout.placeAt("userForm");

With regard to localization, the code above defines the following procedure:

1. Require the jQuery.sap.resources module (!Line: 01)2. Determine the language (!Line: 03)3. Load the resource bundle (!Line: 04)4. Access the text using the welcome key and pass the value for the placeholder ({0}) via an array (!Line: 09)5. Access the text using the lastname key and set it as text for the Label (!Line: 13)

Data Binding

You can also use data binding to access localized texts. The ResourceModel is a wrapper for resource bundles that exposes the localized texts as a model for data binding. You use the ResourceModel to bind texts for control properties to language dependent resource bundle properties. You can instantiate the ResourceModel either with bundleName (name of a resource bundle that equals a SAPUI5 module name within the require/declare concept), or a bundleUrl, which points to a resource bundle. When you use the bundle name, make sure that the file has a .properties suffix. If no locale is defined, the current language is used.

var oModel = new sap.ui.model.resource.ResourceModel({bundleName:"myBundle",bundleLocale:"en"});

var oControl = new sap.ui.commons.Button( { id : "myButton", text : "{i18n>MY_BUTTON_TEXT}"});// attach the resource model with the symbolic name "i18n"oControl.setModel(oModel, "i18n");

NoteThe current data binding implementation does not allow to pass parameters to your texts in the resource bundle. If you have to pass parameters, you must do this on your own. You can, however, access the resource bundle directly from the model instead of loading it:

var myBundle = oModel.getResourceBundle()

After the instance has been created, you have a model containing the resource bundle texts as data.

For a complete overview of available methods and parameters, see the API Reference.

1.3.4.4 References

296P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 297: Hana Cloud

1.3.4.4.1 Compatibility Rules

SAPUI5 plans to be a so-called Release Independent Component (RIC). An important constraint for this is that it must be as simple as possible to upgrade to a newer version. This makes compatibility rules so important.

The following sections explain the meaning of compatibility with regard to the SAPUI5 application and control development.

Versioning Scheme

SAPUI5 uses a 3 digit version identifier, for example 1.4.3. The digits have the following meaning:

● The first digit (1) specifies the major version number.● The second digit (4) specifies the minor version number.● The third digit (3) specifies the patch version number.

New releases of SAPUI5 are described by the major and minor version number. The patch version number is only used to identify patches within a release.

API Evolution

If not mentioned differently, in the following paragraphs "API" refers to "public API", meaning functions, classes, namespaces, controls with their declared properties, aggregrations, and so on. The sole definition of the public API is the SAPUI5 Library - Core & Standard Controls (API Reference Documentation, JSDoc), which is available in the Demo Kit. Features that are not mentioned in the SAPUI5 library are not part of the API.

The following rules apply for introducing new APIs or making incompatible changes to existing APIs:

A major release, that is, a release with a new major version can introduce new APIs or make incompatible changes to existing APIs. If this is the case, the incompatibilities are described in the Release Notes.

A minor release, that is, a release with a new minor version can introduce new APIs, but does not contain incompatible changes to APIs, which have been introduced in the same major release.

A patch release, that is, a release with a new patch version, only contain fixes to the existing implementation, but do not introduce new features or incompatible API changes.

NoteExceptions to these rules are possible, but only in very urgent cases, such as security issues. The exceptions are documented in the Release Notes.

Compatible Changes

The following changes to existing APIs are compatible changes:

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 297

Page 298: Hana Cloud

● Adding new libraries, controls, classes, properties, functions, namespaces to the API● Generalizing properties, that is, moving properties up in the inheritance hierarchy● Changing the logging behavior, that is, adding or removing log output, modifying the content of existing log

output; logging is not part of the API● Adding new values to enumeration types; this means that when dealing with enum properties, always be

prepared to accept new values, for example, by implementing a "default" or "otherwise" path when reacing on enum values

● Modifications to the markup or style (HTML, CSS) of controls

Incompatible Changes

The following changes to existing APIs are incompatible and are only implemented in major releases:

● Removing an API (library, namespace, function, property, control, events, and so on)● Renaming an API (library, namespace, function, property, control, events, and so on)● Removing support for parameters● Removing support for configuration entries● Reducing the visibility of an API; this does not break JavaScript applications, but changes the contract● Removing or reordering parameters in an API signature● Reducing the accepted value range, for example, parameter of a function● Broadening the value range of a return value (or property); exception: Enumerations● Moving JavaScript artifacts (namespaces, functions, classes) between modules● Replacing asserts by precondition checks● Moving properties, etc., down in the inheritance hierarchy● Changing the name of enum values● Changing defaults (properties, function parameters)● Renaming or removing files

If possible, SAPUI5 marks old artifacts as deprecated and creates new artifacts, if applicable, instead of incompatible changes. A deprecation documentation in the SAPUI5 library and maybe a log entry in the implementation explain why and when an artifact has been deprecated and provide hints how to achieve the same results without deprecated functionality.

CautionSome of the new functionality or controls are in an experimental development state and documented as such. These features are still under development and changes to their API are very likely; inthese cases, even incompatible changes in minor releases may occur. They are included in public releases to collect feedback from early adopters. Consumers of such APIs must understand that their respective code might be broken (repeatedly) when upgrading to new SAPUI5 releases and they must be willing to adapt to such changes.

298P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 299: Hana Cloud

Third Party Open Source Libraries

SAPUI5 contains and uses several third party open source libraries, for example, jQuery. These libraries can also be used by applications and/or custom control libraries, but the SAPUI5 compatibility policy described within this document does not apply to these third party libraries.

If you want ro use the contained third party open source libraries, note the following restrictions:

● SAP decides which version(s) and modules of the used libraries are provided.● SAP can upgrade to higher version(s) of the used libraries even within a micro release.● For important reasons such as security SAPUI5 can stop providing a library.● The third party libraries are provided "as is". Extensions, adaptations, and support are not done by SAP.

NoteFor closed source libraries, a use beyond the use of the corresponding SAPUI5 controls is not allowed.

Exceptions: Important to Know

Not part of the public API are all functions, and so on, which are not declared as public in the SAPUI5 library. Also not part of the API is the rendered HTML and the CSS of the controls. This means in particular that the below mentioned scenarios can cause problems, also when switching minor or micro versions. The support for these problems provided by SAP can only be limited, and an adaptation of non-SAPUI5 coding may be necessary. JavaScript facilitates the modification of code that belongs to someone else, for example, enriching prototypes of foreign classes, adding properties or functions to existing objects. This should not be forbidden, but the consequences, meaning the risk of conflicts when SAPUI5 is enhanced, must be clear.

Scenarios:

● Manipulation of HTML/CSS, for example via jQuery, control.addStyleClass, or directly via CSS● Using or overriding non-public functions, etc.● Creation of new controls, for example "Notepad-Controls" based on existing controls (inheritance) or

subclassing in general; new classes also depend on private functionality of the super classes, collision of generated functions for properties, aggregations are possible

● Pixel-perfect compatibility is not guaranteed for SAPUI5 owned controls and, thus, also not guaranteed for controls inheriting from SAPUI5 controls.

1.3.4.4.2 Naming Conventions for Control and Application Development

The following sections introduce the naming conventions for control and application development for SAPUI5.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 299

Page 300: Hana Cloud

Naming Conventions for Control Artifacts

We recommend to use following naming conventions for control artifacts:

● Start control names with an upper case letter and use camel case for concatenated words, for example MatrixLayout.

● Start control property names with a lower case letter and use camel case for concatenated words, for example colSpan.

● Start control event names with a lower case letter and use camel case for concatenated words, for example: press.

● Start control method names with a lower case letter and use camel case for concatenated words, for example doSometing.

● Start control aggregation names with a lower case letter and use camel case for concatenated words.● Start control association names with a lower case letter and use camel case for concatenated words.● For control, property, event, and relation names use unique names to avoid name clashes in generated

classes.● Start parameters of control events with a lower case letter.

NoteSAPUI5 tools check and enforce some of these rules.

The generated setter/getter methods for properties as well as the generated methods for events for the aggregations and associations use camel case notation, for example attach<EventName>.

SAPUI5 controls have constructors, which accept a set of properties and events as JSON string. The framework expects that the names used as keys in a JSON string exactly match the case of the defined control properties and events.

If SAPUI5 controls are exposed as tags, the tag name and its attributes should fit the following naming conventions:

● Start tag names with a lower case letter and use camel case for concatenated words. Except for the lower case of the first character, tag names should match the name of the control to create a relation between the tag and the respective control, for example matrixLayout.

● Start tag attributes with a lower case letter and use camel case for concatenated words, for example colSpan● Name tag attributes for event handlers in lower case letters as follows: on<event-name>; for example onpress

Reserved Characters for Control IDs

The SAPUI5 framework regards the dash '-' as a forbidden character for control IDs. Applications must not use this character in their control IDs.

Control renderers, however, should use the dash to derive synthetic IDs from control IdDs, for example, by appending a suffix like "-mysuffix" to the control ID. By this, naming conflicts with the application can be avoided.

300P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 301: Hana Cloud

Character Description

- Reserved for separators for synthetic IDs

Reserved IDs for DOM Nodes and Elements

The following table contains a list of IDs reserved for SAPUI5 core.

ID Description

sap-ui-bootstrap ID of the bootstrap script tag

sap.ui.core-script ID of the bootstrap script tag (deprecated)

sap-ui-* Prefix of the IDs created SAPUI5-internal

*-r Suffix for former UR LightSpeed root areas (similar to UIArea of SAPUI5)

The following table contains a list of IDs currently used in the sap-ui- namespace.

ID Description

sap-ui-library-* Prefix for UI libraries script tags

sap-ui-theme-* Prefix for theme stylesheets link tags

sap-ui-highlightrect ID of the highlight rect for controls in TestSuite

sap-ui-blindlayer-* ID for BlockLayer

sap-ui-static ID of the static area of SAPUI5

sap-ui-TraceWindowRoot ID of the TraceWindowRoot

sap-ui-xmldata ID of the XML Data Island

Reserved DOM Attributes

The following table contains a list of reserved DOM element attributes names.

Attribute Description

data-sap-ui-* Namespace for custom attributes of SAPUI5

NoteIn general, all custom attibutes should be prefixed with data-.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 301

Page 302: Hana Cloud

Reserved URL Parameters

The following table contains a list of reserved URL parameter names that should be avoided by applications, meaning that an application can use these parameters, but should not introduce its own parameters with these names.

Attribute Description

sap-* Namespace for URL parameters introduced by SAP AG

sap-ui-* Namespace for URL parameters introduced by SAPUI5

Control CSS

To avoid collisions, all CSS classes written to the HTML must start with "sap" if developed inside SAP, and with "sapUi" or "sapM" if developed within the SAPUI5 development teams. Outside the respective groups these prefixes should not be used.

For CSS classes for a specific control, add the control name or an abbreviation of the control name to the above mentioned prefix. For controls outside the commons library you may also add the library name between the prefix and the control name, especially if developed outside the core UI5 development teams.

The HTML root element of controls should contain the CSS class name, and all inner HTML elements requiring a class name should use this class name and add a suffix.

All CSS selectors written by SAPUI5 control developers must refer to at least one CSS class. Pure HTML elements should not be styled to avoid affecting non-owned HTML.

Inline CSS should only be used for control instance specific style, such as the button width.

Styling Contexts

If the visuals of controls are different depending on the context or container in which they are used we recommend to use CSS cascades:

● The area or container writes a marker CSS class to the HTML and documents this CSS class in its JSDoc. The documentation should mention the purpose and contract or meaning of this class, for example, that it modifys the appearance of children in a way that better fits table cells, toolbars, or headers.

● The CSS class may have no CSS styles attached. It is a pure marker. This is because such styles would also need to stay stable and might cause trouble for other containers where these styles are not desired.

● The naming convention for these classes is as follows: Suffix -CTX, for example, sapUiTable-CTX or sapMList-CTX or sapUiBorderless-CTX. This makes them easily discernible from "normal" CSS class names.

● Controls that are used to modify their appearance in such an area shall have CSS where this marker class is used in a cascade and provides the suitable style, for example, .sapUiTable-CTX .myCompanyInputField { border: none; }.

302P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 303: Hana Cloud

1.3.5 Consuming the Connectivity Service

Overview

In this section, you will learn how to use SAP HANA Cloud connectivity service to connect Web applications to Internet, make on-demand to on-premise connections to Java and ABAP on-premise systems and configure destinations to send and fetch e-mail. To do all these tasks, you need to create and configure destinations, according to the relevant protocol type. For more information, see: Using Destinations [page 304]

To learn more how to configure a destination from a particular type, see:

● HTTP Destinations [page 343]● RFC Destinations [page 374]● Mail Destinations [page 392]

Who Can Use It

The following user groups are involved in the end-to-end use of SAP HANA Cloud connectivity service:

● Application developers - develop the SAP HANA Cloud application. They create a connectivity-enabled application by using SAP HANA Cloud connectivity API.

● Application operators - access SAP HANA Cloud Cockpit and are responsible for productive deployment and operation of an application. They are also responsible for configuring the remote connections that an application might need.

● IT administrators - set up the connectivity to SAP HANA Cloud in the customer's on-premise network, using the SAP HANA Cloud connector.

Scenarios

● Making Internet connections between Web applications and external servers via HTTP protocol: Tutorial: Using Internet Services in Cloud Applications [page 358]

● Making connections between Web applications and on-premise backend services via HTTP protocol: Tutorial: Using On-Premise Back-End Services in Cloud Applications [page 364]

● Making connections between Web applications and on-premise backend services via RFC protocol: Tutorial: Invoking ABAP Function Modules in On-Premise ABAP Systems [page 384]

● Establishing connections from on-premise systems to SAP HANA Cloud, using SAP HANA Cloud Connector: Using the Cloud Connector [page 319]

● Sending and fetching e-mail via mail protocols: Sending and Fetching E-Mail [page 391]

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 303

Page 304: Hana Cloud

Troubleshooting

If you encounter connectivity problems, you can check the available solutions related to general connectivity issues or specific on-demand to on-premise cases.

For more information, see Connectivity Troubleshooting Guide [page 402].

Related LinksProduct Restrictions [page 20]Connectivity Service [page 10]

1.3.5.1 Using Destinations

Overview

Connectivity destinations are part of SAP HANA Cloud connectivity service and are used for the outbound communication of an SAP HANA Cloud application to a remote system. They contain the connection details for the remote communication of an application. Connectivity destinations are represented by symbolic names that are used by on-demand applications to refer to remote connections. The connectivity service resolves the destination at runtime based on the symbolic name provided. The result is an object that contains customer-specific configuration details, such as the URL of the remote system or service, the authentication type, and the relative credentials.

The currently supported destination types are HTTP, Mail and RFC.

● HTTP destination - provides data communication via HTTP protocol and is used for both Internet and on-premise connections..

● Mail destination - specifies an e-mail provider for sending and retrieving e-mails via SMTP, IMAP and POP3 protocols.

● RFC destination - makes connections to ABAP on-premise systems via RFC protocol using JCo as API.

HTTP Connectivity Destinations Configuration Level

Destinations can be simultaneously configured on three levels: application, account and subscription. This means it is possible to have one and the same destination on all configuration levels.

● Application level - The destination is related to an application, that is, independent from the account in which the application is running.

● Consumer account level - The destination is related to an account.● Subscription level - The destination is related to a pair <<Application, Account>>.

The runtime tries to resolve a destination in the following order: Subscription level → Consumer account level → Application level.

304P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 305: Hana Cloud

Connectivity Destinations Configuration Cache

● Destination configuration files and Java keystore (JKS) files are cached at runtime. The cache expiration time is set to a small time interval (currently around 4 minutes). This means that once you update an existing destination configuration or a JKS file, the application needs about 4 minutes until the new destination configuration is applied. To avoid this waiting time, the application can be restarted on the cloud; following the restart, the new destination configuration takes effect immediately.

● When you configure a destination for the first time, it takes effect immediately.● If you change a mail destination, the application needs to be restarted before the new configuration becomes

effective.

How to Configure Destinations

To configure and then use a destination to remotely connect your Java EE or on-demand application, you can use either of the following methods:

● Configuring Destinations from the Eclipse IDE [page 307]● Configuring Destinations from the Console Client [page 315]

Related Information

You can see examples in the SDK package that you previously downloaded from http://tools.hana.ondemand.com.

Open the SDK location and go to /tools/samples/connectivity. This folder contains a standard template.properties file, weather destination, and weather.destinations.properties file, which provides all the necessary properties for uploading the weather destination.

1.3.5.1.1 Destination API

What are destinations and when do I need them?

Destinations are part of SAP HANA Cloud connectivity service and are used for the outbound communication of an SAP HANA Cloud application to a remote system. They contain the connection details for the remote communication of an application, which can be configured for each customer to accommodate the specific customer back-end systems and authentication requirements.

From an application developer's perspective, a destination is defined by a symbolic name that is used in the application coding to refer to the destination. At runtime, the symbolic name is then resolved by SAP HANA Cloud

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 305

Page 306: Hana Cloud

connectivity service against the bound destination configuration, which consists of the URL to the target system and some information about the authentication type. For more information, see Using Destinations [page 304].

Destinations should be used by application developers when they aim to provide applications that:

● Integrate with remote services or back-end systems that need to be configured by customers● Integrate with remote services or back-end systems that are located in a fenced environment (that is, behind

firewalls and not publicly accessible)

For more information about configuring destinations, see:

Configuring Destinations from the Eclipse IDE [page 307]

Configuring Destinations from the Console Client [page 315]

Destination Consumption Using a Direct Destination JNDI Lookup

All connectivity API packages are visible by default from all Web applications. Aplications can consume the destinations via a JNDI lookup.

1. To consume destinations using JNDI, you need to define your destination as a resource in the web.xml file. An example of a destination resource named myBackend, which is described in the web.xml file, is as follows:

<resource-ref> <res-ref-name>myBackend</res-ref-name> <res-type>com.sap.core.connectivity.api.http.HttpDestination</res-type></resource-ref>

2. In your servlet code, you can look up the destination (a HTTP destination in this example) from the JNDI registry as following:

import javax.naming.Context;import javax.naming.InitialContext;import com.sap.core.connectivity.api.http.HttpDestination;...

// coding to lookup the destination "myBackend"Context ctx = new InitialContext();HttpDestination destination = (HttpDestination) ctx.lookup("java:comp/env/myBackend");

NoteIf you want the lookup name to differ from the destination name, you can specify the lookup name in <<res-ref-name>> and the destination name in <<mapped-name>>, as shown in the example:

<resource-ref> <res-ref-name>myLookupName</res-ref-name> <res-type>com.sap.core.connectivity.api.http.HttpDestination</res-type> <mapped-name>myBackend</mapped-name></resource-ref>

306P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 307: Hana Cloud

3. With the retrieved HTTP destination, you can then, for example, send a simple <GET> request to the configured remote system by using the following code:

import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.HttpResponse;...

// coding to call service "myService" on the system configured in the given destinationHttpClient createHttpClient = destination.createHttpClient();HttpGet get = new HttpGet("myService"); HttpResponse resp = createHttpClient.execute(get);

NoteIf you want to use <<res-ref-name>>, which contains "/", the name after the last "/" should be the same as the destination name.

For example, you can use <res-ref-name>connectivity/myBackend</res-ref-name>. In this case, you should use java:comp/env/connectivity/myBackend as a lookup string.

If you want to get the URL of your configured destination, use the URI getURI() method. This method returns the URL defined in the destination configuration converted to URI.

Related LinksHTTP Destination API [page 351]

1.3.5.1.2 Configuring Destinations from the Eclipse IDE

Overview

You can use the Connectivity editor in the Eclipse IDE to configure HTTP, Mail and RFC destinations in order to:

● Connect your Web application to the Internet or make it consume an on-premise backend system via HTTP(S);

● Send an e-mail from a simple Web application using an e-mail provider that is accessible on the Internet;● Make your Web application invoke a function module in an on-premise ABAP system via RFC.

Prerequisites

● You have downloaded and set up your Eclipse IDE. For more information, see Setting Up the Tools and SDK [page 27] or Updating the Tools and SDK [page 34].

● You have created a Java EE application. For more information, see Creating a HelloWorld Application [page 36] or Using Java EE 6 Web Profile [page 65].

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 307

Page 308: Hana Cloud

Configuration on SAP HANA Cloud Local Runtime

1. In the context menu of the Servers view, choose New Server .2. Choose SAP HANA Cloud local runtime as the type of server you want to create and then choose Finish.3. A new server <SAP HANA Cloud local runtime [Stopped]> appears on the Servers view.

Also, a Servers folder is created and appears in the navigation tree of the Eclipse IDE. It contains configurable folders and files you can use, for example, to change your HTTP or JMX port.

4. On the Servers view, double-click the added server to open the editor.5. Go to the Connectivity tab view.

a. In the All Destinations section, choose the button to create a new destination.b. From the dialog window, enter a name for your destination, select its type and the choose OK. The

currently supported destination types are HTTP and Mail.c. In the URL field, enter the URL of the target service to which the destination should refer.d. In the Authentication dropdown box, choose the authentication type required by the target service to

authenticate the calls.If the target service does not require authentication, use NoAuthentication. Otherwise, use the BasicAuthentication option for which you need to enter a user name and password accepted by the target service.

e. Optional: In the Properties or Additional Properties section, choose the button to specify additional destination properties.For more information about the available destination properties, see Using Destinations [page 304].

f. Save the editor.

g. To delete a destination, choose the button.6. When new destinations are created, the changes take effect immediately.

Configuration on SAP HANA Cloud

1. In the context menu of the Servers tab, choose New Server .2. Choose SAP HANA Cloud as the type of server you want to create, choose Next, and then Finish.3. A new server <<application>.<account> [Stopped]> appears on the Servers view.4. Double-click the added server to open the server editor.5. Go to the Connectivity tab view.

a. In the All Destinations section, choose the button to create a new destination.b. From the dialog window, enter a name for your destination, select its type and the choose OK. The

currently supported destination types are HTTP and Mail.c. In the URL field, enter the URL of the target service to which the destination should refer.d. In the Authentication dropdown box, choose the authentication type required by the target service to

authenticate the calls.If the target service does not require authentication, use NoAuthentication. Otherwise, use the BasicAuthentication option for which you need to enter a user name and password accepted by the target service.

308P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 309: Hana Cloud

e. In the Proxy Type dropdown box, choose the required type of proxy connection.

NoteThis dropdown box allows you to choose the type of your proxy and is only available when deploying on SAP HANA Cloud. The default value is Internet. In this case, the destination uses the HTTP proxy for the outbound communication with the Internet. For consumption of an on-premise target service, choose the OnPremise option so that the proxy to the SSL tunnel is chosen and the tunnel is established to the connected SAP HANA Cloud connector.

f. Optional: In the Properties or Additional Properties section, choose the button to specify additional destination properties.For more information about the available destination properties, see Using Destinations [page 304].

g. Save the editor. This saves the specified destination configuration in SAP HANA Cloud.

h. To delete a destination, choose the button.6. When new destinations are created, the changes take effect immediately. Since destination configurations

are currently cached with a cache expiration of around 4 minutes, changes in the configuration might not take immediate effect. Changes in destination configurations also take immediate effect when the related Web application is restarted in SAP HANA Cloud.

Example of HTTP Destination

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 309

Page 310: Hana Cloud

Example of Mail Destination

310P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 311: Hana Cloud

Example of RFC Destination

Related LinksTutorial: Using Internet Services in Cloud Applications [page 358]Tutorial: Using On-Premise Back-End Services in Cloud Applications [page 364]Tutorial: Sending E-Mails [page 396]Tutorial: Invoking ABAP Function Modules in On-Premise ABAP Systems [page 384]

1.3.5.1.3 Configuring Destinations from the Cockpit

Overview

Use the Destinations editor in SAP HANA Cloud cockpit to configure HTTP, Mail and RFC destinations in order to:

● Connect your Web application to the Internet or make it consume an on-premise back-end system via HTTP(S)

● Send an e-mail from a simple Web application using an e-mail provider that is accessible on the Internet.● Make your Web application invoke a function module in an on-premise ABAP system via RFC.

You can create, delete and modify destinations as well as import destinations from existing files.

Note

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 311

Page 312: Hana Cloud

You can use this editor to create and edit destinations on application level only.

Prerequisites

So that the Destinations editor is active for your account, you need to have at least one application deployed.

Accessing the Destination Editor

1. In a Web browser, enter one of the following URLs, depending on your account type:

○ Customer and partner accounts: https://account.hana.ondemand.com/cockpit○ Developer accounts: https://account.hanatrial.ondemand.com/cockpit

2. Log in with your SAP HANA Cloud user and password.3. From the Account dropdown menu, choose your account.4. The Applications page is opened by default.5. Choose the application for which you need to create a destination.6. From the left-side panel, choose Destinations.

Creating Destinations

1. To create a new destination, choose New Destination Create New .2. Enter a destination name. The Description field is optional.3. Select destination type from the Type dropdown menu.4. Specify the destination URL.5. Select the proxy type.6. Select the relevant authentication type.7. Optional: You can enter additional properties.

a. In the Additional Properties panel, choose New Property.b. Enter a key (name) and a value for the property. You can add as many properties as you need.

c. To delete a property, choose the button next to it.8. Choose the Save button.

Importing Destinations

1. Choose New Destination Import from File .2. Browse to a configuration file that contains destination configuration.

312P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 313: Hana Cloud

3. If the file content is valid configuration data, it is displayed in the Destinations editor.A Success message confirms that the destination is saved.

Editing and Deleting Destinations

1. To edit a created/imported destination, choose the Edit button.2. You can edit the main parameters as well as the additional properties of a destination.3. Choose the Save button.4. If you want to remove an existing destination, choose the Delete button.

Example of HTTP Destination

Example of Mail Destination

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 313

Page 314: Hana Cloud

314P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 315: Hana Cloud

Example of RFC Destination

Related LinksTutorial: Using Internet Services in Cloud Applications [page 358]Tutorial: Using On-Premise Back-End Services in Cloud Applications [page 364]Tutorial: Sending E-Mails [page 396]Tutorial: Invoking ABAP Function Modules in On-Premise ABAP Systems [page 384]

1.3.5.1.4 Configuring Destinations from the Console Client

Overview

As an application operator, you can configure your application using SAP HANA Cloud console client. You can configure HTTP, Mail or RFC destinations using a standard properties file.

The examples below demonstrate how to upload, download, and delete connectivity destinations. You can perform these operations for destinations related to:

● An account - you only need to specify the account;● An application - you need to specify the account and the application;

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 315

Page 316: Hana Cloud

● A subscribed application provided by another account - you need to specify the provider account and provider application.

To use an application from another account, you must be subscribed to this application through your account.

To configure a destination for a subscribed application, you need to add the following two extra parameters:

● provider-account - denotes the account of the application that will use the destination.● provider-application - denotes the name of the application from the provider account that is able to use the

destination.

NoteMail destinations work on application level only, that is, they do not support provider-account and provider-application.

HTTP Destination Properties Files

● Name - the name of the destination.● URL - the URL of the remote system or service.● Authentication - the type of authentication against the remote system or service.

The number of mandatory property keys varies depending of the authentication type you choose. For more information about the authentication types, see Using Destinations [page 304].

If data is specified incorrectly or mandatory fields are missing, you are prompted accordingly by SAP HANA Cloud console client.

Key stores and trust stores must be stored in JKS files with a standard .jks extension.

Mail Destination Properties Files

● Name - the name of the destination.● Type - must be "MAIL" for mail destinations.● mail.* - javax.mail properties for configuring the mail session.

All properties except Name and Type must start with "mail." and must be part of the JavaMail API. For more information about mail destination properties files, see Mail Destinations [page 392].

If mandatory fields are missing or data is specified incorrectly, you will be prompted accordingly by SAP HANA Cloud console client.

316P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 317: Hana Cloud

RFC Destination Properties Files

● Name - the name of the destination.● Type - must be "RFC" for RFC destinations.● jco.client* - JCo properties for configuring an RFC connection.● jco.destination* - JCo properties for configuring the behavior of a JCo destination.

All properties except Name and Type must start with "jco.client." or "jco.destination". For more information about RFC destination properties files, see RFC Destinations [page 374].

If mandatory fields are missing or data is specified incorrectly, you will be prompted accordingly by the SAP HANA Cloud console client.

Prerequisites

● You have to download and set up the console client. For more information, see Setting Up SAP HANA Cloud Console Client [page 32].

● For more information about all connectivity service restrictions, see Product Restrictions [page 20] → section "SAP Hana Cloud Connectivity Service".

Procedure

1. Open the command prompt.2. Navigate to the tools folder of the SDK location.3. Enter neo help to display all the commands of the console client tool or neo help <command_name> to

display the help information for a command.

The examples below demonstrate how to upload, download, and delete HTTP connectivity destinations.

NoteBear in mind that, by default, your destinations are configured on SAP HANA Cloud, that is the hana.ondemand.com landscape. If you need to specify a particular landscape host, you need to add the --host parameter, as shown in the examples. Otherwise, you can skip this parameter.

Uploading Destination Configuration Properties Files and JKS Files

Enter the following command line:

neo put-destination --account <account_name> --user <user_name> --application <application_name> --localpath <destination_file_or_JKS_file_localpath> --host <landscape_host>

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 317

Page 318: Hana Cloud

Example

neo put-destination --account myaccount --user s1234567 --localpath C:\myfiles\myconfiguration.jks --host hanatrial.ondemand.com

neo put-destination --account myaccount --user s1234567 --application demo --localpath C:\SDK\tools\samples\connectivity\weather --host hanatrial.ondemand.com

neo put-destination --account myaccount --user s1234567 --provider-account otheraccount --provider-application remotedemo--localpath C:\SDK\tools\samples\connectivity\weather --host hanatrial.ondemand.com

Downloading Destination Configuration Properties Files and JKS Files

Enter the following command line:

neo get-destination --account <account_name> --user <user_name> --application <application_name> --name <configuration_name> --localpath <localpath_to_destination_or_JKS_file_to_download> --host <landscape_host>

Example

neo get-destination --account myaccount --user s1234567 --name weather --localpath C:\myfiles --host hanatrial.ondemand.com

neo get-destination --account myaccount -user s1234567 --application demo --name myconfiguration.jks --localpath C:\SDK\tools\samples\connectivity --host hanatrial.ondemand.com

neo get-destination --account myaccount --user s1234567 --provider-account otheraccount --provider-application remotedemo --name weather --localpath C:\SDK\tools\samples\connectivity --host hanatrial.ondemand.com

Deleting Destination Configuration Properties Files and JKS Files

Enter the following command line:

neo delete-destination --account <account_name> --user <user_name> --application <application_name> --name <destination_name_or_JKS_file> --host <landscape_host>

318P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 319: Hana Cloud

Example

neo delete-destination --account myaccount --user s1234567 --name myconfiguration.jks --host hanatrial.ondemand.com

neo delete-destination --account myaccount --user s1234567 --application demo --name weather --host hanatrial.ondemand.com

neo delete-destination --account myaccount --user s1234567 --provider-account otheraccount --provider-application remotedemo --name weather --host hanatrial.ondemand.com

NoteThe configuration parameters used by SAP HANA Cloud console client can also be defined in a properties file instead of being specified directly in the command (with the exception of the --password parameter, which must be specified when the command is executed). When you use a properties file, enter the path to it as the last command line parameter. A sample weather properties file can be found in directory <SDK_location>\tools\samples\connectivity.

Example:

neo put-destination <path_to_properties_file>

Related LinksTutorial: Using Internet Services in Cloud Applications [page 358]Tutorial: Using On-Premise Back-End Services in Cloud Applications [page 364]Tutorial: Sending E-Mails [page 396]Tutorial: Invoking ABAP Function Modules in On-Premise ABAP Systems [page 384]

1.3.5.2 Using the Cloud Connector

Overview

SAP HANA Cloud connector serves as the link between on-demand applications in SAP HANA Cloud and existing on-premise systems. It combines an easy setup with a clear configuration of the systems that are exposed to SAP HANA Cloud. In addition, you can control the resources available for the Java EE applications in those systems. Thus, you can benefit from your existing assets without exposing the whole internal landscape.

Follow the general steps below to learn how to install your SAP HANA Cloud connector.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 319

Page 320: Hana Cloud

General Steps

NoteWe recommend that you read the Secure Connector Setup page before executing the initial configuration. For more information, see Recommendations for Secure Setup [page 324]

1. Installing the Cloud Connector [page 320]2. Initial Configuration [page 329]3. Accessing Control Configuration (HTTP) [page 354]4. Tutorial: Using On-Premise Back-End Services in Cloud Applications [page 364]

1.3.5.2.1 Installing the Cloud Connector

Overview

This page outlines how you install your SAP HANA Cloud connector and configure your certificates to provide best security for the Cloud connector.

320P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 321: Hana Cloud

Prerequisites

There is a list of prerequisites you need to fulfill to successfully install the Cloud connector. For more information, see Prerequisites [page 322].

Procedure

The instructions below apply to zypper and rpm. If you prefer to use other tools with a GUI to install RPMs, for example, Software management in YAST, you are naturally free to do so.

1. Log in as root.2. Extract the ZIP archive on your local file system, preferably into a separate directory, for example, /scratch/

sccRPMs. It should contain three separate RPM files:

○ com.sap.accad-onpremise-<version/platform>.rpm○ com.sap.scc-ui-<version>.rpm○ com.sap.scc-plugin-library-<version/platform>.rpm

3. Install. Execute the commands below.

○ If using zypper:

1. First, create a repository containing the Cloud connector RPMs:

zypper ar -f <extraction_directory> SCCRepository

2. If it has not already been configured, configure the repository containing SUSE RPMs.For more information about managing your SUSE repository, see Novel Doc: Managing Software Repositories and Services.

3. Then, install the Cloud connector (this will also install all dependent RPMs required):

zypper in com.sap.scc-ui

○ If using rpm, change to the extraction directory and execute:

rpm -i --aid *.rpm

NoteDependencies:

If there are missing dependencies, zypper should automatically select them for installation prior to installing the Cloud connector RPM files.

○ Follow the instructions provided by zypper/rpm.○ Since rpm does not use repositories, you will need to manually download and install the required

dependencies if you use rpm.○ The Cloud connector requires the following packages: SuSEfirewall2, autoyast2, bootsplash,

bootsplash-branding-SLES, desktop-translations, dosfstools, expect, gdb, gfxboot, gfxboot-branding-SLES, iptables, less, libltdl7, libopenct1, libopensc2, libpcap0, libxml2-python, libxslt, lsb-release, mpt-firmware, mtools, opensc, openssh, pam_ssh, pcsc-lite, perl-HTML-Parser, perl-HTML-Tagset, perl-Unix-Syslog, perl-XML-XPath, polkit-default-privs, strace, tcl, tcpdump, vim, vim-base, vim-data, wget, xdg-utils, yast2-metapackage-handler, yast2-schema, yast2-trans-en_US, man-pages, man, telnet.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 321

Page 322: Hana Cloud

If there are dependencies that could not be resolved, connect your system to all SLES 11 RPM repositories offered by Novell and try again.

4. Once the installation has completed, start the UI daemon. If your Cloud connector version is:

○ 1.0.1 or higher, the UI daemon is started automatically.○ 1.0.0 or lower, you need to manually start the UI daemon. In the installation directory /opt/sap/scc,

execute:

/opt/sap/scc/daemon.sh start

If you need to manage the daemon, execute:

service scc_daemon stop|restart|start|status

Security Note

Before completing the installation, we strongly recommend that you read and follow the steps described in Recommendations for Secure Setup [page 324]. As a minimum, you should make sure that the default password for the Cloud connector administration UI, which is configured after installation, is changed.

Next Steps

Initial Configuration [page 329]

Prerequisites

Overview

The listed prerequisites need to be fulfilled for successful installation of SAP HANA Cloud connector.

General Connectivity Restrictions

For general information about product restrictions, see Product Restrictions [page 20] → section "SAP HANA Cloud Connectivity Service".

322P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 323: Hana Cloud

Hardware

Hardware prerequisites, physical or virtual machine:

● Memory: mininum 1GB RAM, 4GB recommended● Hard disk space: minimum 20 GB, 100GB recommended (needed for /opt and /usr)● CPU: minimum single core 3 GHz, dual core 2 GHz recommended, x86-64 architecture compatible

Software

Operating system requirements for the Cloud connector:

● SUSE Linux 11 SP1 or SP2, on an x86-64 processor architectureFor more information, see Processor Architecture x86-64.

● Make sure that your server has access to the Internet either directly or via a proxy to all subdomains of hana.ondemand.com and netweaver.ondemand.com.

● Your SLES 11 system is connected to the SUSE/Novell SLES 11 RPM repositories, so that additional RPMs can be downloaded and installed automatically, as required. For more information, see:SUSE Administration GuideKeep your SUSE Linux Updated with Subscription Management Tool

● You have a JRE 6 x64 installed on your system, preferably SAP JVM 6.1 (for download instructions, see SAP Note 1442124). In case you are using SAP JVM or a JVM not taken from an SLES repository, make sure that the Symbolic links /usr/bin/keytool and /usr/bin/java are set properly and point to the binaries in the x64 installation. Typically, on SLES this is done indirectly via links in /etc/alternatives.

NoteDouble verify that /usr/bin/keytool and /usr/bin/java are available. If the keytool file is missing, the installation script does not change the default password secret. If the java file is missing, the installation script will not be able to create the scc_daemon service.

SAP HANA Cloud

● You have downloaded the Cloud connector installation archive from SAP Development Tools for Eclipse.● Restriction: Upgrades can only be done from SAP HANA Cloud connector versions equal to or higher than

1.0.1.

Related LinksInstalling the Cloud Connector [page 320]Recommendations for Secure Setup [page 324]

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 323

Page 324: Hana Cloud

Recommendations for Secure Setup

Overview

The following guideline should be applied by customers who use SAP HANA Cloud connectivity service and SAP HANA Cloud Connector to guarantee the highest level of security.

Password Policy for the Cloud Connector Administration UI

Once installed, the Cloud connector provides an initial user name and password and forces the user (Administrator) to change the password upon initial login. The password should be changed from the initial password to a specific one immediately after installation.

The connector itself does not check the strength of the password. The Cloud connector administrator must select a strong password that cannot be guessed easily.

NoteTo enforce your company's password policy, we recommend that you configure the Administration UI to use an LDAP server for authorizing access to the UI.

Restricting OS Level Access to Machines with Cloud Connector Installation

The Cloud connector currently stores the following configuration items on the file system:

● The X.509 client certificate that establishes the tunnel to SAP HANA Cloud.● The Tomcat-based user authentication file that manages the access to the Cloud connector administration UI

on the file system.

To minimize the risk of this data being stolen, only authorized persons should have access to the machine. We recommend that this machine is only used to provide a Cloud connector. For the time being, other services should be deployed to different installations.

Cloud Connector Administrator Privileges

To log on to the Cloud connector administration UI, the "Administrator" user of the connector must not have an OS user for the machine on which the connector is running. This allows the OS administrator to be distinguished from the Cloud connector administrator. To make an initial connection between the connector and a particular SAP HANA Cloud account, an SAP HANA Cloud user with the needed permissions for the related account is required. We recommend that you separate these roles/duties (that means, you have separate users for Cloud connector administrator and SAP HANA Cloud).

Note

324P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 325: Hana Cloud

We recommend that only a small number of users be granted access to the machine as root.

Using Hard-Drive Encryption for Machines with Cloud Connector Installations

This ensures that the Cloud connector configuration data cannot be read by unauthorized users, even if they obtain access to the hard drive.

Accessing the Cloud Connector Administration UI

The Cloud connector administration UI can be remotely accessed via HTTPS. The connector uses a standard X.509 self-signed certificate as SSL server certificate. The certificate can be exchanged by a customer-specific certificate that is trusted by the customer. For more information, see Installing the Cloud Connector [page 320].

We recommend that you limit the access to the administration UI to localhost. To do this, proceed as follows:

1. Open the default-server.xml file of the Web container provided as part of the Cloud connector: /opt/sap/scc/config_master/org.eclipse.gemini.web.tomcat/default-server.xml

2. Modify the SSL Connector configuration in the <<Host>> section, which makes the Web container listen to the localhost only (that is, IP address 127.0.0.1):

<Connector port="8443" address="127.0.0.1" protocol="HTTP/1.1" SSLEnabled="true" maxThreads="150" scheme="https" secure="true" keystoreFile="config/ks.store" keystorePass="${jks.password}" keyPass="${jks.password}" keyAlias="tomcat" clientAuth="false" sslProtocol="TLS" />

Supported Protocols for On-Demand to On-Premise Connectivity

Currently, HTTP and HTTPS are supported as the protocols between SAP HANA Cloud and on-premise systems when the Cloud connector and the connectivity service are used. The whole route from the application virtual machine in the cloud to the Cloud connector is always SSL-encrypted.

The route from the connector to the back-end system can be SSL-encrypted.

For more information, see Accessing Control Configuration (HTTP) [page 354].

Switching On Audit Log in the Cloud Connector

The Cloud connector audit log must remain switched on (the default log level is "INFO") during the time it is used with productive systems. The administrators responsible for a running Cloud connector are obliged to ensure that

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 325

Page 326: Hana Cloud

the audit log files are properly archived and do not get lost. Additionally, audit logging should be switched on in the connected back-end systems.

1.3.5.2.2 Optional: Replacing the Default SSL Certificate

Overview

By default, the Cloud connector comes with a self-signed default certificate that is used to encrypt the communication between the browser-based user interface and the Cloud connector itself. For security reasons, however, you should replace this certificate with your own certificate. For this purpose, you need to know the password of the Cloud connector's Java keystore. This password is generated during installation and then kept in an encrypted secure storage area.

Procedure

You can read the password by executing the following command:

java -cp /opt/sap/scc/dropins/scc/plugins/com.sap.scc.tomcat.utils*.jar -Djava.library.path=/usr/local/vl/base/lib com.sap.mw.scc.util.SecStoreAccess -show

In the next procedure, we will use the standard Java keytool tool to delete/generate/import certificates from/for/into the Cloud connector's keystore. Memorize the keystore password shown by the above command, as you will need it for these operations.

Also make sure that you change into the directory /opt/sap/scc/config before executing the commands described in the following.

NoteFor a detailed description of the keytool tool, see http://docs.oracle.com/javase/6/docs/technotes/tools/solaris/keytool.html.

Related LinksUsing a Self-Signed Certificate [page 327]

Using Certificates Signed by Trusted Certificate Authority [page 327]

326P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 327: Hana Cloud

Using a Self-Signed Certificate

Context

If you want to use a simple, self-signed certificate, follow the procedure below.

NoteThe parameter values in the following section are simply examples.

The Server configuration delivered by SAP uses the same password for key store (option \-storepass) and key (option \-keypass) under alias tomcat.

Procedure

1. Remove the current default certificate:

keytool -delete -alias tomcat -keystore ks.store -storepass <password>

2. Generate a certificate:

keytool -genkey -v -keyalg RSA -alias tomcat -keypass <password> -keystore ks.store -storepass <password> -dname "CN=SCC, OU=<YourCompany>, O=<YourCompany>"

3. Self-sign it - you will be prompted for the keypass password defined in step 2:

keytool -selfcert -v -alias tomcat -storepass <password> -keystore ks.store

Using Certificates Signed by Trusted Certificate Authority

Overview

Before starting the procedure, bear in mind that

● The parameter values in the following section are simply examples.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 327

Page 328: Hana Cloud

● We recommend that you use a signed certificate by a trusted CA, because it is more secure than a self-signed certificate.

● For your convenience, you can set the generated password as environment variable, like in the command below, and then use $PASS as a password:export PASS=`java -cp /opt/sap/scc/dropins/scc/plugins/com.sap.scc.tomcat.utils*.jar -Djava.library.path=/usr/local/vl/base/lib com.sap.mw.scc.util.SecStoreAccess -show`

Procedure

If you have a signed certificate produced by a trusted certificate authority (CA), go directly to step 3.

1. Create a local Certificate Signing Request (CSR):

keytool -certreq -keyalg RSA -alias tomcat -keypass <password> -keystore ks.store -storepass <password> -file <csr-file-name>

2. Import the certificate chain that you obtained from your trusted CA:

keytool -import -alias root -keystore ks.store -storepass <password> -trustcacerts -file <filename_of_the_certificate_chain>

You now have a file called <<csr-file-name>> that you can submit to the Certificate Authority. In return you get a certificate.

3. Now import your new certificate:

keytool -import -alias tomcat -keystore ks.store -storepass <password> -file <your_certificate_filename>

The password is created at installation time and stored in the secure storage. Thus, only applications with access can read the password. You can read password using Java:

jar -xf /opt/sap/scc/dropins/scc/plugins/com.sap.scc.tomcat.utils*.jar lib/libsapsecstore4j.so java -cp /opt/sap/scc/dropins/scc/plugins/com.sap.scc.tomcat.utils*.jar -Djava.library.path=./lib/ com.sap.mw.scc.util.SecStoreAccess -show

You might need to adapt the configuration if you want to use another key storage file or change the current configuration (HTTPS port, authentication type, SSL protocol, and so on). You can find the SSL configuration in the Connector section of the file /opt/sap/scc/config_master/org.eclipse.gemini.web.tomcat/default-server.xml:

NoteWe recommend that you do not modify the configuration unless you have expertise in this area.

<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true" maxThreads="150" scheme="https" secure="true" keystoreFile="config/ks.store" keystorePass="${jks.password}" keyPass="${jks.password}" keyAlias="tomcat" clientAuth="false" sslProtocol="TLS" />

328P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 329: Hana Cloud

For more information about configuring SSL, see http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#SSL_and_Tomcat.

If you prefer, you can also revert to plain HTTP for the Cloud connector administrator UI.

1.3.5.2.3 Initial Configuration

Overview

Once SAP HANA Cloud connector has been installed and the Cloud connector daemon has been started, you can log on and perform the necessary customization to make your Cloud connector operational. To do this, follow the procedure below.

Logging in to the Cloud Connector Administration UI

To administer the Cloud connector, you need a Web browser.

NoteThe browsers currently supported are: Internet Explorer 9, Firefox 10 (Firefox Extended Support Release - ESR) and the latest version, Safari 5.1, and the latest version of Chrome.

1. In a Web browser, enter: https://<hostname>:8443

○ Here, hostname refers to the machine on which the Cloud connector has been installed.○ If the Cloud connector has been installed and started successfully, you will see the following login screen:

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 329

Page 330: Hana Cloud

2. For User Name / Password enter Administrator / manage (case sensitive).3. When you first log in, you must change the password before you continue.

You can change the password again at a later stage from the Settings menu in the upper right-hand side corner:

Configuring the Proxy Connection

If your internal landscape is protected by a Firewall that blocks any outgoing TCP traffic, you need to specify an HTTPS proxy that the Cloud connector can use to connect to SAP HANA Cloud. Normally, you would need to use the same proxy settings as those being used by your standard Web browser. The Cloud connector needs this proxy for two operations:

● Downloading the correct connection configuration corresponding to your account ID in SAP HANA Cloud● Establishing the SSL tunnel connection from the Cloud connector to your SAP HANA Cloud account.

330P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 331: Hana Cloud

When you log on for the first time, the Cloud connector asks you for the proxy settings (together with some other settings described in the following sections). Enter values the hostname and port fields in the HTTPS Proxy section. You need to specify a proxy server that supports SSL communication; a standard HTTP proxy will not suffice.

NoteIf you are unsure what to specify here, use the same parameters as those used in your Web browser.

If you later need to change the proxy settings (for example, because the company firewall rules have changed), choose the Settings menu in the upper right-hand side corner. Some proxy servers require credentials for authentication. In this case, you need to provide the relevant user/password information.

Downloading Specific Connection Parameters for Your Account from the Cloud

Once the proxy parameters have been defined, the Cloud connector is able to connect to SAP HANA Cloud and download the configuration and credentials corresponding to your SAP HANA Cloud account. When you first log on, the connector also collects the necessary information required for this purpose in the Configuration section on the same screen in which you entered the proxy parameters:

1. The Host field can usually be left at its default value. It specifies the SAP HANA Cloud platform that should be used.

2. For Account ID and Account Operator (user/password), enter the values you obtained when you registered your account on SAP HANA Cloud.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 331

Page 332: Hana Cloud

3. Once all the settings have been completed, choose Apply.4. The Cloud connector starts a handshake with the SAP HANA Cloud side and attempts to establish a secure

SSL tunnel to the server hosting account in which your on-demand applications are running.5. However, no requests are yet allowed to pass from the SAP HANA Cloud side to any of your internal back-end

systems. To allow your on-demand applications to access specific internal back-end systems, proceed with the access configuration described in the next section.

If you later need to change any of the above parameters, you can do so from the Settings menu.

Establishing the Connection to SAP HANA Cloud

Once the initial setup has been completed successfully, the tunnel to the SAP HANA Cloud endpoint is open (even though no requests are allowed to pass until you have completed the access control setup). However, you can manually close (and reopen) the connection to SAP HANA Cloud by opening the Home tab page and choosing the Disconnect button (or the Connect button to reconnect to SAP HANA Cloud).

The green icon next to Landscape Host and HTTP Proxy indicates that they both are valid and work properly. In case of a timeout or a connectivity issue, the icon is respectively yellow (warning) or red (error), and a tooltip displays the cause of the problem.

Related LinksUsing LDAP for Managing Cloud Connector Administrator Users [page 332]

Accessing Control Configuration (HTTP) [page 354]

1.3.5.2.4 Using LDAP for Managing Cloud Connector Administrator Users

Overview

332P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 333: Hana Cloud

After installation, the Cloud connector uses file-based user management. Initially there is one Administrator user with the password manage, which needs to be changed on the first logon. As an alternative to this file-based user management, the Cloud connector also supports LDAP-based user management. If you have an LDAP server in your landscape, you can configure the Cloud connector to use the users available on that LDAP server. All users that are in a group named admin or sccadmin will have the necessary authorization for administrating the Cloud connector. This group membership is checked by the Cloud connector.

Setting LDAP Authentication

1. To change the configuration, log on to the Cloud connector and choose Settings in the menu.

2. The LDAP server generally lists users in an LDAP node and user groups in another node. In this case, you can use the template for LDAP configuration.

3. You copy the template to the configuration text area by choosing the rightmost button immediately below the text area. The template looks as follows:

userPattern="uid={0},ou=people,dc=mycompany,dc=com"roleBase="ou=groups,dc=mycompany,dc=com"roleName="cn"roleSearch="(uniqueMember={0})"

4. Adjust the ou and dc fields in userPattern and roleBase according to the configuration on your LDAP server.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 333

Page 334: Hana Cloud

5. Provide the LDAP server and port (port 389 is used by default), select Use LDAP Authentication and choose Apply. Immediately after applying the LDAP configuration, a restart of the local server is enforced, which invalidates the current browser session. Thus, the browser needs to be refreshed and a new logon to the Cloud connector is necessary with the credentials configured on the LDAP server.To switch back to file-based user management, deselect Use LDAP Authentication and choose Apply.

For more information about how to set up LDAP authentication, see tomcat.apache.org/tomcat-7.0-doc/realm-howto.html.

NoteIf the LDAP configuration is incorrect, you will probably not be able to log on to the Cloud connector UI again. In this case, you can edit the Cloud connector configuration manually. For more information, see the next section.

Manually Switching Cloud Connector Back to File-Based User Management

The configuration file is /opt/sap/scc/config_master/org.eclipse.gemini.web.tomcat/default-server.xml.

1. To revert to file-based authentication, replace the Realm section with the following:

<Realm className="org.apache.catalina.realm.UserDatabaseRealm" digest="SHA1" resourceName="UserDatabase"/>

2. Restart the Cloud connector service using the following command:

service scc_daemon restart

1.3.5.2.5 Connectivity via Reverse Proxy

Overview

This page outlines an alternative approach for technical connectivity between the cloud and on-premise, using a reverse proxy. It also discusses the pros and cons of this method compared to when you use SAP HANA Cloud connector.

334P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 335: Hana Cloud

Features

An alternative approach compared to the SSL VPN solution, provided by SAP HANA Cloud connector, is to expose on-premise services and applications via a reverse proxy to the Internet. For this method, there is typically a reverse proxy setup in the "demilitarized zone" (DMZ) subnetwork of a customer, which:

● Acts as a mediator between SAP HANA Cloud and the on-premise services;● Provides the services of an Application Delivery Controller (ADC) in order, for example, to encrypt, filter,

route, or introspect the inbound traffic.

The figure below shows the minimal overall network topology of this approach. For more information, see Technical Connectivity Guide.

On-premise services accessible via reverse proxy are then callable from SAP HANA Cloud like other HTTP services available on the Internet. When you use destinations to call those services, make sure that the configuration of the ProxyType parameter is set to Internet.

Advantages

Depending on your scenario, you can benefit from the reverse proxy. An example is the required network infrastructure (such as a reverse proxy and ADC services): Since it already exists in your network landscape, you can reuse it to connect to SAP HANA Cloud. In this case, there would be no need to set up and operate new components on your (customer) side.

Disadvantages

● The reverse proxy approach does not prevent the exposed services from being generally accessible via the Internet, which makes them vulnerable to attacks from anywhere in the world. Denial-of-Service attacks in particular are possible and difficult to protect against. Therefore, protection against potentials attacks requires the highest security standards to be implemented in the DMZ and reverse proxy. For the productive deployment of a hybrid cloud/on-premise application, this approach usually requires intense involvement of the customer's IT department and a longer period of implementation.

● SAP-proprietary RFC protocol is not supported, so that a cloud application cannot directly call an on-premise ABAP system without having application proxies on top of ABAP.

Note

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 335

Page 336: Hana Cloud

These demerits do not exist when using the SAP HANA Cloud connector. As it establishes the SSL VPN tunnel to SAP HANA Cloud via a reverse invoke approach, there is no need to configure the DMZ or external firewall of a customer network for inbound traffic. Attacks from the Internet are not possible. With its simple setup and fine-grained access control of exposed systems and resources, the Cloud connector allows a high level of security and fast productive implementation of hybrid applications. It also supports multiple application protocols such asHTTP and RFC.

1.3.5.2.6 Upgrading the Cloud Connector

Overview

NoteBear in mind that the following steps focus on the use of zypper. If you prefer to use other tools with a graphical user interface to install RPMs, for example, Software management in YAST, you are naturally free to do so.

We assume that you have previously followed the initial installation instructions with zypper mentioned in the previous section.

Procedure

1. Extract the ZIP archive on your local file system, preferably into the directory to which you extracted the RPMs you originally used for your initial installation, for example, /scratch/sccRPMs.

2. Execute the zypper commands below.

NoteTo perform the upgrade, you need to be logged in as root.

a. First, refresh the repository containing the Cloud connector RPMs:

zypper ref SCCRepository

b. Then, upgrade SAP HANA Cloud connector (this will also upgrade all dependent RPMs, if required):

zypper up --repo SCCRepository

c. Follow the instructions provided by zypper.

336P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 337: Hana Cloud

1.3.5.2.7 Uninstalling the Cloud Connector

Overview

Follow this procedure to uninstall your SAP HANA Cloud connector.

NoteYou need to be logged on as root in order to perform the uninstallation.

Procedure

1. Execute:

zypper rm AccAD_CFE_ODOP

This removes all packages that have been installed for the Cloud connector from your machine.2. If there are subsequently issues when re-installing the software, remove some of the files manually by

executing:

rm -rf /opt/sap/scc

1.3.5.2.8 Troubleshooting

Overview

This page provides you with details on how to monitor the state of your open tunnel connections in the Cloud connector. You can also view different type of logs and traces that can help you troubleshoot connection problems.

To find a solution for a particular problem or an error you have encountered, you can refer to the Cloud connector troubleshooting pages. For more information, see Connectivity Troubleshooting Guide [page 402].

Monitoring

Information about the tunnel connections currently open to the SAP HANA Cloud endpoint can be monitored on the Home tab page. Here you can find information about the number of streams currently open.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 337

Page 338: Hana Cloud

Tracing

If you encounter problems, you can go to the Monitor Traces tab page and activate tracing there. In the Trace Settings pane, the Cloud connector currently offers four trace levels (apart from Off):

● Runtime: The Cloud connector traces some information on each request that originates from SAP HANA Cloud, whether it was allowed to pass, and to which target system it has been forwarded.

● Runtime and HTTP Traffic: In the addition to the previous, the Cloud connector also traces every HTTP request (header and body) coming from SAP HANA Cloud and every HTTP response coming from the back-end system. Each request/response is traced in both binary and textual format. Note that this may create a huge amount of data, thus you need to use it with care and only for a short time, when troubleshooting a particular problem.

● Runtime and Internal Communication: In addition to the runtime information, the Cloud connector also traces all interaction between its user interface and its runtime.

NoteThis is not generally relevant for normal operation, but rather in special cases where troubleshooting by SAP support personnel is required to address problems in the Cloud connector itself.

● Full: See all the above.

In the Trace Files section, you can view all existing trace files and delete those that are no longer needed.

338P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 339: Hana Cloud

To prevent your browser from being overloaded when files of several MBs or even GBs are loaded simultaneously, the Cloud connector loads only one page into memory and you can display the trace file one page at a time. Use the pagination buttons to scroll forward/backward by one page (angle bracket), or jump to the beginning or end of the file (angle bracket plus vertical bar).

Via the Download/Download All buttons you can create a ZIP archive containing one particular trace file and download it to your local file system for convenient analysis of larger trace files.

NoteTrace files currently in use by the Cloud connector cannot be deleted from the UI. Linux allows them to be deleted from the command line, but we recommend that you do not use this option to avoid inconsistencies in the Cloud connector internal trace management.

Once a problem has been identified, you can turn off the trace again from this page.

Note

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 339

Page 340: Hana Cloud

On this screen, you can use the Refresh button to update the displayed information. (This option is also available on all other screens.) For example, you use this button because more trace files may have been written since you last updated the display.

Audit Logs

From Monitor Audit , you can specify which kind of audit events the Cloud connector should log at runtime. Currently, you can choose between three different Audit Levels:

● All: The Cloud connector writes one audit entry for each received request, regardless of whether or not it was allowed to pass ("Access Allowed" as well as "Access Denied"). The Cloud connector also writes audit entries, whenever an administrator changes one of the critical configuration settings like exposed back-end systems, allowed resources, and so on.

● Security: The Cloud connector writes an audit entry for each request that was blocked ("Access Denied").● Off: No audit entries are written.

Audit entries for configuration changes are written for the following different categories:

● BackendMapping: Something changed in the virtual to internal system mappings.● AllowedResource: For one of the virtual systems, something changed in the accessible resources.● DomainMapping: Something changed in the domain mappings.● SCC Password: The Cloud connector administration password was changed.● LDAP Configuration: Something changed in the LDAP settings.● Configuration: The settings for the connection to SAP HANA Cloud were changed.● Proxy Settings: The proxy settings were changed.● Audit Log Level: The audit log level was changed.

In the Audit Viewer section, you can first define filter criteria and then display the selected audit entries.

● In the Audit Type field, you can select whether you want to view the audit entries for:

○ only requests that were denied;○ only requests that were allowed;○ Cloud connector changes;○ all of the above.

● In the Pattern field, you can specify a certain string that the detail text of each selected audit entry must contain. The detail text contains information about the user name, requested resource/URL, and the virtual <<host>:<port>>. Wildcards are currently not supported in this field. This feature can help you:

○ Filter the audit log for all requests that a particular HTTP user has made during a certain time frame

340P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 341: Hana Cloud

○ Identify all users who attempted to request a particular URL○ Identify all requests to a particular back-end system○ Find out whether someone has changed a certain SAP HANA Cloud connnector configuration. For

example, a search for string "BackendMapping" will return all add-, delete- or modify- operations on the Mapping Virtual To Internal System page.

● The Time Range settings specify the time frame for which you want to display the audit events.

These three filter criteria are combined with a logical AND so that all audit entries that match these criteria are displayed. If you have modified one of the criteria, choose the Refresh button to display the updated selection of audit events that match the new criteria.

In the following example, all audit entries for "allowed" requests from user Administrator between Apr. 1, 00:00:00 and Apr. 6, 23:59:59 are displayed:

Cloud Connector Internal Logs

● On the Monitor Logs tab page, you can find some log files that can help you troubleshoot problems with the internal operation of the Cloud connector. These logs are intended primarily for SAP support.

● Under UI Logs, there are log files in which error details are logged when the communication between the UI component and the local tunnel component fails.

● Under Tunnel Logs you can find log files in which error details are logged when the communication between the local and the remote (SAP HANA Cloud) tunnel endpoint fails.

Processes

The processes monitor displays information about the processes that provide the Cloud connector functionality.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 341

Page 342: Hana Cloud

● The tunnel processes displayed in the left table are all processes needed for the tunnel functionality. The table shows the process ID (PID), the CPU time the process has had since its start, and its name. The Restart button, next to the table header Tunnel, allows restarting all involved processes. Note that this leads to a short downtime of the tunnel connection.

● The UI has a single process only and hence it only shows the process ID (PID) and the CPU time. The Restart button, next to the table header UI, allows restarting the process. In this case, the UI is not usable for a while, but the connectivity runtime is not affected.

1.3.5.3 Exchanging Data via HTTP Protocol

Consuming Connectivity via HTTP

● Call an Internet service using a simple application that queries some weather information from a public service: Tutorial: Using Internet Services in Cloud Applications [page 358]

● Call a service from a fenced customer network using a simple application that consumes an on-premise ping service: Tutorial: Using On-Premise Back-End Services in Cloud Applications [page 364]

Configuring Connectivity via HTTP

● Configure an application using destinations:Configuring Destinations from the Eclipse IDE [page 307]Configuring Destinations from the Console Client [page 315]

● Configure connectivity between a customer system and an on-demand application. You need to install SAP HANA Cloud connector in your internal network and then configure it to expose an on-premise service.For more information, see Installing the Cloud Connector [page 320]

Related LinksTutorial: Using the Keystore Service for Client Side HTTPS Connections [page 520]

342P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 343: Hana Cloud

1.3.5.3.1 HTTP Destinations

Overview

The HTTP destinations provide data communication via HTTP protocol and is used for both Internet and on-premise connections.

HTTP Destination Properties

The runtime tries to resolve a destination in the order: Subscription Level → Account Level → Application Level. By using the optional "DestinationProvider" property, a destination can be limited to application level only, that is, the runtime tries to resolve the destination on application level.

Property Description

DestinationProvider Restricts destination to application level. If the property is specified, the destination will be searched on the application level only. By default, destinations are searched on all configuration levels.

Example

Name=weatherType=HTTPAuthentication=NoAuthenticationDestinationProvider=Application

Supported Proxy Types for Connectivity

The proxy types supported by SAP HANA Cloud connectivity service are:

● Internet - The application can connect to an external REST or SOAP service on the Internet.● OnPremise - The application can connect to an on-premise back-end system through SAP HANA Cloud

connector.

The proxy type used for a destination must be specified by the destination property ProxyType. The property's default value (if not configured explicitly) is Internet.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 343

Page 344: Hana Cloud

Setting Proxy Types for SAP HANA Cloud Local Runtime

If you work in your local development environment behind a proxy server and want to use a service from the Internet, you need to configure your proxy settings on JVM level. To do this, proceed as follows:

1. On the Servers view, double-click the added server and choose Overview to open the editor.2. Click the Open Launch Configuration link.3. Choose the (x)=Arguments tab page.4. In the VM Arguments box, add the following row:

-Dhttp.proxyHost=yourproxyHost -Dhttp.proxyPort=yourProxyPort -Dhttps.proxyHost=yourproxyHost -Dhttps.proxyPort=yourProxyPort

5. Choose OK.6. Start/restart your SAP HANA Cloud local runtime.

For more information and example, see Tutorial: Using Internet Services in Cloud Applications [page 358].

Setting Proxy Types for SAP HANA Cloud

● When using the Internet proxy type, you do not need to perform any additional configuration steps.● When using the OnPremise proxy type, you configure the setting the standard way through the Connectivity

editor in the Eclipse IDE.For more information and example, see Tutorial: Using On-Premise Back-End Services in Cloud Applications [page 364].

Client Authentication Types for HTTP Destinations

Overview

This section lists the supported client authentication types and the relevant supported properties.

No Authentication

This is used for destinations that refer to a service on the Internet or an on-premise system that does not require authentication. The relevant property value is:

344P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 345: Hana Cloud

Authentication=NoAuthentication

NoteWhen a destination is using HTTPS protocol to connect to a Web resource, the JDK truststore is used as truststore for the destination.

Basic Authentication

This is used for destinations that refer to a service on the Internet or an on-premise system that requires basic authentication. The relevant property value is:

Authentication=BasicAuthentication

The following credentials need to be specified:

Property Description

User User name

Password Password

Preemptive If this property is not set or is set to TRUE (that is, the default behavior is to use preemptive sending), the authentication token is sent preemptively. Otherwise, it relies on the challenge from the server (401 HTTP code). The default value (used if no value is explicitly specified) is TRUE. For more information about preemptiveness, see http://tools.ietf.org/html/rfc2617#section-3.3.

NoteWhen a destination is using HTTPS protocol to connect to a Web resource, the JDK truststore is used as truststore for the destination.

Client Certificate Authentication

This is used for destinations that refer to a service in an on-premise system that requires X.509 certificate-based authentication. The relevant property value is:

Authentication=ClientCertificateAuthentication

Note that ClientCertificateAuthentication is currently not supported for communication against on-premise services.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 345

Page 346: Hana Cloud

The following credentials need to be specified:

Property Description

KeyStoreLocation

● When used on SAP HANA Cloud local runtime● When used on SAP HANA Cloud

Path to the JKS file that contains the client certificate(s) for client certificate authentication against a remote server.

● The relative path to the JKS file. The root path is the server's location on the file system.

● The name of the JKS file.

KeyStorePassword The password for the key storage. This property is mandatory in case KeyStoreLocation is used.

NoteYou can upload TrustStore JKS files using the same command for uploading destination configuration property file - you only need to specify the JKS file instead of the destination configuration file.

For more information, see Configuring Destinations from the Console Client [page 315]

Server Certificate Authentication

Overview

The server certificate authentication is applicable for all client authentication types, described below.

Properties

Property Description

TrustStoreLocation

● When used on SAP HANA Cloud local runtime● When used on SAP HANA Cloud

Path to the JKS file which contains trusted certificates (Certificate Authorities) for the client certificate authentication against a remote client.

● The relative path to the JKS file. The root path is the server's location on the file system.

● The name of the JKS file.

Note

346P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 347: Hana Cloud

Property Description

The default JDK truststore is appended to the truststore defined in the destination configuration. As a result, the destination simultaneously uses both truststores. If the TrustStoreLocation property is not specified, the JDK truststore is used as a default truststore for the destination.

TrustStorePassword The password for the JKS trust store file. This property is mandatory in case TrustStoreLocation is used.

TrustAll If this property is set to TRUE in the destination, the server certificate will not be checked for SSL connections. It is intended for test scenarios only, and should not be used in production (since the SSL server certificate is not checked, the server is not authenticated). The possible values are TRUE or FALSE; the default value is FALSE (that is, if the property is not present at all).

In case TrustAll = TRUE, the TrustStoreLocation property is ignored so you can omit it.

In case <TrustAll> = FALSE, the <TrustStoreLocation> property is mandatory to be used.

HostnameVerifier Optional property. It has two values: Strict and BrowserCompatible. This property specifies how the server hostname matches the names stored inside the server's X.509 certificate. This verifying process is only applied if TLS or SSL protocols are used and is not applied if the TrustAll property is specified. The default value (used if no value is explicitly specified) is Strict.

● Strict HostnameVerifier works in the same way as Oracle Java 1.4, Oracle Java 5, and Oracle Java 6-rc. It is also similar to Microsoft Internet Explorer 6. This implementation appears to be compliant with RFC 2818 for dealing with wildcards. A wildcard such as "*.foo.com" matches only subdomains at the same level, for example "a.foo.com". It does not match deeper subdomains such as "a.b.foo.com".

● BrowserCompatible HostnameVerifier works in the same way as Curl and Mozilla Firefox. The hostname must match either the first common name (CN) or any of the subject-alts. A wildcard can occur in the CN and in any of the subject-alts.

The only difference between BrowserCompatible and Strict is that a wildcard (such as ".foo.com") with BrowserCompatible matches all subdomains, including "a.b.foo.com".

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 347

Page 348: Hana Cloud

Property Description

For more information about these Java classes, see Package org.apache.http.conn.ssl.

In case <TrustAll> = TRUE, the <HostnameVerifier> property is ignored so you can omit it.

NoteYou can upload KeyStore JKS files using the same command for uploading destination configuration property file - you only need to specify the JKS file instead of the destination configuration file.

For more information, see Configuring Destinations from the Console Client [page 315]

SAP Assertion SSO Authentication

Overview

By default, all SAP systems accept SAP assertion tickets for user propagation. For more information, see SAP Logon Tickets. The aim of the SAPAssertionSSO destination is to generate such an assertion ticket in order to propagate the currently logged-on SAP HANA Cloud user to an SAP back-end system. You can only use this authentication type if the user IDs on both sides are the same.

Configuration Steps

1. Configure the back-end system so that it can accept SAP assertion tickets signed by a trusted x.509 key pair. For more information, see Configuring a Trust Relationship for SAP Assertion Tickets.

2. Configure the destinations in the SAP HANA Cloud console client with the properties that are listed below and deploy it on SAP HANA Cloud. For more information, see Configuring Destinations from the Console Client [page 315].

NoteConfiguring SAPAssertionSSO destinations from the Eclipse IDE is not yet supported.

348P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 349: Hana Cloud

Properties

The following credentials need to be specified:

Property Description

Name This is the destination name. It must be the same as the destination name you use for the configuration tools (the Connectivity editor in Eclipse IDE and SAP HANA Cloud console client).

Type This is the destination type. Use HTTP as a value for all HTTP(S) destinations.

Authentication This is the authentication type. Use SAPAssertionSSO as a value.

IssuerSID This system ID should be trusted by the back-end system.

IssuerClient This client ID should be trusted by the back-end system.

RecipientSID This is the system ID (SID) of the back-end system.

RecipientClient This is the client ID of the back-end system.

Certificate A base64 encoded certificate that is trusted by the SAP system.

SigningKey A base64 encoded signing/private key that is trusted by the SAP system.

SystemUser This is an optional property. If the property is specified, all SAP assertion tickets are generated with the specified user ID.

If the property is not specified, all SAP assertion tickets are sent on behalf of the currently logged-on user.

Thus, if the current user needs to be propagated, do not use this property.

ProxyType Both Internet and OnPremise proxy types can be used.

Example

Name=weatherType=HTTPAuthentication=SAPAssertionSSOIssuerSID=JAVIssuerClient=000RecipientSID=SAPRecipientClient=100Certificate=MIICiDCCAkegAwI...rvHTQ\=\=SigningKey=MIIBSwIB...RuqNKGA\=

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 349

Page 350: Hana Cloud

Application-to-Application SSO Authentication

Overview

The AppToAppSSO destinations are used in scenario of application-to-application communication where the caller needs to propagate its logged in user. Both applications are deployed on SAP HANA Cloud and consumed within a single account.

Configuration Steps

1. Configure your account to allow principal propagation. For more information, see Using a Custom Identity Provider [page 487] → section "Principal Propagation".

NoteThis setting is done per account, which means that once set to Enabled all applications within the account will accept user propagation.

2. Configure the destinations in the SAP HANA Cloud console client with the properties that are listed below and deploy it on SAP HANA Cloud. For more information, see Configuring Destinations from the Console Client [page 315]

NoteConfiguring AppToAppSSO destinations from the Eclipse IDE is currently not supported.

Properties

The following credentials need to be specified:

Property Description

Name This is the destination name. It must be the same as the destination name you use for the configuration tools (the Connectivity editor in Eclipse IDE and SAP HANA Cloud console client).

Type This is the destination type. Use HTTP as a value for all HTTP(S) destinations.

Authentication This is the authentication type. Use AppToAppSSO as a value.

350P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 351: Hana Cloud

Property Description

URL This is the URL of a protected resource on the called application.

Example

Name=a2assoURL= http://hostname:8080/MyApp/index.jspType=HTTPAuthentication=AppToAppSSO

Related LinksServer Certificate Authentication [page 346]

HTTP Destination API

Overview

By default, all connectivity API packages are visible from all Web applications. In this classical case, applications can consume the destinations via a JNDI lookup. For more information, see Destination API [page 305].

There are specific cases though, when the destination names are not known in advance and cannot be defined in the web.xml file. This is relevant to HTTP destinations and you need to use Destination Factory JNDI lookup (com.sap.core.connectivity.api.DestinationFactory). To do this, follow the procedure below.

Procedure

To look up the destination factory using JNDI, follow the steps:

1. Define a reference in the web.xml file:

<resource-ref> <res-ref-name>connectivity/DestinationFactory</res-ref-name> <res-type>com.sap.core.connectivity.api.DestinationFactory</res-type> </resource-ref>

2. Use the following code in order to look it up:

import com.sap.core.connectivity.api.DestinationFactory;import com.sap.core.connectivity.api.http.HttpDestination...Context ctx = new InitialContext();

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 351

Page 352: Hana Cloud

DestinationFactory destinationFactory =(DestinationFactory)ctx.lookup(DestinationFactory.JNDI_NAME);HttpDestination destination = (HttpDestination) destinationFactory.getDestination("myBackend");

3. With the retrieved HTTP destination, you can then, for example, send a simple GET request to the configured remote system by using the following code:

Related LinksDestination API [page 305]

1.3.5.3.2 Configuring the Cloud Connector for HTTP

Overview

This section helps you to configure your SAP HANA Cloud connector when you are working via the HTTP protocol.

Related LinksInitial Configuration (HTTP) [page 352]

Accessing Control Configuration (HTTP) [page 354]

Initial Configuration (HTTP)

Installation of a System Certificate for Mutual Authentication

In order to setup a mutual authentication between the Cloud connector and any back-end system it connects to, you can import an X.509 client certificate into the Cloud connector. The Cloud connector will then use the so-called "system certificate" for all HTTPS requests to back-ends that request or require a client certificate. This means, that the CA, which signed the Cloud connector's client certificate, needs to be trusted by all back-end systems to which the Cloud connector is supposed to connect.

This system certificate needs to be provided as PKCS#12 file containing the client certificate, the corresponding private key and the CA root certificate that signed the client certificate (plus potentially the certificates of any intermediate CAs, if the certificate chain is longer than 2). Via the file upload dialog, this PKCS#12 file can be chosen from the file system, and its password also needs to be supplied for the import process:

352P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 353: Hana Cloud

If a system certificate has successfully been imported, its distinguished name and validity date are displayed:

Related LinksAccessing Control Configuration (HTTP) [page 354]

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 353

Page 354: Hana Cloud

Accessing Control Configuration (HTTP)

Exposing Intranet Systems

To allow your on-demand applications to access a certain back-end system on the intranet, you need to insert an extra line into the Cloud connector access control management. To do this, go to the Access Control tab page and choose Add.

● The Virtual Host specifies the host name exactly as it is specified as the URL property in the HTTP destination configuration in SAP HANA Cloud. The Internal Host specifies the actual host under which the target system can be reached within the intranet.The virtual host can be a fake name, but the internal host needs to be an existing network address that can be resolved on the intranet.

● The Virtual Port basically allows you to distinguish between different entry points of your back-end system, for example, HTTP/80 and HTTPS/443, and have different sets of access control settings for them. For example, some non-critical resources may be accessed by HTTP, while some other critical resources are to be called using HTTPS only. If you leave the Internal Host parameters blank, the Cloud connector will try to forward the request to the network address specified by the virtual host and port, so in this case, this address needs to be real.

● The Protocol field allows you to decide whether the Cloud connector should use HTTP or HTTPS for the connection to the back-end system. Note that this is completely independent from the settings on SAP HANA Cloud side. Thus, even if the HTTP destination on SAP HANA Cloud side specifies "http://" in its URL, you can select HTTPS. This way you are ensured that the entire connection from the on-demand application to the actual back-end system (provided through the SSL tunnel) is SSL-encrypted. The only prerequisite is that the back-end system supports HTTPS on that port. If you specify HTTPS and there is a "system certificate" imported in the Cloud connector, the latter attempts to use that certificate for performing a client-certificate-based login to the back-end system. If there is no system certificate imported, the Cloud connector opens an HTTPS connection without client certificate.For more information, see Initial Configuration [page 329] → section "Installation of a System Certificate for Mutual Authentication".

354P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 355: Hana Cloud

● For the Back-end Type field select the description that best matches the addressed back-end system. This is important mainly for metering information: tunnel connections to any kind of SAP system are free of charge, while using the tunnel for connecting to a non-SAP system costs a fee.

NoteYou can later edit such a system mapping to make the Cloud connector route the requests for sales-system.cloud:443 to a different back-end system. This can be useful if the system is currently down and there is a back-up system that can serve these requests in the meantime. However, you cannot edit the virtual name of this system mapping. If you want to use a different fictional host name in your on-demand application, you will need to delete the mapping and create a new one.

After saving the hostname mapping, you can use the Check button to trigger a ping from the Cloud connector to the Internal host. This option allows you to make sure that the Cloud connector can indeed access the Internal system, and allows you to catch basic issues like spelling mistakes or firewall problems between the Cloud connector and the Internal host. In case the ping to the Internal host fails, the Cloud connector displays a red exclamation mark icon.

Limiting the Accessible Services for HTTP(S)

In addition to allowing access to a particular host and port, you also need to specify which URL paths (Resources) are allowed to be invoked on that host. The Cloud connector uses very strict white-lists for its access control, so only those URLs for which you explicitly granted access are allowed. All other HTTP(S) requests are denied by the Cloud connector.

To define the permitted URLs (Resources) for a particular back-end system, choose the line corresponding to that back-end system. A dialog appears prompting you to enter the specific URL path that you want to allow to be invoked.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 355

Page 356: Hana Cloud

The Cloud connector checks that the path part of the URL (up to but not including a possible question mark (?) that may denote the start of optional CGI-style query parameters) is exactly as specified in the configuration. If it is not, the request is denied. If you select option Path and all sub-paths, the Cloud connector allows all requests for which the URL path (not considering any query parameters) begins with the specified string.

The Enabled checkbox allows you to specify, whether that resource shall initially be enabled or disabled. (See the following section for an explanation of enabled/disabled resources.)

Enabling/Disabling Resources On-the-Fly

In some cases, it is useful for testing purposes to temporarily disable certain resources without having to delete them from the configuration. This allows you to easily re-provide access to these resources at a later point of time without having to type in everything once again.

● To disable a resource, select it and choose the Disable button:The traffic light turns red, and from now on, the Cloud connector will deny all requests coming in for this resource.

● To enable the resource again, select it and choose the Enable button.● It is also possible to mark multiple lines and then to disable/enable all of them in one go by clicking the

Enable/Disable buttons in the top row.

Examples:

● /production/accounting and Path only (sub-paths are excluded) are selected. Only requests of the form GET /production/accounting or GET /production/accounting?name1=value1&name2=value2... are allowed. (GET can also be replaced by POST, PUT, DELETE, and so on.)

● /production/accounting and Path and all sub-paths are selected. All requests of the form GET /production/accounting-plus-some-more-stuff-here?name1=value1... are allowed.

● / and Path and all sub-paths are selected. All requests to this server are allowed.

Domain Mappings for Cookies

Some HTTP servers return cookies which contain a "domain" attribute. On further requests, HTTP clients should send these cookies to machines whose host names lie in the specified domain.

356P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 357: Hana Cloud

For example, if the client receives a cookie such as the following:

Set-Cookie: cookie-field=some-value; domain=intranet.corp; path=...; ...

it will return that cookie in follow-up requests to all hosts such as machine1.intranet.corp, machine2.intranet.corp, and so on, if other attributes such as "path" or "attribute" require it.

However, in the setup with the Cloud connector between the client and a Web server, this may pose some problems. For instance, assume that you have defined a virtual host www1.sales.cloud and mapped it to the internal host name machine1.intranet.corp. Then, the client "thinks" it is sending an HTTP request to the host name www1.sales.cloud, while the Web server, unaware of the above host name mapping, sets a cookie for the domain intranet.corp. The client does not know this domain name and thus, for the next request to that Web server, it will not attach the cookie, even though it should.

To resolve this problem, choose Access Control Domain Mapping and define a mapping as follows:

This way, the Cloud connector will check the Web server's response for "Set-Cookie" headers, and if it finds one with an attribute domain=intranet.corp, it will replace it with domain=sales.cloud before returning the HTTP response to the client. Then, the client recognizes the domain name, and for the next request against www1.sales.cloud it will attach the cookie, which will then successfully arrive at the server on machine1.intranet.corp.

NoteSome Web servers use a syntax such as "domain=.intranet.corp" (RFC 2109), even though the newer RFC 6265 recommends using the notation without a dot.

NoteAlso bear in mind that the value of the domain attribute may be a simple host name. In this case, no extra domain mapping is necessary on the Cloud connector. If the server sets a cookie with "domain=machine1.intranet.corp", the Cloud connector will automatically reverse the mapping machine1.intranet.corp to www1.sales.cloud and replace the cookie domain accordingly.

Related LinksTutorial: Using On-Premise Back-End Services in Cloud Applications [page 364]

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 357

Page 358: Hana Cloud

1.3.5.3.3 Tutorials

Overview

SAP HANA Cloud connectivity service allows a secure, reliable, and easy-to-consume access to remote services running either on the Internet or in an on-premise network.

Use Cases

The tutorials in this section show how you can make connections to Internet services and on-premise networks:

Tutorial: Using Internet Services in Cloud Applications [page 358]

Tutorial: Using On-Premise Back-End Services in Cloud Applications [page 364]

Tutorial: Using Internet Services in Cloud Applications

Overview

This step-by-step tutorial demonstrates consumption of Internet services using Apache HTTP Client. This tutorial also shows how a connectivity-enabled Web application can be deployed on a local server and on SAP HANA Cloud.

Installation Prerequisites

You have downloaded and set up your Eclipse IDE, SAP HANA Cloud Tools for Java and SAP HANA SDK.

For more information, see Setting Up the Tools and SDK [page 27] and Updating the Tools and SDK [page 34]

Creating a Dynamic Web Project

1. Open the Java EE perspective of the Eclipse IDE.

2. In the Project Explorer view, from the context menu, choose New Dynamic Web Project .3. Enter WeatherDemoApp as the Project name.

358P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 359: Hana Cloud

4. Make sure that SAP HANA Cloud is selected as the target runtime.5. In the Configuration dropdown menu, select Default Configuration for SAP HANA Cloud.6. Choose Finish to finalize the creation of your project.

Creating a Sample Servlet

1. From the WeatherDemoApp context menu, choose New Servlet .2. Enter weather.demo as the Java package and WeatherServlet as the Class name and choose Next.3. In the URL mappings field, select /WeatherServlet and choose Edit.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 359

Page 360: Hana Cloud

4. In the Pattern field, replace the current value with just "/". In this way, the servlet will be mapped as a welcome page for the application.

5. Choose Finish so that the WeatherServlet.java servlet is created and opened in the Java editor.

6. Go to WeatherDemoApp WebContent WEB-INF and open the web.xml file.7. Add the following code block to the <web-app> element:

<resource-ref> <res-ref-name>weather</res-ref-name> <res-type>com.sap.core.connectivity.api.http.HttpDestination</res-type></resource-ref>

NoteThe value of the <res-ref-name> element in the web.xml file should match the name of the destination that you want to be retrieved at runtime. In this case, the destination name is weather.

8. Replace the entire servlet class with the following sample code:

package weather.demo;

import java.io.IOException;import javax.naming.Context;import javax.naming.InitialContext;import javax.naming.NamingException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.conn.ClientConnectionManager;import org.apache.http.util.EntityUtils;

import com.sap.core.connectivity.api.DestinationException;import com.sap.core.connectivity.api.http.HttpDestination;

/** * Servlet implementation class WeatherServlet */public class WeatherServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public WeatherServlet() { super();

360P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 361: Hana Cloud

}

/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpDestination destination; try { // access the HttpDestination for the resource "weather" specified in the web.xml Context ctx = new InitialContext(); destination = (HttpDestination) ctx.lookup("java:comp/env/weather"); } catch (NamingException e) { throw new RuntimeException(e); } HttpClient client; try { client = destination.createHttpClient(); } catch (DestinationException e) { throw new RuntimeException(e); } try { //Create get request HttpGet get = new HttpGet("forecastrss?p=BUXX0005&u=c");

//Execute the request HttpResponse resp = client.execute(get);

//Process the response HttpEntity entity = resp.getEntity(); String respToString = EntityUtils.toString(entity); response.setContentType("text/html"); response.getWriter().print(respToString);

} finally { ClientConnectionManager connectionManager = client.getConnectionManager(); if (connectionManager != null) { connectionManager.shutdown(); } } }

/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { }

}

9. Save the Java editor.The project compiles without errors.

You have successfully created a Web application containing a sample servlet and connectivity functionality.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 361

Page 362: Hana Cloud

Testing the Connectivity-Enabled Web Application on SAP HANA Cloud Local Runtime

1. In the context menu of the Servers view, choose New Server .2. Choose SAP HANA Cloud local runtime as the type of server you want to create and then choose Finish.3. A new server <SAP HANA Cloud local runtime [Stopped]> appears on the Servers tab page.

Also, a Servers folder is created and appears in the navigation tree of the IDE. It contains configurable folders and files you can use, for example, to change your HTTP or JMX ports.

4. If you work behind a proxy server, you need to configure your proxy setting as follows:

○ In the Servers view, double-click the added server to open the editor.○ Click the Open Launch Configuration link.○ Choose the (x)=Arguments tab page.○ In the VM Arguments box, add the following row:

-Dhttp.proxyHost=<your_proxy_host> -Dhttp.proxyPort=<your_proxy_port> -Dhttps.proxyHost=<your_proxy_host> -Dhttps.proxyPort=<your_proxy_port>

○ Choose OK.5. Go to the Connectivity tab page of your SAP HANA Cloud local runtime, create a destination with the name

weather, and configure it so it can be consumed by the application at runtime. For more information, see Configuring Destinations from the Eclipse IDE [page 307].For the sample destination to work properly, the following properties need to be configured:

Name=weather Type=HTTP URL=http://weather.yahooapis.com Authentication=NoAuthentication

6. From the WeatherServlet.java editor's context menu, choose Run As Run on Server .7. Make sure that the Choose an existing server option is selected and choose SAP HANA Cloud local runtime.8. Choose Finish.9. The server is now started, displayed as <SAP HANA Cloud local runtime [Started,

Synchronized]> in the Servers view.

The Internal Web Browser opens with the expected output of the connectivity-enabled Web application.

Deploying the Connectivity-Enabled Web Application on SAP HANA Cloud

1. In the context menu of the Servers view, choose New Server .2. Choose SAP HANA Cloud as the type of server you want to create and choose Next.3. For Server's host name, specify the landscape host depending on your account type: for customer and

partner accounts, use hana.ondemand.com and for trial accounts, use hanatrial.ondemand.com.4. Choose Next.5. On the New Server wizard page, enter your application and account name. Note that only lowercase Latin

letters and digits are allowed.

362P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 363: Hana Cloud

NoteThe application name should be unique enough to allow your deployed application to be easily identified in SAP HANA Cloud Cockpit.

6. Enter your account name, e-mail or user name, and password.

Note○ The name of your account comprises your SCN user ID and the suffix trial, for example,

p1234567trial.○ Developer accounts are intended for personal exploration, and not for use in a production environment

or for team development. You cannot assign members to the account (you will not see the Members list normally available).

○ A developer account has only one virtual machine (VM) at its disposal. You can deploy multiple applications, but you can start only one application at any one time.

○ When deploying to the cloud, remember to use the SAP HANA Cloud landscape host hanatrial.ondemand.com.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 363

Page 364: Hana Cloud

7. Choose Finish.8. A new server <<application>.<account> [Stopped]> appears in the Servers view.9. Go to the Connectivity tab page of the server, create a destination with the name weather, and configure it

using the following properties:

Name=weather Type=HTTP URL=http://weather.yahooapis.com Authentication=NoAuthenticationProxyType=Internet

10. From the WeatherServlet.java editor's context menu, choose Run As Run on Server .

11. Make sure that the Choose an existing server option is selected and choose <Server_host_name><Server_name> .

12. Choose Finish.13. The Internal Web Browser opens with the URL pointing to SAP HANA Cloud and displaying the expected

output of the connectivity-enabled Web application.

Next Step

You can monitor the state and logs of your Web application deployed on SAP HANA Cloud by using the cockpit.

For more information, see SAP HANA Cloud Cockpit [page 50].

Tutorial: Using On-Premise Back-End Services in Cloud Applications

Overview

This step-by-step tutorial demonstrates how a sample Web application consumes a back-end system via HTTP(S) by using SAP HANA Cloud connectivity service. For simplicity, instead of using a real back-end service, we use a second sample Web application containing a "Ping" servlet, which mimics the back-end service and can be called via HTTP(S).

The tutorial guides you through the following:

1. Installation prerequisites2. Setting the "Ping" back-end service used in the tutorial3. Developing a sample Web application that uses SAP HANA Cloud connectivity service to consume the "Ping"

back-end service.

364P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 365: Hana Cloud

Connectivity User Roles

In the on-demand to on-premise connectivity end-to-end scenario, different user roles are involved. The particular steps for the relevant roles are described below:

● IT Administrator - Sets up and configures SAP HANA Cloud connector. Scenario steps:

1. Downloads SAP HANA Cloud connector from https://tools.hana.ondemand.com/#cloud2. Installs the connector.3. Establishes an SSL tunnel from the connector to an SAP HANA Cloud account.4. Configures the exposed back-end services and resources.

● Application Developer - Develops Web applications using destinations. Scenario steps:

1. Installs the Eclipse IDE, SAP HANA Cloud Tools for Java and SAP HANA Cloud SDK.2. Develops a Java EE application using the destination API.3. Configures connectivity destinations as resources in the web.xml file.4. Configures connectivity destinations via the SAP HANA Cloud server adapter in Eclipse IDE.5. Deploys and tests the Java EE application on SAP HANA Cloud and SAP HANA Cloud local runtime.

● Account Operator - Deploys Web applications, configures their destinations, and conducts tests. Scenario steps:

1. Obtains a ready Java EE application WAR file.2. Deploys the Java EE application to an SAP HANA Cloud account.3. Uploads the connectivity destination configuration via SAP HANA Cloud console client.4. Tests the Java EE application on SAP HANA Cloud local runtime and deploys it again to the SAP HANA

Cloud account.

Installation Prerequisites

● You have downloaded and set up your Eclipse IDE, SAP HANA Cloud Tools for Java and SAP HANA SDK.For more information, see Setting Up the Tools and SDK [page 27] and Updating the Tools and SDK [page 34]

● You have downloaded and configured SAP HANA Cloud connector. For more information, see Using the Cloud Connector [page 319].

Setting Up the "Ping" Application as a Back-End Service

This tutorial uses a Web application that responds to a request with a ping as a sample back-end system. SAP HANA Cloud connectivity service currently supports HTTP and HTTPS as protocols and provides an easy way to consume REST-based Web services.

Instead of the sample back-end service provided in this tutorial, you can use also other services that can be consumed through REST-based Web services.

To set up the sample "Ping" application as a back-end service, see Setting Up a Ping Application as a Sample Back-End Service [page 372].

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 365

Page 366: Hana Cloud

Once the "Ping" application is running on your local Tomcat, you need to configure the ping service, provided by the application, in your installed SAP HANA Cloud connector. This is required since the connector only allows access to white-listed back-end services. To do this, follow the steps below:

1. In the SAP HANA Cloud connector administration UI, go to the Access Control tab page.2. Add a new system under the list of defined resources. Under Mapping Virtual To Internal System, choose the

Add button and define an entry as shown in the following screenshot. The Internal Host must be the physical host name of the machine on which the Tomcat of the "Ping" application is running.

3. For the specified internal system, specify the URL paths /PingAppHttpBasicAuth and /PingAppHttpNoAuth as accessible resources as shown in the screenshot below. Make sure that you have selected the Path and all sub-paths option when defining the paths.

Creating a Dynamic Web Project

1. Open the Java EE perspective of the Eclipse IDE.

2. On the Project Explorer view, from the context menu, choose New Dynamic Web Project .3. Enter ConnectivityHelloWorld as the Project name.4. Make sure that SAP HANA Cloud is set as the target runtime.5. In the Configuration dropdown menu, select Default Configuration for SAP HANA Cloud.6. Choose Finish to finalize the creation of your project.

366P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 367: Hana Cloud

Creating a Sample Servlet

1. From the ConnectivityHelloWorld context menu, choose New Servlet .2. Enter hello as the Java package and ConnectivityHelloWorld as the Class name and choose Next.3. In the URL mappings field, select /ConnectivityHelloWorld and choose Edit.4. In the Pattern field, replace the current value with just "/". In this way, the servlet will be mapped as a welcome

page for the application.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 367

Page 368: Hana Cloud

5. Choose Finish so that the ConnectivityHelloWorld.java servlet is created and opened in the Java editor.

6. Go to ConnectivityHelloWorld WebContent WEB-INF and open the web.xml file.7. Add the following code block to the <<web-app>> element:

<resource-ref> <res-ref-name>pingdest</res-ref-name> <res-type>com.sap.core.connectivity.api.http.HttpDestination</res-type> </resource-ref>

Note○ This defines pingdest as a resource that can be looked up in the application via JNDI registry. Note that

the mapped_name element under <resource-ref> is not supported.○ The value of the <res-ref-name> element in the web.xml file should match the name of the destination

that you want to be retrieved at runtime. In this case, the destination name is pingdest.

8. Replace the entire servlet class to make use of the destination API. The destination API is visible by default for SAP HANA Cloud applications and must not be added explicitly to the application class path.

package hello;

import java.io.IOException;

import javax.naming.Context;import javax.naming.InitialContext;import javax.naming.NamingException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.util.EntityUtils;

import com.sap.core.connectivity.api.DestinationException;import com.sap.core.connectivity.api.http.HttpDestination;

/** * Sample application that uses the SAP HANA Cloud connectivity service. * * Note: The API of the connectivity service is located under * <code>com.sap.core.connectivity.api</code>. The old API under * <code>com.sap.core.connectivity.httpdestination.api</code> has been deprecated. */public class ConnectivityHelloWorld extends HttpServlet {

368P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 369: Hana Cloud

private static final long serialVersionUID = 1L;

/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

try { // access the HttpDestination for the resource "pingdest" specified in the web.xml Context ctx = new InitialContext(); HttpDestination destination = (HttpDestination) ctx.lookup("java:comp/env/pingdest"); HttpClient createHttpClient = destination.createHttpClient();

// make a GET-request to the backend; // for basic authentication use HttpGet get = new HttpGet("pingbasic"); HttpGet get = new HttpGet("pingnoauth"); HttpResponse resp = createHttpClient.execute(get); HttpEntity entity = resp.getEntity(); String respToString = EntityUtils.toString(entity); int statusCode = resp.getStatusLine().getStatusCode();

response.getWriter().println("Status code: " + statusCode); response.getWriter().println("Response: " + respToString);

} catch (DestinationException e) { throw new RuntimeException(e); } catch (NamingException e) { throw new RuntimeException(e); }

}

/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub }

}

9. Save the Java editor and make sure that the project compiles without errors.

Deploying the Application

1. To deploy your Web application on SAP HANA Cloud local runtime or SAP HANA Cloud, follow the steps described in the respective pages:Deploying Locally from Eclipse IDE [page 533]Deploying on the Cloud from Eclipse IDE [page 535]

2. Once the application is deployed successfully on SAP HANA Cloud local runtime and on SAP HANA Cloud, the application issues an exception saying that the pingdest destination has not been specified yet:

HTTP Status 500 -

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 369

Page 370: Hana Cloud

type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

java.lang.RuntimeException: javax.naming.NamingException: Error while attempting to resolve reference [Root exception is javax.naming.NamingException: Cannot create resource object instance due to exception in the object factory [Root exception is com.sap.core.connectivity.api.DestinationException: com.sap.security.destinations.ConfigurationException: Destination with name pingdest cannot be found. Make sure it is created and configured.]] hello.ConnectivityHelloWorld.doGet(ConnectivityHelloWorld.java:65) javax.servlet.http.HttpServlet.service(HttpServlet.java:735) javax.servlet.http.HttpServlet.service(HttpServlet.java:848) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) java.lang.reflect.Method.invoke(Method.java:597) org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:274) org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:271) java.security.AccessController.doPrivileged(Native Method) javax.security.auth.Subject.doAsPrivileged(Subject.java:517) org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:306) org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:166)

3. As a next step, you need to configure the pingdest destination.

Configuring the Destination in SAP HANA Cloud

To configure the destination in SAP HANA Cloud, you need to use the virtual host name (virtualpingbackend) and port (1234) specified in one of the previous steps on the SAP HANA Cloud connector's Access Control tab page.

1. In the Eclipse IDE, open the Servers view and double-click on <<application>.<account>> to open the SAP HANA Cloud server editor.

2. Open the Connectivity tab page.

3. In the All Destinations section, choose to create a new destination with the name pingdest.

○ When connecting with no authentication, use the following properties:

Name=pingdestType=HTTP URL=https://virtualpingbackend:1234/PingAppHttpNoAuth/Authentication=NoAuthenticationProxyType=OnPremise

370P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 371: Hana Cloud

○ To connect with basic authentication, use the following configuration:

Name=pingdest Type=HTTPURL=https://virtualpingbackend:1234/PingAppHttpBasicAuth/Authentication=BasicAuthenticationUser=pinguserPassword=pingpasswordProxyType=OnPremise

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 371

Page 372: Hana Cloud

4. Save the destination.5. The Connectivity editor automatically saves the configuration in SAP HANA Cloud.6. Call the URL that references the SAP HANA Cloud application again in the Web browser. The application

should now return the ping response.

Next Step

You can monitor the state and logs of your Web application deployed on SAP HANA Cloud using the cockpit.

For more information, see SAP HANA Cloud Cockpit [page 50].

Setting Up a Ping Application as a Sample Back-End Service

Overview

This section describes how you set up a simple "Ping" Web application that is used as a dummy back-end service.

372P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 373: Hana Cloud

Prerequisites

You have downloaded SAP HANA Cloud SDK on your local file system.

Procedure

1. Set up a servlet container such as Tomcat.2. Add a user and role for basic authentication by adding the following lines to thetomcat-users.xml file in

directory <TOMCAT_HOME>/conf file:

<role rolename="pingrole"/><user name="pinguser" password="pingpassword" roles="pingrole" />

3. From the SDK location, go to /tools/examples/connectivity/onpremise, copy files PingAppHttpNoAuth.war and PingAppHttpBasicAuth.war and paste them into the <TOMCAT_HOME>/webapps directory.

4. Start Tomcat and access the on-premise applications at the URLs below. Use pinguser / pingpassword as the credentials:http://localhost:8080/PingAppHttpNoAuth/pingnoauthhttp://localhost:8080/PingAppHttpBasicAuth/pingbasic

Related LinksTutorial: Using On-Premise Back-End Services in Cloud Applications [page 364]

1.3.5.4 Invoking ABAP Function Modules via RFC Protocol

Installation Prerequisites

● To provide connectivity tunnel via RFC destinations, your Cloud connector version needs to be at least 1.3.0.● To develop a JCo application, your SDK version needs to be at least 1.29.18. Also, your SDK local runtime

needs to be hosted by a 64-bit JVM.On Windows platforms, you need to install Microsoft Visual C++ 2010 Redistributable Package (x64). To download this package, go to http://www.microsoft.com/en-us/download/details.aspx?id=14632.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 373

Page 374: Hana Cloud

Consuming Connectivity via RFC

You can call a service from a fenced customer network using a simple application which consumes a simple on-premise remotely-enabled function module.

The invocation of function modules via RFC is offered via the JCo API like the one available in SAP NetWeaver Application Server Java since version 7.10, and in JCo standalone 3.0. If you are an experienced JCo developer, you can easily develop a Web application using JCo: you simply consume the APIs like you do in other Java environments. Restrictions that apply in the SAP HANA Cloud environment are mentioned in the section below.

To see a sample Web application, see Tutorial: Invoking ABAP Function Modules in On-Premise ABAP Systems [page 384].

Configuring Connectivity via RFC

● Configuring applications to use RFC destinations.For more information, see Configuring Destinations from the Console Client [page 315] and RFC Destinations [page 374].

● Configuring connectivity between a customer system and an on-demand application. You need to install SAP HANA Cloud connector in your internal network and then configure it to expose a remotely-enabled function module in an on-premise ABAP system.For more information, see Configuring the Cloud Connector for RFC [page 380].

Restrictions

● JCoServer functionality cannot be used within SAP HANA Cloud.● Environment embedding, such as that offered by JCo standalone 3.0, is not possible. This is, however, similar

to SAP NetWeaver AS Java.● Currently, a stateful sequence of function module invocations needs to occur in a single HTTP request/

response cycle.● Initially, only a logon with user/password credentials is supported.● The supported set of configuration properties is restricted. For more information, see RFC Destinations [page

374].

1.3.5.4.1 RFC Destinations

374P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 375: Hana Cloud

Overview

RFC destinations provide the configuration needed for communicating with an on-premise ABAP system via RFC. The RFC destination data is used by the JCo version that is offered within SAP HANA Cloud to establish and manage the connection.

RFC Destination Properties

The RFC destination specific configuration in SAP HANA Cloud consists of properties arranged in groups, as described below. The supported set of properties is a subset of the standard JCo properties in arbitrary environments. The configuration data is divided into the following groups:

● User logon properties● Physical connection● Special parameters● Pooling configuration● Repository configuration

The minimal configuration contains user logon properties and information identifying the target host. This means you must at least provide a set of properties containing this information.

Example

Name=SalesSystemType=RFCjco.client.client=000jco.client.lang=ENjco.client.user=consultantjco.client.passwd=<password>jco.client.ashost=sales-system.cloudjco.client.sysnr=42jco.destination.pool_capacity=5jco.destination.peak_limit=10

User Logon Properties

This group of JCo properties covers different types of user credentials, as well as the ABAP system client and the logon language. The currently supported logon mechanism uses user/password as the credentials.

Property Description

jco.client.client Represents the client to be used in the ABAP system. Valid format is a three-digit number.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 375

Page 376: Hana Cloud

Property Description

jco.client.lang Optional property. Represents the logon language. If the property is not provided, the user's or system's default language is used. Valid values are two-character ISO language codes or one-character SAP language codes.

jco.client.user Represents the user to be used for logging on to the ABAP system.

jco.client.passwd Represents the password of the user that shall be used. Note that passwords in systems of SAP NetWeaver releases lower than 7.0 are case-insensitive and can be only eight characters long. For releases 7.0 and higher, passwords are case-sensitive with a maximum length of 40.

Target System Configuration

Overview

Two types of configurations exist that can be used alternatively:

● Direct connection to an ABAP application server;● Load balancing connection to a group of ABAP application servers via a message server.

Depending on the configuration used, different properties are considered mandatory or optional.

Direct Connection Configuration

Property Description

jco.client.ashost Represents the application server host to be used. In the case of configurations in SAP HANA Cloud, this property needs to match a virtual host entry in the Cloud connector Access Control configuration. The existence of this property signals that a direct connection shall be established.

jco.client.sysnr Represents the so-called "system number" and has two digits. It identifies the logical port on which the application server is listening for incoming requests. In

376P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 377: Hana Cloud

Property Description

the case of configurations in SAP HANA Cloud, this property needs to match a virtual port entry in the Cloud connector Access Control configuration.

NoteThe virtual port in the above access control entry needs to be named <sapgw##>, where <<##>> is the value of sysnr.

Load Balancing Configuration

Property Description

jco.client.mshost Represents the message server host to be used. In the case of configurations in SAP HANA Cloud, this property needs to match a virtual host entry in the Cloud connector Access Control configuration. The existence of this property signals that a load balancing connection shall be established.

jco.client.group Optional property. Identifies the group of application servers that shall be used, the so-called "logon group". If the property is not specified, the group PUBLIC will be used.

jco.client.r3name Represents the three-character system ID of the ABAP system to be addressed. In the case of configurations in SAP HANA Cloud, this property needs to match a virtual port entry in the Cloud connector Access Control configuration.

NoteThe virtual port in the above access control entry needs to be named <sapms###>, where <<###>> is the value of r3name.

jco.client.msserv Represents the port on which the message server is listening for incoming requests. This property can be used as an alternative to jco.client.r3name. One of these two needs to be present. In the case of configurations in SAP HANA Cloud, this property needs to match a virtual port entry in the Cloud connector Access Control configuration. You can therefore avoid

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 377

Page 378: Hana Cloud

Property Description

lookups in the etc / services file on the Cloud connector host.

Parameters Influencing Communication Behavior

This group of JCo properties allows you to influence the connection to an ABAP system. All properties are optional.

Property Description

jco.client.trace Defines whether protocol traces shall be created. Valid values are 1 (trace is on) and 0 (trace is off). The default value is 0.

jco.client.codepage Declares the 4-digit SAP codepage that shall be used when initiating the connection to the backend. The default value is 1100 (comparable to iso-8859-1). It is important to provide this property if the password that is used contains characters that cannot be represented in 1100.

jco.client.delta Enables/disables table parameter delta management. It is enabled if set to 1 (default value), and respectively disabled if set to 0.

Pooling Configuration

Overview

This group of JCo properties covers different settings for the behavior of pooling for connections. All properties are optional.

Property Description

jco.destination.pool_capacity Represents the maximum number of idle connections kept open by the destination. A value of 0 has the effect of no connection pooling, that is, connections will be closed after each request. The default value is 1.

378P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 379: Hana Cloud

Property Description

jco.destination.peak_limit Represents the maximum number of active connections that can simultaneously be created for a destination.

jco.destination.max_get_client_time Represents the maximum time in milliseconds to wait for a connection, if the maximum number of active connections is already allocated by applications.

jco.destination.expiration_time Represents the time in milliseconds after which idle connections that are available in the pool can be closed.

jco.destination.expiration_check_period Represents the interval in milliseconds within which the timeout checker thread checks the idle connections in the pool for expiration.

Pooling Details

● Each destination is associated with a connection factory and, if the pooling feature is used, with a connection pool.

● Initially, the destination's connection pool is empty, and the JCo runtime does not preallocate any connection. The first connection will be created when the first function module invocation is performed. The peak_limit property describes how many connections can be created simultaneously, if applications allocate connections in different sessions at the same time. A connection is allocated either when a stateless function call is executed, or when a connection for a stateful call sequence is reserved within a session.

● After the <<peak_limit>> number of connections has been allocated (in <<peak_limit>> number of sessions), the next session will wait for at most <<max_get_client_time>> milliseconds until a different session releases a connection (either finishes a stateless call or ends a stateful call sequence). In case the waiting session does not make a connection during the <<max_get_client_time>> period, the function request will be aborted with JCoException with the key JCO_ERROR_RESOURCE.

● Connections that are no longer used by applications are returned to the destination pool. There are at most <<pool_capacity>> number of connections kept opened by the pool. Further connections (<<peak_limit>> - <<pool_capacity>>) will be closed immediately after usage. The pooled connections (opened connections in the pool) are marked as expired if they are not used again during <<expiration_time>> milliseconds. All expired connections will be closed by a timeout checker thread which executes the check every <<expiration_check_period>> milliseconds.

Repository Configuration

This JCo properties group allows you to influence how the repository that dynamically retrieves function module metadata behaves. All properties below are optional. Alternatively, applications could create their metadata in their code, using the metadata factory methods within the JCo class, to avoid additional round-trips to the on-premise system.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 379

Page 380: Hana Cloud

Property Description

jco.destination.repository_destination Specifies which destination should be used for repository queries. If the destination does not exist, an error occurs when trying to retrieve the repository. Defaults to itself.

jco.destination.repository.user Optional property. If this property is set, and the repository destination is not set, it will be used as the user for repository queries. This case allows a different user to be used for repository lookups and restricts that user's permissions accordingly.

jco.destination.repository.passwd Represents the password for a repository user. The property is mandatory if a repository user is used.

1.3.5.4.2 Configuring the Cloud Connector for RFC

Overview

This section helps you to configure your SAP HANA Cloud connector when you are working via the RFC protocol.

Related LinksInitial Configuration (RFC) [page 380]

Access Control Configuration (RFC) [page 381]

Initial Configuration (RFC)

SNC Configuration for Mutual Authentication

To set up a mutual authentication between SAP HANA Cloud connector and an ABAP back-end system (connected via RFC), you can configure SNC for the Cloud connector. It will then use the associated PSE for all RFC SNC requests. This means that the SNC identity, represented by this PSE needs to:

● Be trusted by all back-end systems to which the Cloud connector is supposed to connect;● Play the role of a trusted external system, by adding the SNC name of the Cloud connector to the

SNCSYSACL table. You can find more details in the SNC configuration documentation for the release of your ABAP system.

380P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 381: Hana Cloud

Configuration Parameters

● Library Name: Provides the location of the SNC library you are using for the Cloud connector. Bear in mind that you must use one and the same library name on both sides of the communication.

● My Name: The SNC name that identifies the Cloud connector. It represents a valid scheme for the SNC implementation that is used.

● Quality of Protection (QoP): Determines the level of protection that you require for the connectivity to the ABAP systems.

Access Control Configuration (RFC)

Exposing Intranet Systems

To allow your on-demand applications to access a certain back-end system on the intranet, you need to insert an extra line within the access control management of the Cloud connector.

1. Go to the Access Control tab page.2. Choose Add.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 381

Page 382: Hana Cloud

○ Virtual Host: Specifies the host name exactly as it is specified as the jco.client.ashost or jco.client.mshost property in the RFC destination configuration in SAP HANA Cloud. The Internal Host specifies the actual host under which the target system can be reached within the intranet. The virtual host can be a fake name, but the internal host needs to be an existing network address that can be resolved on the intranet from the Cloud connector machine.

○ Virtual Port: Allows you to distinguish between different entry points of your back-end system. For example, sapgw42 for application server logon and sapmsPRD for a message server logon. The value specifies the port as the logical name. In the case of application server logon, the value is specified as <<sapgw##>>, where <##> is the value of the jco.client.sysnr RFC destination property. In the case of message server logon, it is <<sapms###>>, where <###> is the value of the jco.client.r3name property in the RFC destination configuration in SAP HANA Cloud.

NoteIf you leave the Internal Host/Port fields blank, the Cloud connector will try to forward the request to the network address specified by Virtual Host and Virtual Port. In this case, the "virtual" address must be real.

○ Protocol: You need to choose whether the Cloud connector should use RFC or RFC with SNC for connecting to the back-end system.Note that this is completely independent from the settings on the SAP HANA Cloud side. This way, you are ensured that the entire connection from the on-demand application to the actual back-end system (provided through the SSL tunnel) is secured, partly with SSL and partly with SNC.

Note○ The back-end needs to be properly configured to support SNC connections.○ SNC configuration has to be provided in the Cloud connector.

For more information, see Initial Configuration (RFC) [page 380].○ Back-end Type: You need to select the description that best matches the addressed back-end system.

With RFC, only the ABAP System is a suitable value, which means usage of RFC is free of charge.

382P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 383: Hana Cloud

NoteYou can later edit such a system mapping to make the Cloud connector route the requests for sales-system.cloud:sapgw42 to a different back-end system. This can be useful if the system is currently down and there is a back-up system that can serve these requests in the meantime. However, you cannot edit the virtual name of this system mapping. If you want to use a different fictional host name in your on-demand application, you need to delete the mapping and create a new one.

3. After saving the hostname mapping, you can trigger a ping from the Cloud connector to the internal host, using the Check button.This allows you to make sure the Cloud connector can indeed access the internal system, and allows you to catch basic issues such as spelling mistakes or firewall problems between the Cloud connector and the internal host.

4. If the ping to the internal host is successful, the Cloud connector displays a green icon. If it fails, the icon is a red exclamation mark.

Limiting the Accessible Resources for RFC

In addition to allowing access to a particular host and port, you also need to specify which function modules (Resources) may be invoked on that host. The Cloud connector uses very strict whitelists for its access control, so only those function modules for which you explicitly granted access are allowed. All other RFC requests are denied by the Cloud connector.

1. To define the permitted function modules (Resources) for a particular back-end system, choose the row corresponding to that back-end system. A dialog appears, prompting you to enter the specific function module name whose invoking you want to allow.

2. The Cloud connector checks that the function module name of an incoming request is exactly as specified in the configuration. If it is not, the request is denied.

3. If you select the Prefix option, the Cloud connector allows all incoming requests for which the function module name begins with the specified string.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 383

Page 384: Hana Cloud

4. The Enabled checkbox allows you to specify whether that resource should be initially enabled or disabled.

1.3.5.4.3 Tutorial: Invoking ABAP Function Modules in On-Premise ABAP Systems

Context

This step-by-step tutorial shows how a sample Web application invokes function module in an on-premise ABAP system via RFC, by using the connectivity service.

The tutorial guides you through the following sections:

● Presenting the user roles● Defining the installation prerequisites● Developing a sample Web application that uses the connectivity service to consume the simple function

module STFC_CONNECTION.

Connectivity User Roles

Different user roles are involved in the on-demand to on-premise connectivity end-to-end scenario. The particular steps for the relevant roles are described below:

IT Administrator

This role sets up and configures SAP HANA Cloud connector. Scenario steps:

1. Downloads SAP HANA Cloud connector from https://tools.hana.ondemand.com/#cloud2. Installs the connector.3. Establishes an SSL tunnel from the connector to an SAP HANA Cloud account.4. Configures the exposed back-end services and resources.

Application Developer

This role develops Web applications using destinations. Scenario steps:

1. Installs the Eclipse IDE, SAP HANA Cloud Tools for Java and SAP HANA Cloud SDK.2. Develops a Java EE application using the destination API.

384P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 385: Hana Cloud

3. Configures connectivity destinations as resources in the web.xml file.4. Configures connectivity destinations via the SAP HANA Cloud server adapter in Eclipse IDE.5. Deploys and tests the Java EE application on SAP HANA Cloud and SAP HANA Cloud local runtime.

Account Operator

This role deploys Web applications, configures their destinations, and conducts tests. Scenario steps:

1. Obtains a ready Java EE application WAR file.2. Deploys the Java EE application to an SAP HANA Cloud account.3. Uploads the connectivity destination configuration via SAP HANA Cloud console client.4. Tests the Java EE application on SAP HANA Cloud local runtime and deploys it again to the SAP HANA Cloud

account.

Installation Prerequisites

● You have downloaded and set up your Eclipse IDE and SAP HANA Cloud Tools for Java.● You have downloaded the SDK. Its version needs to be at least 1.29.18.● Your SDK local runtime needs to be hosted by a 64-bit JVM. On Windows platforms, you need to install

Microsoft Visual C++ 2010 Redistributable Package (x64).● You have downloaded and configured your Cloud connector. Its version needs to be at least 1.3.0.

To download the SAP tools, go to https://tools.hana.ondemand.com/#cloud.

To download the Microsoft Visual C++ package, go to http://www.microsoft.com/en-us/download/details.aspx?id=14632.

To read the installation documentation, go to Setting Up the Tools and SDK [page 27] and Installing the Cloud Connector [page 320].

Creating a Dynamic Web Project

Procedure

1. Open the Java EE perspective of the Eclipse IDE.

2. On the Project Explorer view, from the context menu, choose New Dynamic Web Project .3. Enter jco_demo as the Project name.

4. Make sure that SAP HANA Cloud is set as the target runtime.5. In the Configuration dropdown menu, select Default Configuration for SAP HANA Cloud.6. Choose Finish to complete the creation of your project.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 385

Page 386: Hana Cloud

Creating a Sample Servlet

Procedure

1. From the jco_demo context menu, choose New Servlet .2. Enter com.sap.demo.jco as the Java package and ConnectivityRFCExample as the Class name and

choose Next.3. Choose Finish so that the ConnectivityRFCExample.java servlet is created and opened in the Java editor.

4. Go to ConnectivityHelloWorld WebContent WEB-INF and open the web.xml file.5. Replace the entire servlet class to make use of the JCo API. The JCo API is visible by default for SAP HANA

Cloud applications and must not be added explicitly to the application class path.

package com.sap.demo.jco;

import java.io.IOException;import java.io.PrintWriter;

import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

import com.sap.conn.jco.AbapException;import com.sap.conn.jco.JCoDestination;import com.sap.conn.jco.JCoDestinationManager;import com.sap.conn.jco.JCoException;import com.sap.conn.jco.JCoFunction;import com.sap.conn.jco.JCoParameterList;import com.sap.conn.jco.JCoRepository;

/** * Sample application that uses the SAP HANA Cloud connectivity service. In particular, * it makes use of the capability to invoke a function module in an ABAP system * via RFC * * Note: The JCo APIs are available under <code>com.sap.conn.jco</code>. */public class ConnectivityRFCExample extends HttpServlet{ private static final long serialVersionUID = 1L;

public ConnectivityRFCExample() { }

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter responseWriter = response.getWriter(); try { // access the RFC Destination "JCoDemoSystem" JCoDestination destination=JCoDestinationManager.getDestination("JCoDemoSystem");

386P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 387: Hana Cloud

// make an invocation of STFC_CONNECTION in the backend; JCoRepository repo=destination.getRepository(); JCoFunction stfcConnection=repo.getFunction("STFC_CONNECTION");

JCoParameterList imports=stfcConnection.getImportParameterList(); imports.setValue("REQUTEXT", "SAP HANA Cloud connectivity runs with JCo"); stfcConnection.execute(destination); JCoParameterList exports=stfcConnection.getExportParameterList(); String echotext=exports.getString("ECHOTEXT"); String resptext=exports.getString("RESPTEXT"); response.addHeader("Content-type", "text/html"); responseWriter.println("<html><body>"); responseWriter.println("<h1>Executed STFC_CONNECTION in system JCoDemoSystem</h1>"); responseWriter.println("<p>Export parameter ECHOTEXT of STFC_CONNECTION:<br>"); responseWriter.println(echotext); responseWriter.println("<p>Export parameter RESPTEXT of STFC_CONNECTION:<br>"); responseWriter.println(resptext); responseWriter.println("</body></html>"); } catch (AbapException ae) { //just for completeness: As this function module does not have an exception //in its signature, this exception cannot occur. However,you should always //take care of AbapExceptions } catch (JCoException e) { response.addHeader("Content-type", "text/html"); responseWriter.println("<html><body>"); responseWriter.println("<h1>Exception occurred while executing STFC_CONNECTION in system JCoDemoSystem</h1>"); responseWriter.println("<pre>"); e.printStackTrace(responseWriter); responseWriter.println("</pre>"); responseWriter.println("</body></html>"); } }}

6. Save the Java editor and make sure that the project compiles without errors.

Deploying the Application

Procedure

1. To deploy your Web application on SAP HANA Cloud local runtime and on SAP HANA Cloud, follow the steps described under Deploying from the Eclipse IDE.

2. Once the application is deployed successfully on the SAP HANA Cloud local runtime and on SAP HANA Cloud, the application issues an exception saying that the JCoDemoSystem destination has not been specified yet:

Exception occurred while executing STFC_CONNECTION in system JCoDemoSystem

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 387

Page 388: Hana Cloud

com.sap.conn.jco.JCoException: (106) JCO_ERROR_RESOURCE: Destination JCoDemoSystem does not exist at com.sap.conn.jco.rt.DefaultDestinationManager.update(DefaultDestinationManager.java:223) at com.sap.conn.jco.rt.DefaultDestinationManager.searchDestination(DefaultDestinationManager.java:377) at com.sap.conn.jco.rt.DefaultDestinationManager.getDestinationInstance(DefaultDestinationManager.java:96) at com.sap.conn.jco.JCoDestinationManager.getDestination(JCoDestinationManager.java:52) at com.sap.demo.jco.ConnectivityRFCExample.doGet(ConnectivityRFCExample.java:47) ..... (cut rest of the call stack)

3. As a next step, you need to configure the JCoDemoSystem destination.

Configuring the RFC Destination in SAP HANA Cloud

To configure the destination in SAP HANA Cloud, you need to use a virtual application server host name (abapserver.hana.cloud) and a virtual system number (42) that you will expose later on in the SCC. Alternatively, you could use a load balancing configuration with a message server host and a system ID.

Procedure

1. Create a properties file with the following settings:

Name=JCoDemoSystemType=RFCjco.client.ashost=abapserver.hana.cloudjco.client.sysnr=42jco.client.user=DEMOUSERjco.client.passwd=<password>jco.client.client=000jco.client.lang=ENjco.destination.pool_capacity=5

2. Upload this file to your Web application in SAP HANA Cloud. Fore more information, see Configuring Destinations from the Console Client [page 315].

3. Call the URL that references the SAP HANA Cloud application again in the Web browser. The application should now return with a different exception:

Exception occurred while executing STFC_CONNECTION in system JCoDemoSystem

com.sap.conn.jco.JCoException: (102) JCO_ERROR_COMMUNICATION: Opening connection to backend failed: Opening connection denied at com.sap.conn.jco.rt.MiddlewareJavaRfc.generateJCoException(MiddlewareJavaRfc.java:632) at com.sap.conn.jco.rt.MiddlewareJavaRfc$JavaRfcClient.connect(MiddlewareJavaRfc.java:1307)

388P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 389: Hana Cloud

at com.sap.conn.jco.rt.ClientConnection.connect(ClientConnection.java:726) at com.sap.conn.jco.rt.PoolingFactory.init(PoolingFactory.java:107) at com.sap.conn.jco.rt.ConnectionManager.createFactory(ConnectionManager.java:316) at com.sap.conn.jco.rt.DefaultConnectionManager.createFactory(DefaultConnectionManager.java:46) at com.sap.conn.jco.rt.ConnectionManager.getFactory(ConnectionManager.java:290) at com.sap.conn.jco.rt.ConnectionManager.getClient(ConnectionManager.java:83) at com.sap.conn.jco.rt.Context.getConnection(Context.java:216) at com.sap.conn.jco.rt.RfcDestination.execute(RfcDestination.java:1306) at com.sap.conn.jco.rt.RfcDestination.execute(RfcDestination.java:1278) at com.sap.conn.jco.rt.AbapFunction.execute(AbapFunction.java:295) at com.sap.demo.jco.ConnectivityRFCExample.doGet(ConnectivityRFCExample.java:55) ..... (cut rest of the call stack)

4. This means the SAP HANA Cloud connector denied opening a connection to this system. As a next step, you need to configure the system in your installed SAP HANA Cloud connector.

Configuring the Host Mapping in SAP HANA Cloud Connector

This is required since the Cloud Connector only allows access to white-listed back-end systems. To do this, follow the steps below:

Procedure

1. Optional: In the SAP HANA Cloud connector administration UI, you can check under Monitor Auditwhether access has been denied:

OP_ACCESS_DENIED, Denying access to system abapserver.hana.cloud:sapgw42

2. In the SAP HANA Cloud connector administration UI, go to the Access Control tab page.3. Add a new system under the list of defined resources. Under Mapping Virtual To Internal System, choose the

Add button and define an entry as shown in the following screenshot. The Internal Host must be the physical host name of the machine on which the ABAP application server is running.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 389

Page 390: Hana Cloud

4. Call the URL that references the SAP HANA Cloud application again in the Web browser. The application should now return with a different exception:

com.sap.conn.jco.JCoException: (102) JCO_ERROR_COMMUNICATION: Access denied for STFC_CONNECTION at com.sap.conn.jco.rt.MiddlewareJavaRfc.generateJCoException(MiddlewareJavaRfc.java:632) at com.sap.conn.jco.rt.MiddlewareJavaRfc$JavaRfcClient.execute(MiddlewareJavaRfc.java:1764) at com.sap.conn.jco.rt.ClientConnection.execute(ClientConnection.java:1110) at com.sap.conn.jco.rt.ClientConnection.execute(ClientConnection.java:943) at com.sap.conn.jco.rt.RfcDestination.execute(RfcDestination.java:1307) at com.sap.conn.jco.rt.RfcDestination.execute(RfcDestination.java:1278) at com.sap.conn.jco.rt.AbapFunction.execute(AbapFunction.java:295) at com.sap.demo.jco.ConnectivityRFCExample.doGet(ConnectivityRFCExample.java:55) ..... (cut rest of the call stack)

5. This means the SAP HANA Cloud connector denied invoking STFC_CONNECTION in this system. As a final step, you need to provide access to this function module in your installed SAP HANA Cloud connector.

Configuring the Function Module in SAP HANA Cloud Connector

This is required since the Cloud connector only allows access to white-listed resources (which are defined on the basis of function module names with RFC). To do this, follow the steps below:

390P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 391: Hana Cloud

Procedure

1. Optional: In the SAP HANA Cloud connector administration UI, you can check under Monitor Auditwhether access has been denied:

OP_ACCESS_DENIED, Denying access for user DEMOUSER to resource STFC_CONNECTION on system abapserver.hana.cloud:sapgw42

2. In the SAP HANA Cloud connector administration UI, go to the Access Control tab page.3. For the specified internal system referring to abapserver.hana.cloud, add a new resource. Select the system

in the table.4. Add a new function name under the list of exposed resources. Under Resources Accessible On

localappserverhost.compamy.corp:sapgw23, choose the Add button and specify STFC_CONNECTION as the accessible resource as shown in the screenshot below. Make sure that you have selected the Exact Name option to only expose this single function module.

5. Call the URL that references the SAP HANA Cloud application again in the Web browser. The application should now return with a message showing the export parameters of the function module after a successful invocation.

Related Information

You can monitor the state and logs of your Web application deployed on SAP HANA Cloud using the cockpit.

For more information, see SAP HANA Cloud Cockpit [page 50].

1.3.5.5 Sending and Fetching E-Mail

The e-mail connectivity functionality allows you to send electronic mail messages from your Web applications using e-mail providers that are accessible on the Internet, such as Google Mail (Gmail). It also allows you to retrieve e-mails from the mailbox of your e-mail account.

To send and fetch e-mail, you need to do the following:

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 391

Page 392: Hana Cloud

● Obtain a mail session resource using resource injection or, alternatively, using a JNDI lookup.● Configure the mail session resource by specifying the protocol settings of your mail server as a mail

destination configuration. SMTP is supported for sending e-mail, and POP3 and IMAP for retrieving messages from a mailbox account.

● In your Web application, use the JavaMail API (javax.mail) to create and send a MimeMessage object or retrieve e-mails from a message store.

Related LinksMail Destinations [page 392]A mail destination is used to specify the mail server settings for sending or fetching e-mail, such as the e-mail provider, e-mail account, and protocol configuration.

JavaMail API [page 394]In your Web application, you use the JavaMail API (javax.mail) to create and send a MimeMessage object or retrieve e-mails from a message store.

Enabling the Debugging Feature [page 395]In order to troubleshoot e-mail delivery and retrieval issues, it is useful to have debug information about the mail session established between your SAP HANA Cloud application and your e-mail provider.

Tutorial: Sending E-Mails [page 396]

1.3.5.5.1 Mail Destinations

A mail destination is used to specify the mail server settings for sending or fetching e-mail, such as the e-mail provider, e-mail account, and protocol configuration.

The name of the mail destination must match the name used for the mail session resource. You can configure a mail destination directly in a destination editor or in a mail destination properties file. The mail destination then needs to be made available on the cloud platform. If a mail destination is updated, an application restart is required so that the new configuration becomes effective.

Mail Destination Properties

The following properties are used to configure the mail destination:

Property Description Mandatory

Name The name of the destination. The mail session that is configured by this mail destination is available by injecting the mail session resource mail/<Name>. The name of the mail session resource must match the destination name.

The recommended name for a mail destination is Session.

Yes

Type The type of destination. It must be MAIL for mail destinations.

Yes

392P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 393: Hana Cloud

Property Description Mandatory

mail.* javax.mail properties for configuring the mail session. For a list of available properties, see https://javamail.java.net/nonav/docs/api/. The property names must start with "mail.".

To send e-emails, you must specify at least mail.transport.protocol and mail.smtp.host.

To retrieve e-mails, you must specify at least mail.store.protocol, mail.<protocol>.host, and for POP3 mail.pop3.port.

Depends on the mail protocol used.

mail.password Password that is used for authentication. The user name for authentication is specified by mail.user (a standard javax.mail property).

Yes, if authentication is used (mail.smtp.auth=true and generally for fetching e-mail).

Note the following points:

● mail.smtp.port: The SMTP standard ports 465 (SMTPS) and 587 (SMTP+STARTTLS) are open for outgoing connections on the SAP HANA Cloud platform.

● mail.pop3.port: The POP3 standard ports 995 (POP3S) and 110 (POP3+STARTTLS) are open for outgoing connections (used to fetch e-mail).

● mail.imap.port: The IMAP standard ports 993 (IMAPS) and 143 (IMAP +STARTTLS) are open for outgoing connections (used to fetch e-mail).

● mail.<protocol>.host: The mail server of an e-mail provider accessible on the Internet, such as Google Mail (for example, smtp.gmail.com, imap.gmail.com, and so on).

SMTP and IMAP Example

The destination below has been configured to use Gmail as the e-mail provider, SMTP with STARTTLS (port 587) for sending e-mail, and IMAP (SSL) for receiving e-mail:

Name=SessionType=MAIL

mail.user=<gmail account name>mail.password=<gmail account password>

mail.transport.protocol=smtpmail.smtp.host=smtp.gmail.commail.smtp.auth=truemail.smtp.starttls.enable=truemail.smtp.port=587

mail.store.protocol=imapsmail.imaps.host=imap.gmail.com

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 393

Page 394: Hana Cloud

SMTPS Example

The destination below uses Gmail and SMTPS (port 465) for sending e-mail:

Name=SessionType=MAIL

mail.user=<gmail account name>mail.password=<gmail account password>

mail.transport.protocol=smtpsmail.smtps.host=smtp.gmail.commail.smtps.auth=truemail.smtps.port=465

Related LinksConfiguring Destinations from the Eclipse IDE [page 307]Configuring Destinations from the Cockpit [page 311]

Configuring Destinations from the Console Client [page 315]

1.3.5.5.2 JavaMail API

In your Web application, you use the JavaMail API (javax.mail) to create and send a MimeMessage object or retrieve e-mails from a message store.

Mail Session

You can obtain a mail session resource using resource injection or a JNDI lookup. The properties of the mail session are specified by a mail destination configuration. So that the resource is linked to this configuration, the names of the destination configuration and mail session resource must be the same.

● Resource injectionYou can directly inject the mail session resource using annotations as shown in the example below. You do not need to declare the JNDI resource reference in the web.xml deployment descriptor.

@Resource(name = "mail/Session")private javax.mail.Session mailSession;

● JNDI lookupTo obtain a resource of type javax.mail.Session, you declare a JNDI resource reference in the web.xml deployment descriptor in the WebContent/WEB-INF directory as shown below. Note that the recommended resource reference name is Session and the recommended subcontext is mail (mail/Session):

<resource-ref> <res-ref-name>mail/Session</res-ref-name> <res-type>javax.mail.Session</res-type></resource-ref>

394P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 395: Hana Cloud

An initial JNDI context can be obtained by creating a javax.naming.InitialContext object. You can then consume the resource by looking up the naming environment through the InitialContext, as follows:

InitialContext ctx = new InitialContext();Session mailSession = (Session)ctx.lookup("java:comp/env/mail/Session");

Note that according to the Java EE Specification, the prefix java:comp/env should be added to the JNDI resource name (as specified in the web.xml) to form the lookup name.

Sending E-Mail

With the javax.mail.Session object you have retrieved, you can use the JavaMail API to create a MimeMessage object with its constituent parts (instances of MimeMultipart and MimeBodyPart). The message can then be sent using the send method from the Transport class:

Transport transport = mailSession.getTransport();transport.connect();MimeMessage mimeMessage = new MimeMessage(mailSession);...transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());transport.close();

Fetching E-Mail

You can retrieve the e-mails from the inbox folder of your e-mail account using the getFolder method from the Store class as follows:

Store store = mailSession.getStore();store.connect();Folder folder = store.getFolder("INBOX");folder.open(Folder.READ_ONLY);Message[] messages = folder.getMessages();...folder.close(true);store.close();

Related LinksConnectivity Service API [page 401]

1.3.5.5.3 Enabling the Debugging Feature

In order to troubleshoot e-mail delivery and retrieval issues, it is useful to have debug information about the mail session established between your SAP HANA Cloud application and your e-mail provider.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 395

Page 396: Hana Cloud

Context

To include debug information in the standard trace log files (ljs_trace_xxx.log) written at runtime, you can use the JavaMail debugging feature and the System.out logger as follows.

Procedure

1. To enable the JavaMail debugging feature, add the mail.debug property to the mail destination configuration as shown below:

mail.debug=true

2. The System.out logger is preconfigured with the log level INFO. You require at least INFO or a level with more detailed information. To check the log level for your application, log into the cockpit from the SAP HANA Cloud landing page:

○ Customer and partner accounts: https://account.hana.ondemand.com○ Developer accounts: https://account.hanatrial.ondemand.com

3. Choose Applications in the navigation area and click your application to go to the dashboard.4. In the navigation area, choose Logging.

In the Log Settings section in the content area, a list of all loggers used by the application is shown with the log levels that are currently applicable.

5. Enter system.out in the Filter field.

6. If necessary, change the log level for the System.out logger.

NoteYou can check the log level of the System.out logger in a similar manner from the Eclipse IDE.

Related LinksManaging Application Logs from the Eclipse IDE [page 552]

1.3.5.5.4 Tutorial: Sending E-Mails

Overview

This step-by-step tutorial shows how you can send an e-mail from a simple Web application using an e-mail provider that is accessible on the Internet. As an example, it uses Gmail.

The tutorial involves the following steps:

1. Create a dynamic Web project and add a servlet2. Extend the servlet to create and send a MimeMessage object3. Test your application locally using the file system

396P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 397: Hana Cloud

4. Configure a mail destination and deploy your application to the cloud

A sample application mail is available in the SAP HANA Cloud SDK in the <sdk>/samples folder. For more information, see Samples [page 42].

Prerequisites

You have installed the SAP HANA Cloud Tools and created a SAP HANA Cloud server runtime environment as described in Setting Up the Tools and SDK [page 27].

1. Create a Dynamic Web Project and Servlet

To develop applications for the SAP HANA Cloud platform, you require a dynamic Web project and servlet.

1. From the Eclipse main menu, choose File New Dynamic Web Project .2. In the Project name field, enter mail.3. Make sure that SAP HANA Cloud is selected as the target runtime.4. In the Configuration area, leave the default configuration for SAP HANA Cloud and choose Finish.5. To add a servlet to the project you have just created, select the mail node in the Project Explorer view.

6. From the Eclipse main menu, choose File New Servlet .7. Enter the Java package com.sap.cloud.sample.mail and the class name MailServlet.8. Choose Finish to generate the servlet.

2. Extend the Servlet

You add code to create a simple Web UI for composing and sending an e-mail message. The code includes the following methods:

● doGet(): Creates an HTML form for entering e-mail details.● doPost(): Uses the mail session resource to create and send a MimeMessage object. It confirms that an e-

mail has been sent.

1. In the Project Explorer view, expand the mail/Java Resources/src/com.sap.cloud.sample.mail node.

2. Select MailServlet.java, and from the context menu choose Open With Java Editor .3. In the opened editor, replace the entire servlet class with the following content:

package com.sap.cloud.sample.mail;

import java.io.IOException;import java.io.PrintWriter;

import javax.annotation.Resource;import javax.mail.Message.RecipientType;

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 397

Page 398: Hana Cloud

import javax.mail.MessagingException;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeBodyPart;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;import org.slf4j.LoggerFactory;

/** * Servlet implementing a mail example which shows how to use the connectivity service APIs to send e-mail. * The example provides a simple UI to compose an e-mail message and send it. The post method uses * the connectivity service and the javax.mail API to send the e-mail. */public class MailServlet extends HttpServlet {

@Resource(name = "mail/Session") private Session mailSession;

private static final long serialVersionUID = 1L; private static final Logger LOGGER = LoggerFactory.getLogger(MailServlet.class);

/** {@inheritDoc} */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Show input form to user response.setHeader("Content-Type", "text/html"); PrintWriter writer = response.getWriter(); writer.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" " + "\"http://www.w3.org/TR/html4/loose.dtd\">"); writer.write("<html><head><title>Mail Test</title></head><body>"); writer.write("<form action='' method='post'>"); writer.write("<table style='width: 100%'>"); writer.write("<tr>"); writer.write("<td width='100px'><label>From:</label></td>"); writer.write("<td><input type='text' size='50' value='' name='fromaddress'></td>"); writer.write("</tr>"); writer.write("<tr>"); writer.write("<td><label>To:</label></td>"); writer.write("<td><input type='text' size='50' value='' name='toaddress'></td>"); writer.write("</tr>"); writer.write("<tr>"); writer.write("<td><label>Subject:</label></td>"); writer.write("<td><textarea rows='1' cols='100' name='subjecttext'>Subject</textarea></td>"); writer.write("</tr>"); writer.write("<tr>"); writer.write("<td><label>Mail:</label></td>"); writer.write("<td><textarea rows='7' cols='100' name='mailtext'>Mail Text</textarea></td>"); writer.write("</tr>"); writer.write("<tr>"); writer.write("<tr>"); writer.write("<td><input type='submit' value='Send Mail'></td>"); writer.write("</tr>");

398P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 399: Hana Cloud

writer.write("</table>"); writer.write("</form>"); writer.write("</body></html>"); }

/** {@inheritDoc} */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Transport transport = null; try { // Parse form parameters String from = request.getParameter("fromaddress"); String to = request.getParameter("toaddress"); String subjectText = request.getParameter("subjecttext"); String mailText = request.getParameter("mailtext"); if (from.isEmpty() || to.isEmpty()) { throw new RuntimeException("Form parameters From and To may not be empty!"); }

// Construct message from parameters MimeMessage mimeMessage = new MimeMessage(mailSession); InternetAddress[] fromAddress = InternetAddress.parse(from); InternetAddress[] toAddresses = InternetAddress.parse(to); mimeMessage.setFrom(fromAddress[0]); mimeMessage.setRecipients(RecipientType.TO, toAddresses); mimeMessage.setSubject(subjectText, "UTF-8"); MimeMultipart multiPart = new MimeMultipart("alternative"); MimeBodyPart part = new MimeBodyPart(); part.setText(mailText, "utf-8", "plain"); multiPart.addBodyPart(part); mimeMessage.setContent(multiPart);

// Send mail transport = mailSession.getTransport(); transport.connect(); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());

// Confirm mail sending response.getWriter().println( "E-mail was sent (in local scenario stored in '<local-server>/work/mailservice'" + " - in cloud scenario using configured mail session)."); } catch (Exception e) { LOGGER.error("Mail operation failed", e); throw new ServletException(e); } finally { // Close transport layer if (transport != null) { try { transport.close(); } catch (MessagingException e) { throw new ServletException(e); } } } }}

4. Save the class.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 399

Page 400: Hana Cloud

3. Test the Application Locally

Test your code using the local file system before configuring your mail destination and testing the application in the cloud.

1. To test your application on the local server, select the servlet and choose Run Run As Run on Server .2. Make sure that the Manually define a new server radio button is selected and select SAP HANA Cloud local

runtime.3. Choose Finish. A sender screen appears, allowing you to compose and send an e-mail. The sent e-mail is

stored in the work/mailservice directory contained in the root of your SAP HANA Cloud server.

NoteTo send the e-mail through a real e-mail server, you can configure a destination as described in the next section, but using the local server runtime. Remember that once you have configured a destination for local testing, messages are no longer sent to the local file system.

4. Test the Application in the Cloud

Create a mail destination that contains the SMTP settings of your e-mail provider. The name of the mail destination must match the name used in the resource reference in the web.xml descriptor.

1. In the Eclipse main menu, choose File New Other Server Server .2. Select the server type SAP HANA Cloud and choose Next.3. In the SAP HANA Cloud Application dialog box, enter the name of your application and your account, user, and

password and choose Finish. The new server is listed in the Servers view.4. Double-click the server and switch to the Connectivity tab.

5. In the All Destinations section, choose the New Destination button.6. In the New Destination dialog box, enter the name Session and type Mail and choose OK.

7. Configure the destination by adding the properties for port 587 (SMTP+STARTTLS) or 465 (SMTPS). To do this, choose the Add Property button in the Properties section:

○ To use port 587 (SMTP+STARTTLS), add the following properties:

400P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 401: Hana Cloud

Property Value

mail.transport.protocol smtp

mail.smtp.host smtp.gmail.com

mail.smtp.auth true

mail.smtp.starttls.enable true

mail.smtp.port 587

mail.user <gmail account name>

mail.password <gmail account password>

The configured destination for port 587 is shown below:

○ For port 465 (SMTPS), use the following properties:

Property Value

mail.transport.protocol smtps

mail.smtps.host smtp.gmail.com

mail.smtps.auth true

mail.smtps.port 465

mail.user <gmail account name>

mail.password <gmail account password>

8. Save the destination to upload it to the cloud. The settings take effect when the application is next started.

9. In the Project Explorer view, select MailServlet.java and choose Run Run As Run on Server .10. Make sure that the Choose an existing server radio button is selected and select the server you have just

defined.11. Choose Finish to deploy to the cloud. You should now see the sender screen, where you can compose and

send an e-mail

1.3.5.6 Connectivity Service API

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 401

Page 402: Hana Cloud

API Description

org.apache.http http://hc.apache.org

org.apache.http.client http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/package-summary.html

org.apache.http.util http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/util/package-summary.html

javax.mail https://javamail.java.net/nonav/docs/api/

SAP HANA Cloud connectivity service uses javax.mail version 1.4.1 (SDK 1.x) and javax.mail version 1.4.5 (SDK 2.x).

com.sap.core.connectivity.api You can find the connectivity API in directory <<SDK_location>/javadoc/com/sap/core/connectivity/api>.

You can also access it on the following URL: https://help.hana.ondemand.com/javadoc/index.html

1.3.5.7 Connectivity Troubleshooting Guide

What is it?

This section contains troubleshooting information related to SAP HANA Cloud Connectivity service and SAP HANA Cloud connector. It provides solutions to general connectivity issues as well as to specific on-demand to on-premise cases.

Locate the problem or error you have encountered and follow the steps recommended in the solution.

SAP Support Information

If you cannot find a solution to your issue, use the following template to provide specific, issue-relevant information. This helps SAP Support to resolve your problem case.

● The Java EE code that throws an error (if any)● A screenshot of the error message displayed for the failed operation or the error message from the

HttpResponse body● Access credentials for your on-demand or on-premise location

You can submit this information by creating a customer ticket in the SAP CSS system. Use the following components:

● BC-NEO-CON - for general connectivity issues● BC-MID-SCC - for connectivity issues related to installing and configuring SAP HANA Cloud connector,

configuring tunnels, connections, and so on.

In case you experience a more serious issue that cannot be resolved with traces and logs only, access to the SAP HANA Cloud connector is needed by support. In such a situation, follow the instructions of the notes below:

402P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 403: Hana Cloud

● For providing access to the Administration UI via a browser is described, check SAP Note 592085.● For providing SSH access to the operating system of the Linux machine, on which the connector is installed,

check SAP Note 1275351.

Related LinksHTTP-Related Issues [page 403]Connector Configuration and Tunnel Related Issues [page 406]

1.3.5.7.1 HTTP-Related Issues

Overview

In this section, you can find troubleshooting information relating to general issues that you may encounter with the SAP HANA Cloud connectivity service.

Related LinksException java.lang.ClassCastException [page 403]NoHttpResponseException - Target Server Failed to Respond [page 404]Error Code 500 - Destination Name Not Found [page 404]Error Code 504 [page 405]

Exception java.lang.ClassCastException

Symptom

When you want to get a destination in your application, you receive the following exception:

com.sap.core.connectivity.httpdestination.impl.HttpDestinationImpl:org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader@7051630a incompatible with interface com.sap.core.connectivity.api.http.HttpDestination:org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader@6a22a6bb

Problem

You have included some of the dependent libraries in your <WEB-INF/lib> folder.

Keywords

java.lang.ClassCastException, ClassCastException, connectivity, destination

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 403

Page 404: Hana Cloud

Solution

Exclude all SDK libraries from your application WAR file.

If the problem persists, create a ticket in the SAP Customer support system to describe your problem. For more information, see Connectivity Troubleshooting Guide [page 402] → SAP Support Information.

NoHttpResponseException - Target Server Failed to Respond

Symptom

An on-premise destination returns the following error:

org.apache.http.NoHttpResponseException: Target server failed to respond

Problem

The calling application cannot be successfully authenticated to use the tunnel for the related account and tenant.

Keywords

NoHttpResponseException

Solution

If the problem persists, create a ticket in the SAP customer support system to describe your problem. For more information, see Connectivity Troubleshooting Guide [page 402] → SAP Support Information.

Error Code 500 - Destination Name Not Found

Symptom

Destination HttpResponse has status code 500 and HttpResponse body contains:

"Configuration with name <name> does not exist under path /SPACES/<account_name>/appliances/<appliance_name>/components/<component_name>/base/connectivity"

404P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 405: Hana Cloud

Problem

Configuration of specified destination cannot be resolved at runtime. The reason is that the destination has either not been configured at all, or such a destination name does not exist.

Keywords

error, 500, destination configuration, destination name

Solution

1. Make sure you enter the correct name of an existing destination property file. The file must not have extension unless it is a JKS file with .jks extension.

2. Execute again the relevant put or get command. For example:

neo put-destination --account myaccount --application demo --user s1234567 --localpath C:\SDK\tools\samples\connectivity\weather

For more information, see Configuring Destinations from the Console Client [page 315].3. If the problem persists, create a ticket in the SAP customer support system to describe your problem. For

more information, see Connectivity Troubleshooting Guide [page 402] → SAP Support Information.

Error Code 504

Symptom

Destination HttpResponse has status code 504.

Problem

The connectivity proxy server in SAP HANA Cloud has timed out.

Keywords

error, 504

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 405

Page 406: Hana Cloud

Solution

If the problem persists, create a ticket in the SAP customer support system to describe your problem. For more information, see Connectivity Troubleshooting Guide [page 402] → SAP Support Information.

1.3.5.7.2 Connector Configuration and Tunnel Related Issues

Overview

In this section, you can find troubleshooting information relating to issues you may encounter while connecting SAP HANA Cloud connector to SAP HANA Cloud, configuring the tunnel, changing your certificates, or configuring used destinations of an on-demand application.

Related LinksUnsuccessful Connection to SAP HANA Cloud [page 406]Error Code 403 [page 407]Error Code 404 [page 408]Error Code 500 [page 408]Error Code 503 [page 409]

Unsuccessful Connection to SAP HANA Cloud

Symptom

SAP HANA Cloud connector cannot connect to the SAP HANA Cloud platform.

Problem

The SAP HANA Cloud connector UI returns the following error message:

Communication failure - see log for detailsError message in /opt/sap/scc/log/lgs_trace.logTesting tunnel connection failed: Connection to <host:port> refusedorg.apache.http.conn.HttpHostConnectException: Connection to <host:port> refused

406P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 407: Hana Cloud

Keywords

SAP HANA Cloud connector, SCC, initial connection

Solution

● The HTTPS proxy settings may be incorrect. Check the proxy settings from the Settings tab page in you SAP HANA Cloud connector.

● If the problem persists, create a ticket in the SAP customer support system to describe your problem. For more information, see Connectivity Troubleshooting Guide [page 402] → SAP Support Information.

Error Code 403

Symptom

Destination HttpResponse has status code 403. The content type is "text/xml" and the response looks as follows:

<?xml version=\"1.0\"?><sopc-processor><error-message>Access denied for user <user> to resource <resource> on system <system></error-message></sopc-processor>

Problem

In the SAP HANA Cloud connector configuration, either there is no entry defined as the virtual host for the <<system>> used, or the virtual host is specified but the <<resource>> used is not defined in its list of configured resources.

Keywords

error, 403, HttpResponse, text/xml, SAP HANA Cloud connector, SCC

Solution

Log on to SAP HANA Cloud connector and make sure that, in the Access Control tab section, your <<system>> and <<resource>> are configured as required.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 407

Page 408: Hana Cloud

Error Code 404

Symptom

Destination HttpResponse has status code 404.

Problem

The related tunnel has never been created.

Keywords

error, 404, SAP HANA Cloud Connector, SCC

Solution

1. In SAP HANA Cloud connector, check whether the tunnel is operational and that it is connected to the correct account in SAP HANA Cloud. If not, connect the tunnel and try again.

2. In SAP HANA Cloud c onnector, reconfigure the tunnel settings:

a. Open Settings.b. Go to the Configuration tab and configure Account, User, and Password.c. Go to HTTPS Proxy settings and configure them (if needed).

3. If the problem persists, create a ticket in the SAP customer support system to describe your problem. For more information, see Connectivity Troubleshooting Guide [page 402] → SAP Support Information.

Error Code 500

Symptom

Destination HttpResponse has status code 500 and the HttpResponse body contains the text "Could not connect to the requested service".

Problem

The connected SAP HANA Cloud Connector has no access to the requested back-end service.

408P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 409: Hana Cloud

Keywords

error, 500, SAP HANA Cloud Connector, SCC

Solution

1. Check the configuration of the destinations and SAP HANA Cloud connector: The URL of the destination used should consist of a host and a port that are configured on the connector's Access Control tab page as virtual host and port.

2. Check that the back-end system is running and accessible from the SAP HANA Cloud connector machine.3. Check that the correct protocol is used for the requested back-end service in the destination configuration

(that is, HTTP/HTTPS), as it was specified on the connector's Access Control tab.4. If a system certificate is configured, make sure it is the correct certificate with permissions to the relevant

back-end system.5. If the problem persists, create a ticket in the SAP customer support system to describe your problem. For

more information, see Connectivity Troubleshooting Guide [page 402] → SAP Support Information.

Error Code 503

Symptom

Destination HttpResponse has status code 503 and the HttpResponse body contains the text "No route for the requested service".

Problem

The connectivity proxy in SAP HANA Cloud cannot resolve the requested URL. Either the URL of the destination used is incorrect, the service is not configured for the connectivity proxy, or the tunnel is down.

Keywords

error, 503, SAP HANA Cloud connector, SCC

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 409

Page 410: Hana Cloud

Solution

1. Check the requested URL used by the destination (the host and port of the URL should match the specified virtual host and port in SAP HANA Cloud connector).

2. Check that the tunnel is established. SAP HANA Cloud Connector should indicate a "Connected" state for the relevant SAP HANA Cloud account.

3. Check that the back-end service required is configured on the connector's Access Control tab page.4. If the problem persists, create a ticket in the SAP customer support system to describe your problem. For

more information, see Connectivity Troubleshooting Guide [page 402] → SAP Support Information.

1.3.6 Consuming the Persistence Service

Overview

The SAP HANA Cloud persistence service provides persistence in a relational database for applications that are hosted on SAP HANA Cloud. This section introduces the key concepts of the persistence service and shows how you can use JPA and JDBC to manage relational data in your applications:

● Tutorials: Familiarize yourself with the JPA and JDBC technologies on SAP HANA Cloud by completing the tutorials.

● Basic conceptual information: Particular aspects about working with JPA and JDBC that were introduced in the tutorials are explained in more detail.

● Database switch: For test purposes, replace the local database provided as standard with a database of your choice.

● SQL trace: Activate the SQL trace to include SQL details in the standard trace files.● EclipseLink weaving: Enable static weaving in Eclipse.● Remote database access (beta version): Remotely access your Web application's database schema and

tables in the cloud.● Links to more information about the JPA and JDBC APIs● Frequently asked questions (FAQ) about the persistence service

Related LinksTutorials [page 411]Programming with JPA [page 440]Using Plain JDBC [page 448]Creating SAP HANA Column-Store Tables [page 451]Changing the Local Database [page 456]Using the SQL Trace [page 456]EclipseLink Weaving [page 458]Remote Database Access [page 460]The remote database access solution allows you to remotely access the relational databases used on the SAP HANA Cloud platform. This not only lets you investigate and repair application data, but also allows you to remotely create, drop, or modify an application’s database objects by issuing DDL statements, such as ALTER TABLE or CREATE INDEX.

JPA and JDBC APIs [page 471]

410P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 411: Hana Cloud

Frequently Asked Questions [page 471]

1.3.6.1 Tutorials

The SAP HANA Cloud Platform supports both object-relational persistence using JPA 2.0 with EclipseLink as the persistence provider, and relational persistence using JDBC. JPA provides an object-oriented view of the persisted data and allows you to work directly with Java objects that are automatically synchronized with the database. Unlike JDBC, it does not require you to manually write SQL statements to read and write objects from and to the database tables.

The tutorials in this section show how you can persist data in a simple Java EE Web application. Note that JPA is considered the standard approach for developing applications for SAP HANA Cloud. We recommend that you use container-managed persistence, which is the model most commonly used by Web applications:

● Adding Container-Managed Persistence with JPA (SDK 2.x) [page 411]● Adding Application-Managed Persistence with JPA (SDK 1.x) [page 420]● Adding Persistence Using JDBC [page 430]

The tutorials can be run on all databases supported on the SAP HANA Cloud Platform, that is, SAP MaxDB and the SAP HANA database. For local deployment, the persistence service provides an embedded Apache Derby database instance.

NoteThe SAP HANA database is not available for local testing.

Related LinksMigrating Web Applications That Use context.xml [page 439]

1.3.6.1.1 Adding Container-Managed Persistence with JPA (SDK 2.x)

Overview

This step-by-step tutorial shows how you can use JPA together with EJB to persist data in a simple Web application that manages a list of persons.

The tutorial involves the following steps:

1. Create a dynamic Web project and add the following:

○ JPA project facet: Eclipse enables the relevant JPA tooling and adds the required libraries and artifacts, such as the persistence.xml file.

○ Servlet: you extend the servlet to use the JPA persistence entity and EJB session bean in step 4.2. Create a JPA persistence entity class named Person containing the following: an auto-incremented ID as the

primary key of the database table; person attributes; a query method that retrieves a Person object from the database table. Each person stored in the database is represented by a Person entity object.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 411

Page 412: Hana Cloud

3. Create an EJB session bean that handles the database operations.4. Extend the servlet to use the Person entity and EJB session bean. The servlet adds Person entity objects to

the database, retrieves their details, and displays them on the screen.5. Test and deploy the Web application.

A ready-to-run sample application persistence-with-ejb is available in the SAP HANA Cloud SDK 2.x in the <sdk>/samples folder as a complete solution to this tutorial. For more information, see Samples [page 42].

To run the sample on the SAP HANA database, you need to specify com.sap.persistence.platform.database.HDBPlatform as the target database. In the tutorial, this is step 4 of section 2.2.

Prerequisites

You have installed the SAP HANA Cloud Tools and created a SAP HANA Cloud server runtime environment as described in Setting Up the Tools and SDK [page 27]. You need to use the SDK 2.x.

1. Create a Dynamic Web Project

1.1 Create a Dynamic Web Project with a JPA Facet

1. From the Eclipse main menu, choose File New Dynamic Web Project .2. In the Project name field, enter persistence-with-ejb.3. Make sure that SAP HANA Cloud is selected as the target runtime.4. In the Dynamic web module version section, select 3.0.5. In the Configuration section, choose Modify and in the Project Facets dialog box select the JPA checkbox as

shown below:

412P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 413: Hana Cloud

6. Choose OK to confirm and return to the Dynamic Web Project page, as shown below:

7. Choose Next, and on the Java page keep the default settings and choose Next again.8. On the JPA Facet page in the Platform section, select EclipseLink 2.4.x from the dropdown list.9. In the JPA implementation section, select Disable Library Configuration from the dropdown list.10. In the Persistent class management section, make sure that the radio button Discover annotated classes

automatically is selected and choose Finish to complete this step:

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 413

Page 414: Hana Cloud

1.2 Add a Servlet to the Dynamic Web Project

1. In the Project Explorer view, select the persistence-with-ejb node.

2. From the Eclipse main menu, choose File New Servlet .3. Enter the Java package com.sap.cloud.sample.persistence and the class name

PersistenceEJBServlet.4. Choose Finish to generate the servlet.

2. Create the JPA Persistence Entity

2.1 Create the Person Entity

1. In the Project Explorer view, select the persistence-with-ejb/Java Resources/src/com.sap.cloud.sample.persistence node.

414P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 415: Hana Cloud

2. From the Eclipse main menu, choose File New Other Class .3. Make sure that the Java package is com.sap.cloud.sample.persistence.4. Enter the class name Person and choose Finish.5. In the opened editor, replace the entire class with the following content:

package com.sap.cloud.sample.persistence;

import javax.persistence.Basic;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.NamedQuery;import javax.persistence.Table;

/** * Class holding information on a person. */@Entity@Table(name = "T_PERSON")@NamedQuery(name = "AllPersons", query = "select p from Person p")public class Person { @Id @GeneratedValue private Long id; @Basic private String firstName; @Basic private String lastName;

public long getId() { return id; }

public void setId(long newId) { this.id = newId; }

public String getFirstName() { return this.firstName; }

public void setFirstName(String newFirstName) { this.firstName = newFirstName; }

public String getLastName() { return this.lastName; }

public void setLastName(String newLastName) { this.lastName = newLastName; }}

6. Save the class.

2.2 Maintain the Metadata of the Person Entity

In the persistence-with-ejb/Java Resources/src/META-INF folder, define additional settings in persistence.xml:

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 415

Page 416: Hana Cloud

1. Select persistence.xml, and from the context menu choose Open With Persistence XML Editor .2. On the General tab, enter org.eclipse.persistence.jpa.PersistenceProvider in the Persistence

provider field.3. On the Schema Generation tab, enter Create Tables in the DDL generation type field.4. If you intend to deploy with the SAP HANA database, switch to the Options tab and enter

com.sap.persistence.platform.database.HDBPlatform in the Target database field.

NoteThis property should be set before you deploy the application on the SAP HANA database, otherwise an error will occur. If this happens, you need to re-create the table with the correct definitions by setting the DDL generation type to Drop and Create Tables and then redeploy the application. Afterwards, set it back to Create Tables so that you do not lose your data once you deploy again.

When testing the application locally, remember to remove this property.

5. Save the file.

3. Create an EJB Session Bean

1. In the Project Explorer view, select the persistence-with-ejb/Java Resources/src/com.sap.cloud.sample.persistence node.

2. From the Eclipse main menu, choose File New Session Bean (EJB 3.x) .3. Make sure that the Java package is com.sap.cloud.sample.persistence.4. Enter the class name PersonBean, keep the default setting Stateless, and choose Finish.5. In the opened editor, replace the entire class with the following content:

package com.sap.cloud.sample.persistence;

import java.util.List;

import javax.ejb.LocalBean;import javax.ejb.Stateless;import javax.persistence.EntityManager;import javax.persistence.PersistenceContext;

/** * Session Bean implementation class PersonBean */@Stateless@LocalBeanpublic class PersonBean {

@PersistenceContext private EntityManager em;

public List<Person> getAllPersons() { return em.createNamedQuery("AllPersons").getResultList();

}

public void addPerson(Person person) { em.persist(person); em.flush();

416P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 417: Hana Cloud

}}

6. Save the class.

4. Develop a Persistence-Enabled Web Application

4.1 Prepare the Web Application Project for JPA

Add the XSS Protection Library to the Web application project:

1. In the Project Explorer view, select the persistence-with-ejb/WebContent/WEB-INF/lib node.

2. From the context menu, choose Import General File System and choose Next.3. Browse to the local directory where you downloaded and unpacked the SAP HANA Cloud 2.x SDK, select the

repository/plugins directory, and choose OK.4. Select the checkbox com.sap.security.core.server.csi_1.x.y.jar and choose Finish.

4.2 Extend the Servlet to Use Persistence

1. In the Project Explorer view, expand the persistence-with-ejb/Java Resources/src/com.sap.cloud.sample.persistence node.

2. Select PersistenceEJBServlet.java, and from the context menu choose Open With Java Editor .3. In the opened editor, replace the entire servlet class with the following content:

package com.sap.cloud.sample.persistence;

import java.io.IOException;import java.sql.SQLException;import java.util.List;

import javax.ejb.EJB;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;import org.slf4j.LoggerFactory;

import com.sap.security.core.server.csi.IXSSEncoder;import com.sap.security.core.server.csi.XSSEncoder;

/** * Servlet implementation class PersistenceEJBServlet */@WebServlet("/")public class PersistenceEJBServlet extends HttpServlet { private static final long serialVersionUID = 1L;

private static final Logger LOGGER = LoggerFactory .getLogger(PersistenceEJBServlet.class);

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 417

Page 418: Hana Cloud

@EJB PersonBean personBean;

/** {@inheritDoc} */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().println("<p>Persistence with JPA!</p>"); try { appendPersonTable(response); appendAddForm(response); } catch (Exception e) { response.getWriter().println( "Persistence operation failed with reason: " + e.getMessage()); LOGGER.error("Persistence operation failed", e); } }

/** {@inheritDoc} */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { doAdd(request); doGet(request, response); } catch (Exception e) { response.getWriter().println( "Persistence operation failed with reason: " + e.getMessage()); LOGGER.error("Persistence operation failed", e); } }

private void appendPersonTable(HttpServletResponse response) throws SQLException, IOException { // Append table that lists all persons List<Person> resultList = personBean.getAllPersons(); response.getWriter().println( "<p><table border=\"1\"><tr><th colspan=\"3\">" + (resultList.isEmpty() ? "" : resultList.size() + " ") + "Entries in the Database</th></tr>"); if (resultList.isEmpty()) { response.getWriter().println( "<tr><td colspan=\"3\">Database is empty</td></tr>"); } else { response.getWriter() .println( "<tr><th>First name</th><th>Last name</th><th>Id</th></tr>"); } IXSSEncoder xssEncoder = XSSEncoder.getInstance(); for (Person p : resultList) { response.getWriter().println( "<tr><td>" + xssEncoder.encodeHTML(p.getFirstName()) + "</td><td>" + xssEncoder.encodeHTML(p.getLastName()) + "</td><td>" + p.getId() + "</td></tr>"); } response.getWriter().println("</table></p>"); }

private void appendAddForm(HttpServletResponse response) throws IOException { // Append form through which new persons can be added response.getWriter() .println( "<p><form action=\"\" method=\"post\">"

418P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 419: Hana Cloud

+ "First name:<input type=\"text\" name=\"FirstName\">" + "&nbsp;Last name:<input type=\"text\" name=\"LastName\">" + "&nbsp;<input type=\"submit\" value=\"Add Person\">" + "</form></p>"); }

private void doAdd(HttpServletRequest request) throws ServletException, IOException, SQLException { // Extract name of person to be added from request String firstName = request.getParameter("FirstName"); String lastName = request.getParameter("LastName");

if (firstName != null && lastName != null && !firstName.trim().isEmpty() && !lastName.trim().isEmpty()) { Person person = new Person(); person.setFirstName(firstName); person.setLastName(lastName);

personBean.addPerson(person); } }}

4. Save the servlet. The project should compile without any errors.

5. Test and Deploy the Web Application

5.1 Test on Local Server

1. To test your Web application on the local server, follow the steps for deploying a Web application locally as described in Deploying Locally from Eclipse IDE [page 533]. You should see the following output:

2. Enter a first name (for example, John) and a last name (for example, Smith) and choose Add Person.John Smith is added to the database as shown below:

If you add more names to the database, they will also be listed in the table displayed. This illustrates that you have successfully enabled persistence using the Person entity.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 419

Page 420: Hana Cloud

5.2 Deploy on SAP HANA Cloud

To test your Web application on SAP HANA Cloud, follow the steps for deploying a Web application to SAP HANA Cloud as described in Deploying on the Cloud from Eclipse IDE [page 535]. You should see the same output as when the application was tested on the local server, as described in the previous step.

1.3.6.1.2 Adding Application-Managed Persistence with JPA (SDK 1.x)

Overview

This step-by-step tutorial shows how you can use JPA to persist data in a simple Web application that manages a list of persons.

The tutorial involves the following steps:

1. Create a dynamic Web project and add the following:

○ JPA project facet: Eclipse enables the relevant JPA tooling and adds the required libraries and artifacts, such as the persistence.xml file.

○ Servlet: you extend the servlet to use the JPA persistence entity in step 3.2. Create a JPA persistence entity class named Person. You add an auto-incremented ID to the database table

as the primary key and two further attributes. You also define a query method that retrieves a Person object from the database table. Each person stored in the database is represented by a Person entity object.

3. Extend the servlet to use the Person entity. The servlet adds Person entity objects to the database, retrieves their details, and displays them on the screen.

4. Test and deploy the Web application.

A ready-to-run sample application persistence-with-jpa is available in the SAP HANA Cloud SDK in the <sdk>/samples folder as a complete solution to this tutorial. For more information, see Samples [page 42].

Prerequisites

● You have installed theSAP HANA Cloud Tools and created a SAP HANA Cloud server runtime environment as described in Setting Up the Tools and SDK [page 27]. You need to use the SDK 1.x.

● You have downloaded the JPA Provider, EclipseLink:

1. Download the latest 2.4.x version of EclipseLink from http://www.eclipse.org/eclipselink/downloads. Select the EclipseLink 2.4.x Installer Zip (intended for use in Java EE environments).

2. Extract the archive.3. Copy the following two files to a separate directory in your local file system:

○ eclipselink.jar from the directory eclipselink/jlib○ javax.persistence_2.*.jar from the directory eclipselink/jlib/jpa

You will need to add these files to your Web application in a later step.

420P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 421: Hana Cloud

1. Create a Dynamic Web Project

1.1 Create a Dynamic Web Project with a JPA Facet

1. From the Eclipse main menu, choose File New Dynamic Web Project .2. In the Project name field, enter persistence-with-jpa.3. Make sure that SAP HANA Cloud is selected as the target runtime.4. In the Configuration section, choose Modify and in the Project Facets dialog box select the JPA checkbox as

shown below:

5. Choose OK to confirm and return to the Dynamic Web Project page, as shown below:

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 421

Page 422: Hana Cloud

6. Choose Next, and on the Java page keep the default settings and choose Next again.7. On the JPA Facet page in the Platform section, select EclipseLink 2.4.x from the dropdown list.8. In the JPA implementation section, select Disable Library Configuration from the dropdown list.9. In the Persistent class management section, select the radio button Annotated classes must be listed in

persistence.xml and choose Finish to complete this step:

422P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 423: Hana Cloud

1.2 Add a Servlet to the Dynamic Web Project

1. In the Project Explorer view, select the persistence-with-jpa node.

2. From the Eclipse main menu, choose File New Servlet .3. Enter the Java package com.sap.cloud.sample.persistence and the class name

PersistenceWithJPAServlet.4. Choose Finish to generate the servlet.

2. Create the JPA Persistence Entity

2.1 Create the Person Entity Using the Graphical JPA Editor

1. To create all persistence-related classes in one package, change the default Java package used for new entities as follows:

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 423

Page 424: Hana Cloud

a. Select the persistence-with-jpa project, and from the context menu choose Properties JPAJPA Diagram Editor .

b. In the Default Java package for new entities field, change org.persistence to com.sap.cloud.sample.persistence and choose OK to confirm.

2. Create the Person entity using the JPA editor:

a. In the Project Explorer view, select the persistence-with-jpa/JPA Content node, and from the context menu choose Open Diagram.The graphical JPA editor opens.

b. Confirm the JPA Support dialog with OK and select Do not show this message again.c. From the palette, drag and drop a Java Entity onto the editor grid.d. A class called Entity1 is created automatically.

e. Select the Java entity Entity1, and from the context menu choose Refactor Entity Class Rename . Alternatively, click the name and use the inline editor to rename the entity.

f. Enter Person as the new name and choose Finish.g. Save the file.

3. Create a named query for the Person entity:

a. Select the Person entity, and from the context menu choose Open JPA Details View.b. In the Queries section in the JPA Details view, choose Add. The Add Query dialog box opens.c. Enter the name AllPersons and the type Named Query, and choose OK.d. In the Query field, enter the text select p from Person p.

e. Save all.4. Create and modify the attributes of the Person entity:

a. In the graphical editor, select the ID attribute of the Person entity.b. In the Primary Key Generation section in the JPA Details view, select the Primary key generation checkbox

and leave Default (Auto) in the Strategy field.

424P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 425: Hana Cloud

c. Add new attributes by hovering over the Person entity and choosing the Create Attribute button. Define two attributes with the names FirstName and LastName.

d. Save the file.

2.2 Maintain the Metadata of the Person Entity

In the persistence-with-jpa/Java Resources/src/META-INF folder, define additional settings in persistence.xml:

1. Select persistence.xml, and from the context menu choose Open With Persistence XML Editor .2. On the General tab, enter org.eclipse.persistence.jpa.PersistenceProvider in the Persistence

provider field.3. On the Connection tab, enter the transaction type Resource Local.4. On the Schema Generation tab, enter Create Tables in the DDL generation type field.5. Save the file.

3. Develop a Persistence-Enabled Web Application

3.1 Prepare the Web Application Project for JPA

1. Add EclipseLink executables to the Web application project:

a. In the Project Explorer view, select the persistence-with-jpa/WebContent/WEB-INF/lib node.

b. From the context menu, choose Import General File System and then choose Next.c. Browse to and select the local directory to which you copied the downloaded EclipseLink JAR files (see

the Prerequisites section), and choose OK.d. Choose the Select All button to select the checkboxes for the two EclipseLink JAR files, eclipselink.jar and

javax.persistence_2.*.jar, and then choose Finish.2. If you intend to deploy with the SAP HANA database, add the SAP HANA JAR to the Web application project:

a. In the Project Explorer view, select the persistence-with-jpa/WebContent/WEB-INF/lib node.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 425

Page 426: Hana Cloud

b. From the context menu, choose Import General File System and then choose Next.c. Browse to the local directory where you downloaded and unpacked the SAP HANA Cloud SDK, select the

repository/plugins directory, and choose OK .d. Select the checkbox com.sap.core.persistence.osgi.hdb.platform_x.y.z.jar and choose Finish.

3. Add the XSS Protection Library to the Web application project:

a. In the Project Explorer view, select the persistence-with-jpa/WebContent/WEB-INF/lib node.

b. From the context menu, choose Import General File System and then choose Next.c. Browse to the local directory where you downloaded and unpacked the SAP HANA Cloud SDK, select the

repository/plugins directory, and choose OK .d. Select the checkbox com.sap.security.core.server.csi_1.x.y.jar and choose Finish.

4. Adapt the Java build path order:

a. In the Project Explorer view, select the persistence-with-jpa node, and from the context menu choose Properties.

b. Select Java Build Path and switch to the Order and Export tab.c. Select Web App Libraries and move it up so that it is positioned above SAP HANA Cloud.d. Choose OK to finish this step.

5. Add the resource reference description to web.xml:

a. In the Project Explorer view, expand the persistence-with-jpa/WebContent/WEB-INF node.

b. Select web.xml, and from the context menu choose Open With Text Editor .c. Insert the following content after the <servlet-mapping> elements:

<resource-ref> <res-ref-name>jdbc/DefaultDB</res-ref-name> <res-type>javax.sql.DataSource</res-type></resource-ref>

d. Save the file.6. Optionally modify the servlet deployment descriptor information:

a. Open the web.xml file as in the previous step.b. Replace the URL pattern "/PersistenceWithJPAServlet" that was generated for the servlet with "/" as

shown below:

<servlet-mapping> <servlet-name>PersistenceWithJPAServlet</servlet-name> <url-pattern>/</url-pattern></servlet-mapping>

c. Save the file.

NoteAn application's URL path contains the context root followed by the optional URL pattern ("/<URL pattern>"). The servlet URL pattern that is automatically generated by Eclipse uses the servlet’s class name as part of the pattern. Since the cockpit only displays the context root, this means that you cannot directly open the application in the cockpit without adding the servlet name. To call the application by only the context root, use "/" as the URL mapping, then you will no longer have to correct the URL in the browser.

426P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 427: Hana Cloud

3.2 Extend the Servlet to Use Persistence

1. In the Project Explorer view, expand the persistence-with-jpa/Java Resources/src/com.sap.cloud.sample.persistence node.

2. Select PersistenceWithJPAServlet.java, and from the context menu choose Open With Java Editor .

3. In the opened editor, replace the entire servlet class with the following content:

package com.sap.cloud.sample.persistence;

import java.io.IOException;

import java.sql.SQLException;import java.sql.Connection;import java.util.HashMap;import java.util.List;import java.util.Map;

import javax.naming.InitialContext;import javax.naming.NamingException;import javax.persistence.EntityManager;import javax.persistence.EntityManagerFactory;import javax.persistence.Persistence;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.sql.DataSource;

import org.eclipse.persistence.config.PersistenceUnitProperties;import org.slf4j.Logger;import org.slf4j.LoggerFactory;

import com.sap.security.core.server.csi.IXSSEncoder;import com.sap.security.core.server.csi.XSSEncoder;

/** * Servlet implementing a simple JPA based persistence sample application for * SAP HANA Cloud. */public class PersistenceWithJPAServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger LOGGER = LoggerFactory .getLogger(PersistenceWithJPAServlet.class);

private DataSource ds; private EntityManagerFactory emf;

/** {@inheritDoc} */ @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void init() throws ServletException { Connection connection = null; try { InitialContext ctx = new InitialContext(); ds = (DataSource) ctx.lookup("java:comp/env/jdbc/DefaultDB"); connection = ds.getConnection(); Map properties = new HashMap(); properties.put(PersistenceUnitProperties.NON_JTA_DATASOURCE, ds); String databaseProductName = connection.getMetaData() .getDatabaseProductName(); if (databaseProductName.equals("HDB")) { properties.put("eclipselink.target-database",

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 427

Page 428: Hana Cloud

"com.sap.persistence.platform.database.HDBPlatform"); } emf = Persistence.createEntityManagerFactory( "persistence-with-jpa", properties); } catch (NamingException e) { throw new ServletException(e); } catch (SQLException e) { LOGGER.error("Could not determine database product."); throw new ServletException(e); } finally { if (connection != null) { try { connection.close(); } catch (SQLException x) { LOGGER.debug("Unable to close connection.", x); } } } }

/** {@inheritDoc} */ @Override public void destroy() { emf.close(); }

/** {@inheritDoc} */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().println("<p>Persistence with JPA!</p>"); try { appendPersonTable(response); appendAddForm(response); } catch (Exception e) { response.getWriter().println( "Persistence operation failed with reason: " + e.getMessage()); LOGGER.error("Persistence operation failed", e); } }

/** {@inheritDoc} */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { doAdd(request); doGet(request, response); } catch (Exception e) { response.getWriter().println( "Persistence operation failed with reason: " + e.getMessage()); LOGGER.error("Persistence operation failed", e); } }

private void appendPersonTable(HttpServletResponse response) throws SQLException, IOException { // Append table that lists all persons EntityManager em = emf.createEntityManager(); try { @SuppressWarnings("unchecked") List<Person> resultList = em.createNamedQuery("AllPersons") .getResultList(); response.getWriter().println( "<p><table border=\"1\"><tr><th colspan=\"3\">"

428P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 429: Hana Cloud

+ (resultList.isEmpty() ? "" : resultList.size() + " ") + "Entries in the Database</th></tr>"); if (resultList.isEmpty()) { response.getWriter().println( "<tr><td colspan=\"3\">Database is empty</td></tr>"); } else { response.getWriter() .println( "<tr><th>First name</th><th>Last name</th><th>Id</th></tr>"); } IXSSEncoder xssEncoder = XSSEncoder.getInstance(); for (Person p : resultList) { response.getWriter().println( "<tr><td>" + xssEncoder.encodeHTML(p.getFirstName()) + "</td><td>" + xssEncoder.encodeHTML(p.getLastName()) + "</td><td>" + p.getId() + "</td></tr>"); } response.getWriter().println("</table></p>"); } finally { em.close(); } }

private void appendAddForm(HttpServletResponse response) throws IOException { // Append form through which new persons can be added response.getWriter() .println( "<p><form action=\"\" method=\"post\">" + "First name:<input type=\"text\" name=\"FirstName\">" + "&nbsp;Last name:<input type=\"text\" name=\"LastName\">" + "&nbsp;<input type=\"submit\" value=\"Add Person\">" + "</form></p>"); }

private void doAdd(HttpServletRequest request) throws ServletException, IOException, SQLException { // Extract name of person to be added from request String firstName = request.getParameter("FirstName"); String lastName = request.getParameter("LastName");

// Add person if name is not null/empty EntityManager em = emf.createEntityManager(); try { if (firstName != null && lastName != null && !firstName.trim().isEmpty() && !lastName.trim().isEmpty()) { Person person = new Person(); person.setFirstName(firstName); person.setLastName(lastName); em.getTransaction().begin(); em.persist(person); em.getTransaction().commit(); } } finally { em.close(); } }}

4. Save the servlet. The project should compile without any errors.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 429

Page 430: Hana Cloud

4. Test and Deploy the Web Application

4.1 Test on Local Server

1. To test your Web application on the local server, follow the steps for deploying a Web application locally as described in Deploying Locally from Eclipse IDE [page 533]. You should see the following output:

2. Enter a first name (for example, John) and a last name (for example, Smith) and choose Add Person.John Smith is added to the database as shown below:

If you add more names to the database, they will also be listed in the table displayed. This illustrates that you have successfully enabled persistence using the Person entity.

4.2 Deploy on SAP HANA Cloud

To test your Web application on SAP HANA Cloud, follow the steps for deploying a Web application to SAP HANA Cloud as described in Deploying on the Cloud from Eclipse IDE [page 535]. You should see the same output as when the application was tested on the local server, as described in the previous step.

1.3.6.1.3 Adding Persistence Using JDBC

Overview

This step-by-step tutorial shows how you can use JDBC to persist data in a simple Web application that manages a list of persons.

The tutorial involves the following steps:

1. You create a dynamic Web project and add a servlet, which you extend in step 3.

430P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 431: Hana Cloud

2. You create an entity class named Person with basic attributes and a DAO class, PersonDAO, in which you encapsulate the access to the persistence layer.

3. You extend the servlet to use the persistence functionality. The servlet adds Person entity objects to the database, retrieves their details, and displays them on the screen.

4. You test and deploy the Web application.

A ready-to-run sample application persistence-with-jdbc is available in the SAP HANA Cloud SDK in the <sdk>/samples folder as a complete solution to this tutorial. For more information, see Samples [page 42].

Prerequisites

You have installed the SAP HANA Cloud Tools and created a SAP HANA Cloud server runtime environment as described in Setting Up the Tools and SDK [page 27].

1. Create a Dynamic Web Project

1.1 Create the Web Project

1. From the Eclipse main menu, choose File New Dynamic Web Project .2. In the Project name field, enter persistence-with-jdbc.3. Make sure that SAP HANA Cloud is selected as the target runtime.4. Keep the default settings for the other project settings and choose Finish.

1.2 Add a Servlet to the Web Project

1. In the Project Explorer view, select the persistence-with-jdbc node.

2. From the Eclipse main menu, choose File New Servlet .3. Enter the Java package com.sap.cloud.sample.persistence and the class name

PersistenceWithJDBCServlet.4. Choose Finish to generate the servlet.

2. Create the Person Entity and Person DAO

2.1 Add Person.java to the Web Application Project

1. In the Project Explorer view, select the persistence-with-jdbc/Java Resources/src/com.sap.cloud.sample.persistence node.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 431

Page 432: Hana Cloud

2. From the context menu, choose New Class , check that the package entered is com.sap.cloud.sample.persistence, enter the class name Person, and choose Finish.

3. Open the file in the text editor and insert the following content:

package com.sap.cloud.sample.persistence;

/** * Class holding information on a person. */public class Person { private String id; private String firstName; private String lastName;

public String getId() { return id; }

public void setId(String newId) { this.id = newId; }

public String getFirstName() { return this.firstName; }

public void setFirstName(String newFirstName) { this.firstName = newFirstName; }

public String getLastName() { return this.lastName; }

public void setLastName(String newLastName) { this.lastName = newLastName; }}

4. Save the class.

2.2 Add PersonDAO.java to the Web Application Project

1. In the Project Explorer view, select the persistence-with-jdbc/Java Resources/src/com.sap.cloud.sample.persistence node.

2. From the context menu, choose New Class , check that the package entered is com.sap.cloud.sample.persistence, enter the class name PersonDAO, and choose Finish.

3. Open the file in the text editor and insert the following content:

package com.sap.cloud.sample.persistence;

import java.sql.Connection;import java.sql.DatabaseMetaData;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;

432P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 433: Hana Cloud

import java.util.List;import java.util.UUID;

import javax.sql.DataSource;

/** * Data access object encapsulating all JDBC operations for a person. */public class PersonDAO { private DataSource dataSource;

/** * Create new data access object with data source. */ public PersonDAO(DataSource newDataSource) throws SQLException { setDataSource(newDataSource); }

/** * Get data source which is used for the database operations. */ public DataSource getDataSource() { return dataSource; }

/** * Set data source to be used for the database operations. */ public void setDataSource(DataSource newDataSource) throws SQLException { this.dataSource = newDataSource; checkTable(); }

/** * Add a person to the table. */ public void addPerson(Person person) throws SQLException { Connection connection = dataSource.getConnection();

try { PreparedStatement pstmt = connection .prepareStatement("INSERT INTO PERSONS (ID, FIRSTNAME, LASTNAME) VALUES (?, ?, ?)"); pstmt.setString(1, UUID.randomUUID().toString()); pstmt.setString(2, person.getFirstName()); pstmt.setString(3, person.getLastName()); pstmt.executeUpdate(); } finally { if (connection != null) { connection.close(); } } }

/** * Get all persons from the table. */ public List<Person> selectAllPersons() throws SQLException { Connection connection = dataSource.getConnection(); try { PreparedStatement pstmt = connection .prepareStatement("SELECT ID, FIRSTNAME, LASTNAME FROM PERSONS"); ResultSet rs = pstmt.executeQuery(); ArrayList<Person> list = new ArrayList<Person>(); while (rs.next()) { Person p = new Person(); p.setId(rs.getString(1));

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 433

Page 434: Hana Cloud

p.setFirstName(rs.getString(2)); p.setLastName(rs.getString(3)); list.add(p); } return list; } finally { if (connection != null) { connection.close(); } } }

/** * Check if the person table already exists and create it if not. */ private void checkTable() throws SQLException { Connection connection = null;

try { connection = dataSource.getConnection(); if (!existsTable(connection)) { createTable(connection); } } finally { if (connection != null) { connection.close(); } } }

/** * Check if the person table already exists. */ private boolean existsTable(Connection conn) throws SQLException { DatabaseMetaData meta = conn.getMetaData(); ResultSet rs = meta.getTables(null, null, "PERSONS", null); while (rs.next()) { String name = rs.getString("TABLE_NAME"); if (name.equals("PERSONS")) { return true; } } return false; }

/** * Create the person table. */ private void createTable(Connection connection) throws SQLException { PreparedStatement pstmt = connection .prepareStatement("CREATE TABLE PERSONS " + "(ID VARCHAR(255) PRIMARY KEY, " + "FIRSTNAME VARCHAR (255)," + "LASTNAME VARCHAR (255))"); pstmt.executeUpdate(); }}

4. Save the class.

434P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 435: Hana Cloud

3. Develop a Persistence-Enabled Web Application

3.1 Prepare the Web Application Project for JDBC

1. Add the XSS Protection Library to the Web application project:

a. In the Project Explorer view, select the persistence-with-jdbc/WebContent/WEB-INF/lib node.

b. From the context menu, choose Import General File System and then choose Next.c. Browse to the local directory where you downloaded and unpacked the SAP HANA Cloud SDK, select the

repository/plugins directory, and choose OK.d. Select the checkbox com.sap.security.core.server.csi_1.x.y.jar and choose Finish.

2. Adapt the Java build path order:

a. In the Project Explorer view, select the persistence-with-jdbc node, and from the context menu choose Properties.

b. Select Java Build Path and switch to the Order and Export tab.c. Select Web App Libraries and move it up so that it is positioned above SAP HANA Cloud.d. Choose OK to finish this step.

3. Add the resource reference description to web.xml:

a. In the Project Explorer view, expand the persistence-with-jdbc/WebContent/WEB-INF node.

b. Select web.xml, and from the context menu choose Open With Text Editor .c. Insert the following content after the <servlet-mapping> elements:

<resource-ref> <res-ref-name>jdbc/DefaultDB</res-ref-name> <res-type>javax.sql.DataSource</res-type></resource-ref>

d. Save the file.4. Optionally modify the servlet deployment descriptor information:

a. Open the web.xml file as in the previous step.b. Replace the URL pattern "/PersistenceWithJDBCServlet" that was generated for the servlet with "/" as

shown below:

<servlet-mapping> <servlet-name>PersistenceWithJDBCServlet</servlet-name> <url-pattern>/</url-pattern></servlet-mapping>

c. Save the file.

NoteAn application's URL path contains the context root followed by the optional URL pattern ("/<URL pattern>"). The servlet URL pattern that is automatically generated by Eclipse uses the servlet’s class name as part of the pattern. Since the cockpit only displays the context root, this means that you cannot directly open the application in the cockpit without adding the servlet name. To call the application by only the context root, use "/" as the URL mapping, then you will no longer have to correct the URL in the browser.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 435

Page 436: Hana Cloud

3.2 Extend the Servlet to Use Persistence

1. In the Project Explorer view, expand the persistence-with-jdbc/Java Resources/src/com.sap.cloud.sample.persistence node.

2. Select PersistenceWithJDBCServlet.java, and from the context menu choose Open With Java Editor .

3. In the opened editor, replace the entire servlet class with the following content:

package com.sap.cloud.sample.persistence;

import java.io.IOException;import java.sql.SQLException;import java.util.List;

import javax.naming.InitialContext;import javax.naming.NamingException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.sql.DataSource;

import org.slf4j.Logger;import org.slf4j.LoggerFactory;

import com.sap.security.core.server.csi.IXSSEncoder;import com.sap.security.core.server.csi.XSSEncoder;

/** * Servlet implementing a simple JDBC based persistence sample application for * SAP HANA Cloud. */public class PersistenceWithJDBCServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger LOGGER = LoggerFactory .getLogger(PersistenceWithJDBCServlet.class);

private PersonDAO personDAO;

/** {@inheritDoc} */ @Override public void init() throws ServletException { try { InitialContext ctx = new InitialContext(); DataSource ds = (DataSource) ctx .lookup("java:comp/env/jdbc/DefaultDB"); personDAO = new PersonDAO(ds); } catch (SQLException e) { throw new ServletException(e); } catch (NamingException e) { throw new ServletException(e); } }

/** {@inheritDoc} */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().println("<p>Persistence with JDBC!</p>"); try { appendPersonTable(response); appendAddForm(response); } catch (Exception e) {

436P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 437: Hana Cloud

response.getWriter().println( "Persistence operation failed with reason: " + e.getMessage()); LOGGER.error("Persistence operation failed", e); } }

/** {@inheritDoc} */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { doAdd(request); doGet(request, response); } catch (Exception e) { response.getWriter().println( "Persistence operation failed with reason: " + e.getMessage()); LOGGER.error("Persistence operation failed", e); } }

private void appendPersonTable(HttpServletResponse response) throws SQLException, IOException { // Append table that lists all persons List<Person> resultList = personDAO.selectAllPersons(); response.getWriter().println( "<p><table border=\"1\"><tr><th colspan=\"3\">" + (resultList.isEmpty() ? "" : resultList.size() + " ") + "Entries in the Database</th></tr>"); if (resultList.isEmpty()) { response.getWriter().println( "<tr><td colspan=\"3\">Database is empty</td></tr>"); } else { response.getWriter() .println( "<tr><th>First name</th><th>Last name</th><th>Id</th></tr>"); } IXSSEncoder xssEncoder = XSSEncoder.getInstance(); for (Person p : resultList) { response.getWriter().println( "<tr><td>" + xssEncoder.encodeHTML(p.getFirstName()) + "</td><td>" + xssEncoder.encodeHTML(p.getLastName()) + "</td><td>" + p.getId() + "</td></tr>"); } response.getWriter().println("</table></p>"); }

private void appendAddForm(HttpServletResponse response) throws IOException { // Append form through which new persons can be added response.getWriter() .println( "<p><form action=\"\" method=\"post\">" + "First name:<input type=\"text\" name=\"FirstName\">" + "&nbsp;Last name:<input type=\"text\" name=\"LastName\">" + "&nbsp;<input type=\"submit\" value=\"Add Person\">" + "</form></p>"); }

private void doAdd(HttpServletRequest request) throws ServletException, IOException, SQLException { // Extract name of person to be added from request String firstName = request.getParameter("FirstName");

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 437

Page 438: Hana Cloud

String lastName = request.getParameter("LastName");

// Add person if name is not null/empty if (firstName != null && lastName != null && !firstName.trim().isEmpty() && !lastName.trim().isEmpty()) { Person person = new Person(); person.setFirstName(firstName.trim()); person.setLastName(lastName.trim()); personDAO.addPerson(person); } }}

4. Save the servlet. The project should compile without any errors.

4. Test and Deploy the Web Application

4.1 Test on Local Server

1. To test your Web application on the local server, follow the steps for deploying a Web application locally as described in Deploying Locally from Eclipse IDE [page 533]. You should see the following output:

2. Enter a first name (for example, John) and a last name (for example, Smith) and choose Add Person.John Smith is added to the database as shown below:

If you add more names to the database, they will also be listed in the table displayed.

4.2 Deploy on SAP HANA Cloud

To test your Web application on SAP HANA Cloud, follow the steps for deploying a Web application to SAP HANA Cloud as described in Deploying on the Cloud from Eclipse IDE [page 535]. You should see the same output as when the application was tested on the local server, as described in the previous step.

438P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 439: Hana Cloud

1.3.6.1.4 Migrating Web Applications That Use context.xml

Overview

Earlier versions of the persistence tutorials used context.xml to declare a reference to the default data source provided by the persistence service. The tutorials have since been adapted to include the resource reference description in the web.xml deployment descriptor, in accordance with the Java EE Specification, as follows:

<resource-ref> <res-ref-name> NAME </res-ref-name> <res-type> TYPE </res-type> </resource-ref>

If you have Web applications that use context.xml, you are advised to switch to web.xml as soon as possible by completing the migration steps described below. The use of context.xml is no longer supported.

Procedure

1. Open the context.xml file in the WebContent/META-INF folder of your Web application project. You should see the following with similar values (the values shown below are based on the tutorials):

<Resource name="jdbc/DefaultDB" auth="Container" type="javax.sql.DataSource" factory="com.sap.jpaas.service.persistence.core.JNDIDataSourceFactory"/>

You require the resource name and type values in the next step.2. Add the resource reference description to the web.xml file:

a. Open web.xml in the WebContent/WEB-INF folder of your Web application project.b. Insert the following content after the <servlet-mapping> elements:

<resource-ref> <res-ref-name>NAME</res-ref-name> <res-type>TYPE</res-type> </resource-ref>

c. Replace the values for the resource name and type with those from step 1, as shown in the example below, and save:

<resource-ref> <res-ref-name>jdbc/DefaultDB</res-ref-name> <res-type>javax.sql.DataSource</res-type> </resource-ref>

3. Delete context.xml from the WebContent/META-INF folder of your Web application project.

Related LinksAdding Application-Managed Persistence with JPA (SDK 1.x) [page 420]

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 439

Page 440: Hana Cloud

Adding Persistence Using JDBC [page 430]

1.3.6.2 Programming with JPA

JPA offers two main types of persistence, container-managed persistence and application-managed persistence, which differ in terms of the management and life cycle of the entity manager.

The main features of each scenario are shown in the table below. We recommend that you use container-managed persistence (SDK 2.x), which is the model most commonly used by Web applications:

JPA Scenario SDK 1.x SDK 2.x

Container-managed persistence JTA transactions

Entity manager injection using the @PersistenceContext annotation

Application-managed persistence Resource-local transactions

Injection of the entity manager factory using the @PersistenceUnit annotation

Manual creation of the entity manager factory using javax.persistence.Persistence. createEntityManagerFactory

EclipseLink

For the application-managed persistence scenario with manual creation of the entity manager factory, you need to download EclipseLink and add the following JAR files to your project:

● SDK 1.x:

○ eclipselink\jlib\eclipselink.jar○ eclipselink\jlib\jpa\javax.persistence_2.*.jar

Note that you do not require this JAR file if you use the @Resource annotation to inject the data source.● SDK 2.x: eclipselink\jlib\eclipselink.jar

The EclipseLink download is available from http://www.eclipse.org/eclipselink/downloads. Click EclipseLink 2.4.x Installer Zip and then download the archive and extract it to your local file system. For the SDK 1.x scenario, where you require two JAR files, we recommend that you copy the two files required (see above) to a separate directory in your local file system.

For details about importing the files into your Web application project and specifying the JPA implementation library EclipseLink, see the tutorial Adding Application-Managed Persistence with JPA (SDK 1.x) [page 420].

NoteYou should not import these files for the injection scenarios (SDK 2.x). This leads to problems if you are using the SAP HANA database.

440P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 441: Hana Cloud

SAP HANA Database

Since the SAP HANA database platform is not part of the EclipseLink version currently used in SAP HANA Cloud, the following steps are necessary if you deploy with the SAP HANA database:

● Injection scenarios (SDK 2.x): Specify com.sap.persistence.platform.database.HDBPlatform as the target database in the persistence.xml file ("eclipselink.target-database" property)For more information, see the tutorial Adding Container-Managed Persistence with JPA (SDK 2.x) [page 411].

● Application-managed persistence scenario with manual creation of the entity manager factory (SDK 1.x and 2.x):

○ Import com.sap.core.persistence.osgi.hdb.platform_x.y.z.jar from the <sdk>/repository/plugins directory into your project

○ Add the "eclipselink.target-database" property com.sap.persistence.platform.database.HDBPlatform to the persistence unit properties

For more information, see the tutorial Adding Application-Managed Persistence with JPA (SDK 1.x) [page 420].

NoteRemember that the SAP HANA database is only available in the cloud. The persistence service does not provide the SAP HANA database for local deployment.

Related LinksPersistence Unit [page 441]Entity Classes [page 443]Default Data Source [page 444]Container-Managed Entity Managers [page 445]Application-Managed Entity Managers [page 447]

1.3.6.2.1 Persistence Unit

Overview

A JPA model contains a persistence configuration file, persistence.xml, which describes the defined persistence unit. A persistence unit in turn defines all entity classes managed by the entity managers in your application and includes the metadata for mapping the entity classes to the database entities.

The persistence.xml file is located in the META-INF folder within the persistence unit src folder. The JPA persistence provider used by the persistence service is org.eclipse.persistence.jpa.PersistenceProvider. Although it is not strictly necessary to declare the JPA provider, we recommend that you do so once you include EclipseLink-specific properties, such as those related to DDL generation.

ExampleIn the persistence.xml file in the tutorial Adding Container-Managed Persistence with JPA (SDK 2.x) [page 411], the persistence unit is named persistence-with-ejb, the transaction type is JTA (default setting), the DDL

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 441

Page 442: Hana Cloud

generation type has been set to Create Tables, and the SAP HANA database has been specified as the target database, as shown below:

<?xml version="1.0" encoding="UTF-8"?><persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="persistence-with-ejb"> <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> <class>com.sap.cloud.sample.persistence.Person</class> <properties> <property name="eclipselink.ddl-generation" value="create-tables" /> <property name="eclipselink.target-database" value="com.sap.persistence.platform.database.HDBPlatform"/> </properties> </persistence-unit></persistence>

JTA Transactions

The SDK 2.x supports JTA transactions. To use JTA transactions, the transaction type attribute in the persistence.xml file should be set appropriately using one of the following options:

● Simply use the default setting, which is JTA transactions (do not explicitly set a value), as shown in the example below:

<persistence-unit name="persistence-with-ejb">

● Set the value of the transaction type attribute to JTA, as shown in the example below:

<persistence-unit name="persistence-with-ejb" transaction-type="JTA">

Since the persistence service provides only one data source at present, it is not necessary to configure a data source in the persistence.xml file. Depending on the transaction type specified, the persistence service provides either a managed or unmanaged data source.

Resource-Local Transactions

These are transactions explicitly controlled by your application through the EntityTransaction interface of the entity manager. To use resource-local transactions, the transaction type attribute in the persistence.xml file has to be set to RESOURCE_LOCAL, indicating that the entity manager factory should provide resource-local entity managers. When you work with a non-JTA data source, the non-JTA data source element also has to be set in the persistence unit properties.

Note that the SDK 1.x supports resource-local transactions only.

442P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 443: Hana Cloud

DDL Generation Type

The persistence service uses the EclipseLink capabilities for generating database tables. The following values are valid for generating the DDL for the entity specified in the persistence.xml file:

● none: EclipseLink does not generate a DDL (no schema is generated).● create-tables: EclipseLink attempts to execute a CREATE TABLE SQL. It creates a DDL for non-existent

tables and leaves existing tables unchanged (they are not dropped or replaced).● drop-and-create-tables: EclipseLink attempts to DROP all tables and then CREATE all tables.

NoteThis option will often be used during the development phase, when there are frequent changes to the schema or data needs to be deleted. Don't forget to change it to create-tables before the application goes live, since all data is lost when a table is dropped.

1.3.6.2.2 Entity Classes

To declare a class as an entity and define how that entity maps to the relevant database table, you can either decorate the Java object with metadata using Java annotations or denote it as an entity in the XML descriptor.

The Dali Java Persistence Tools provided as part of the Eclipse IDE for Java EE Developers allow you to use a JPA diagram editor to create, edit, and display entities and their relationships (your application’s data model) in a graphical environment. For more information about the Dali Java Persistence Tools, see the User Guide at http://www.eclipse.org/webtools/dali/docs/dali_user_guide_2.2.pdf.

ExampleThe tutorial Adding Application-Managed Persistence with JPA (SDK 1.x) [page 420] defines the entity class Person, as shown below:

package com.sap.cloud.sample.persistence;import javax.persistence.*;@Entity@Table(name = "T_PERSON")@NamedQuery(name = "AllPersons", query = "select p from Person p")public class Person {

@Id @GeneratedValue private long id; @Basic private String FirstName; @Basic private String LastName;

● The Person class has been annoted as an entity: @Entity.● The @Table annotation maps the entity to the database table T_PERSON.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 443

Page 444: Hana Cloud

● The @NamedQuery annotation indicates that a static query has been created in the metadata. The name element of @NamedQuery gives the name of the query that will be used with the createNamedQuery() method, while the query element specifies the actual query.

● The definition of the field serving as the unique identifier of the entity has been annotated with @Id, indicating it is the primary key in the database. Its value is generated automatically (@GeneratedValue).

1.3.6.2.3 Default Data Source

Overview

The persistence service provides every application deployed on the SAP HANA Cloud Platform with its own database user and schema, provided the default data source is used.

Injection Scenarios (SDK 2.x)

For both container-managed persistence and application-managed persistence, the container (JPA container or OpenEJB container, depending on your application) automatically makes available the default data source. Since the persistence service only supports one data source at present, it is not necessary to explicitly declare a data source in the persistence.xml file or web.xml deployment descriptor. The persistence service provides either a managed or unmanaged data source, depending on the transaction type specified in the persistence.xml file.

Application-Managed Persistence with Manual Creation of the Entity Manager Factory

For this scenario, you can retrieve the default data source using a JNDI lookup or resource injection, as described in the sections below.

JNDI Lookup

The persistence service binds the default data source that maps to your Web application's database schema as a resource to Tomcat's JNDI (Java Naming and Directory Interface) registry. Before you can consume the data source in your Web application, you need to declare a reference to the default data source provided by the persistence service.

The JNDI resource reference to a JDBC DataSource object factory is declared in the web.xml deployment descriptor in the WebContent/WEB-INF directory as shown below. Note that the resource reference name is just an example:

<resource-ref>

444P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 445: Hana Cloud

<res-ref-name>jdbc/DefaultDB</res-ref-name> <res-type>javax.sql.DataSource</res-type></resource-ref>

The resource attributes denote the following:

● Name: The JNDI name of the resource. The Java EE Specification recommends that the data source reference be declared in the jdbc subcontext (jdbc/NAME).

● Type: The type of resource that will be returned during the lookup.

The <resource-ref> elements should be added after the <servlet-mapping> elements in the deployment descriptor.

You can obtain an initial JNDI context from Tomcat by creating a javax.naming.InitialContext object, and then consume the data source by looking up the naming environment through the InitialContext, as follows:

InitialContext ctx = new InitialContext();DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/DefaultDB");

Note that according to the Java EE Specification, the prefix java:comp/env should be added to the JNDI resource name (as specified in web.xml) to form the lookup name.

For more information about defining and referencing resources according to the Java EE standard, see the Java EE Specification.

Data Source Injection

You can directly inject the data source using annotations as shown in the example below. You do not need to declare the JNDI resource reference in the web.xml deployment descriptor nor in the resource name, since the persistence service will automatically provide the default data source.

@Resourceprivate javax.sql.DataSource ds;

1.3.6.2.4 Container-Managed Entity Managers

Overview

Container-managed entity managers are the model most commonly used by web applications. Container-managed entity managers require JTA transactions. Generally, container-managed entity managers are used with stateless session beans and transaction-scoped persistence contexts, which are thread-safe. This model is described in the sections below.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 445

Page 446: Hana Cloud

Entity Manager Injection

EJB session beans, which encapsulate the business logic of your application and typically perform the database operations, can use the @PersistenceContext annotation to directly inject the entity manager. The corresponding entity manager factory is created transparently by the container. Note that a persistence context type has not been explicitly specified in the example below and is therefore, by default, transaction-scoped:

@PersistenceContextprivate EntityManager em;

If you have more than one persistence unit, you also need to specify the persistence unit name (@PersistenceContext(unitName = "<persistence unit name>")).

Transaction Management

The persistence context made available is based on JTA and provides automatic transaction management. Each EJB business method automatically has a managed transaction, unless specified otherwise. The entity manager life cycle, such as its instantiation and closing, is controlled by the container. Methods designed for resource-local transactions, such as em.getTransaction().begin(), em.getTransaction().commit(), and em.close(), must therefore not be used.

Session Bean Injection

An instance of the EJB session bean class can be injected into the servlet of the web application with an annotation in the following form, where PersonBean is an example session bean class:

@EJB PersonBean personBean;

Extended Persistence Contexts

An extended persistence context allows a session bean to maintain its state across multiple JTA transactions. To use an extended persistence context, the value of the persistence context type has to be set to EXTENDED (@PersistenceContext(type=PersistenceContextType.EXTENDED)) and the session bean declared as stateful. Bear in mind that an extended persistence context is not thread-safe.

446P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 447: Hana Cloud

1.3.6.2.5 Application-Managed Entity Managers

Entity Manager Factory

The EntityManagerFactory interface is used to create and manage the entity managers in your Web application. You can create an entity manager factory as follows:

● Manual creation of the entity manager factoryYou use javax.persistence.Persistence.createEntityManagerFactory to create an EntityManagerFactory object that operates on the default data source that you have retrieved as follows:

Map properties = new HashMap();properties.put(PersistenceUnitProperties.NON_JTA_DATASOURCE, ds);emf = Persistence.createEntityManagerFactory("persistence-with-jpa", properties);

In the code above, the non-JTA data source element has been set in the persistence unit properties, and the persistence unit name is the name of the persistence unit declared in the persistence.xml file.

NoteYou are advised to include the above code in the servlet init() method, as illustrated in the tutorial Adding Application-Managed Persistence with JPA (SDK 1.x) [page 420], since this method is called only once during initialization when the servlet instance is loaded.

● Injection of the entity manager factory (SDK 2.x)You inject the entity manager factory using the @PersistenceUnit annotation, as shown in the example below:

@PersistenceUnitEntityManagerFactory emf;

Entity Manager

You can use the entity manager factory obtained above to create an entity manager as follows:

EntityManager em = emf.createEntityManager();

Transaction Management

Application-managed entity managers are always extended and therefore retain the entities beyond the scope of a transaction. You should therefore close an entity manager when it is no longer needed by calling EntityManager.close() or alternatively EntityManager.clear() wherever appropriate, such as at the end of a transaction. Bear in mind that an entity manager must not be used concurrently by multiple threads, so design your entity manager handling in such a way that concurrent access of entity managers is prevented.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 447

Page 448: Hana Cloud

Related LinksEntity Transaction API [page 448]

Entity Transaction API

When working with a resource-local entity manager, the transaction boundaries need to be set manually in your application code using the EntityTransaction API. You can obtain the entity transaction attached to the entity manager by calling EntityManager.getTransaction().

To create and update data in the database, you require an active transaction. The EntityTransaction API provides the begin() method for starting a transaction, and the commit() and rollback() methods for ending a transaction. When a commit is executed, all changes are synchronized with the database.

ExampleThe tutorial code (Adding Application-Managed Persistence with JPA (SDK 1.x) [page 420]) shows how to create and persist an entity:

Person person = new Person("<name>");em.getTransaction().begin();em.persist(person); em.getTransaction().commit(); em.close();

The EntityManager.persist() method makes an entity persistent by associating it with an entity manager. It is inserted into the database when the commit() method is called. The persist() method can only be called on new entities.

1.3.6.3 Using Plain JDBC

Overview

Although JPA is suited for most application development scenarios and is the recommended approach on SAP HANA Cloud, there might be particular cases where the low-level control provided by JDBC is more appropriate. Bear in mind, however, that working with JDBC entails manually writing SQL statements to read and write objects from and to the database.

Default Data Source

The default data source provided by the persistence service allows each application deployed on the SAP HANA Cloud Platform to access a dedicated database schema. To retrieve the default data source, you can use a JNDI lookup or resource injection.

448P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 449: Hana Cloud

JNDI Lookup

The persistence service binds the default data source that maps to your Web application's database schema as a resource to Tomcat's JNDI (Java Naming and Directory Interface) registry. Before you can consume the data source in your Web application, you need to declare a reference to the default data source provided by the persistence service.

The JNDI resource reference to a JDBC DataSource object factory is declared in the web.xml deployment descriptor in the WebContent/WEB-INF directory as shown below. Note that the resource reference name is just an example:

<resource-ref> <res-ref-name>jdbc/DefaultDB</res-ref-name> <res-type>javax.sql.DataSource</res-type></resource-ref>

The resource attributes denote the following:

● Name: The JNDI name of the resource. The Java EE Specification recommends that the data source reference be declared in the jdbc subcontext (jdbc/NAME).

● Type: The type of resource that will be returned during the lookup.

The <resource-ref> elements should be added after the <servlet-mapping> elements in the deployment descriptor.

You can obtain an initial JNDI context from Tomcat by creating a javax.naming.InitialContext object, and then consume the data source by looking up the naming environment through the InitialContext, as follows:

InitialContext ctx = new InitialContext();DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/DefaultDB");

Note that according to the Java EE Specification, the prefix java:comp/env should be added to the JNDI resource name (as specified in web.xml) to form the lookup name.

For more information about defining and referencing resources according to the Java EE standard, see the Java EE Specification.

Data Source Injection

You can directly inject the data source using annotations as shown in the example below. You do not need to declare the JNDI resource reference in the web.xml deployment descriptor nor in the resource name, since the persistence service will automatically provide the default data source.

@Resourceprivate javax.sql.DataSource ds;

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 449

Page 450: Hana Cloud

JDBC Connection

The default data source that you have retrieved in the section above allows you to create a JDBC connection to the database. You can use the resulting Connection object to instantiate a Statement object and execute SQL statements, as shown in the example below.

private static final String STMT_SELECT_ALL = "SELECT ID, FIRSTNAME, LASTNAME FROM " + TABLE_NAME;Connection conn = dataSource.getConnection(); try { PreparedStatement pstmt = conn.prepareStatement(STMT_SELECT_ALL); ResultSet rs = pstmt.executeQuery(); ...

Database Tables

You use plain SQL statements to create the tables you require. Since there is currently no tool support available, you have to manually maintain the table life cycles. The exact syntax to be used may differ depending on the underlying database. The Connection object provides metadata about the underlying database and its tables and fields, which can be accessed as shown in the code below:

String database = conn.getMetaData().getDatabaseProductName();

To create a table in the Apache Derby database, you could use the following SQL statement executed with a PreparedStatement object:

private static final String STMT_CREATE_TABLE_DERBY = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, " + "FIRSTNAME VARCHAR (255), LASTNAME VARCHAR (255))";

PreparedStatement pstmt = conn.prepareStatement(STMT_CREATE_TABLE_DERBY);pstmt.executeUpdate();

Note that the equivalent statement for SAP MaxDB differs as follows:

private static final String STMT_CREATE_TABLE_MAXDB = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER DEFAULT SERIAL PRIMARY KEY, " + "FIRSTNAME VARCHAR (255), LASTNAME VARCHAR (255))";

DAO Objects and SQL Statements

See the tutorial Adding Persistence Using JDBC [page 430] for an example of how to execute SQL statements and apply the Data Access Object (DAO) design pattern in your Web application.

Note

450P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 451: Hana Cloud

Remember that the persistence service only supports SAP MaxDB and the SAP HANA database on the SAP HANA Cloud platform. If you use Apache Derby for local development, your application might behave differently in the cloud, since the syntax of the SQL statements is not identical on these databases.

1.3.6.4 Creating SAP HANA Column-Store Tables

Overview

The SAP HANA database allows tables to be created with row-based storage or column-based storage. By default, tables are created with row-based storage, but you can change the type of table storage you have applied, if necessary.

The example below shows the SQL syntax used by the SAP HANA database to create different table types. The first two SQL statements both create row-store tables, the third a column-store table, and the fourth changes the table type from row-store to column-store:

CREATE TABLE T_PERSONCREATE ROW TABLE T_PERSONCREATE COLUMN TABLE T_PERSONALTER TABLE T_PERSON COLUMN

EclipseLink JPA

When using EclipseLink JPA for data persistence, the table type applied by default in the SAP HANA database is row-store. To create a column-store table or alter an existing row-store table, you can manually modify your database using SQL DDL statements, or you can use open source tools, such as Liquibase (with plain SQL statements), to handle automated database migrations.

Due to the limitations of the EclipseLink schema generation feature, you will need to use one of the above options anyway to handle the life cycle management of your database objects.

ALTER TABLE Example

This section shows how you can use the ALTER TABLE statement to change a row-store table created by default in the SAP HANA database to a column-store table. The example is based on the Adding Persistence Using JPA (SDK 1.x) tutorial and provides a solution designed specifically for this tutorial and use case. It is not intended as a model for wider use.

The example allows you to take advantage of the automatic table generation feature provided by JPA EclipseLink. You merely alter the existing table at an appropriate point, when the schema containing the relevant table has just been created. The applicable code snippet is added to the init() method of the servlet (PersistenceWithJPAServlet). The main changes to the servlet code are outlined below:

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 451

Page 452: Hana Cloud

1. Since the table must already exist when the ALTER statement is called, a small workaround is introduced in the init() method. An entity manager is created at an earlier stage than in the original version of the tutorial in order to trigger the generation of the schema:

//workaround: create EntityManager to trigger schema generationemf.createEntityManager().close();

2. The SAP HANA database table SYS.M_TABLES contains information about all row and column tables in the current schema. A new method is added to the servlet which uses this table to check that T_PERSON is not already a column-store table.

3. Another new method alters the table using the SQL statement ALTER TABLE <table name> COLUMN.

To apply the solution, replace the entire servlet class PersistenceWithJPAServlet with the following content:

package com.sap.cloud.sample.persistence;

import java.io.IOException;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.HashMap;import java.util.List;import java.util.Map;

import javax.naming.InitialContext;import javax.naming.NamingException;import javax.persistence.EntityManager;import javax.persistence.EntityManagerFactory;import javax.persistence.Persistence;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.sql.DataSource;

import org.eclipse.persistence.config.PersistenceUnitProperties;import org.slf4j.Logger;import org.slf4j.LoggerFactory;

import com.sap.security.core.server.csi.IXSSEncoder;import com.sap.security.core.server.csi.XSSEncoder;

/** * Servlet implementing a simple JPA based persistence sample application for SAP HANA Cloud. */public class PersistenceWithJPAServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger LOGGER = LoggerFactory.getLogger(PersistenceWithJPAServlet.class); private static final String SQL_GET_TABLE_TYPE = "SELECT TABLE_NAME, TABLE_TYPE FROM SYS.M_TABLES WHERE TABLE_NAME = ?"; private static final String PERSON_TABLE_NAME = "T_PERSON";

private DataSource ds; private EntityManagerFactory emf;

/** {@inheritDoc} */ @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void init() throws ServletException { Connection connection = null;

452P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 453: Hana Cloud

try { InitialContext ctx = new InitialContext(); ds = (DataSource) ctx.lookup("java:comp/env/jdbc/DefaultDB");

Map properties = new HashMap(); properties.put(PersistenceUnitProperties.NON_JTA_DATASOURCE, ds); boolean onHANA = runsOnHANADatabase(); if (onHANA) { properties.put("eclipselink.target-database", "com.sap.persistence.platform.database.HDBPlatform"); }

emf = Persistence.createEntityManagerFactory("persistence-with-jpa", properties);

// convert T_PERSON to column table // workaround: create EntityManager to trigger schema generation emf.createEntityManager().close(); if (onHANA) { convertToColumnTable(PERSON_TABLE_NAME); } } catch (NamingException e) { throw new ServletException(e); } catch (SQLException e) { LOGGER.error("Could not determine database product.", e); throw new ServletException(e); } finally { if (connection != null) { try { connection.close(); } catch (SQLException x) { LOGGER.debug("Unable to close connection.", x); } } } }

/** {@inheritDoc} */ @Override public void destroy() { emf.close(); }

/** {@inheritDoc} */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().println("<p>Persistence with JPA Sample!</p>"); try { appendPersonTable(response); appendAddForm(response); } catch (Exception e) { response.getWriter().println("Persistence operation failed with reason: " + e.getMessage()); LOGGER.error("Persistence operation failed", e); } }

/** {@inheritDoc} */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { doAdd(request); doGet(request, response); } catch (Exception e) { response.getWriter().println("Persistence operation failed with reason:

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 453

Page 454: Hana Cloud

" + e.getMessage()); LOGGER.error("Persistence operation failed", e); } }

private void appendPersonTable(HttpServletResponse response) throws SQLException, IOException { // Append table that lists all persons EntityManager em = emf.createEntityManager(); try { @SuppressWarnings("unchecked") List<Person> resultList = em.createNamedQuery("AllPersons").getResultList(); response.getWriter().println( "<p><table border=\"1\"><tr><th colspan=\"3\">" + (resultList.isEmpty() ? "" : resultList.size() + " ") + "Entries in the Database</th></tr>"); if (resultList.isEmpty()) { response.getWriter().println("<tr><td colspan=\"3\">Database is empty</td></tr>"); } else { response.getWriter().println("<tr><th>First name</th><th>Last name</th><th>Id</th></tr>"); } IXSSEncoder xssEncoder = XSSEncoder.getInstance(); for (Person p : resultList) { response.getWriter().println( "<tr><td>" + xssEncoder.encodeHTML(p.getFirstName()) + "</td><td>" + xssEncoder.encodeHTML(p.getLastName()) + "</td><td>" + p.getId() + "</td></tr>"); } response.getWriter().println("</table></p>"); } finally { em.close(); } }

private void appendAddForm(HttpServletResponse response) throws IOException { // Append form through which new persons can be added response.getWriter().println( "<p><form action=\"\" method=\"post\">" + "First name:<input type=\"text\" name=\"FirstName\">" + "&nbsp;Last name:<input type=\"text\" name=\"LastName\">" + "&nbsp;<input type=\"submit\" value=\"Add Person\">" + "</form></p>"); }

private void doAdd(HttpServletRequest request) throws ServletException, IOException, SQLException { // Extract name of person to be added from request String firstName = request.getParameter("FirstName"); String lastName = request.getParameter("LastName");

// Add person if name is not null/empty EntityManager em = emf.createEntityManager(); try { if (firstName != null && lastName != null && !firstName.trim().isEmpty() && !lastName.trim().isEmpty()) { Person person = new Person(); person.setFirstName(firstName); person.setLastName(lastName); em.getTransaction().begin(); em.persist(person); em.getTransaction().commit(); } } finally { em.close();

454P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 455: Hana Cloud

} }

private boolean runsOnHANADatabase() throws SQLException { boolean onHANA = false; Connection connection = ds.getConnection(); try { String databaseProductName = connection.getMetaData().getDatabaseProductName(); if (databaseProductName.equals("HDB")) { onHANA = true; } } finally { connection.close(); } return onHANA; }

private void convertToColumnTable(String tableName) throws SQLException { if (!isColumnTable(tableName)) { Connection connection = ds.getConnection(); try { String sql = "ALTER TABLE " + tableName + " COLUMN"; PreparedStatement stmt = connection.prepareStatement(sql); stmt.executeUpdate(); stmt.close(); } finally { connection.close(); } } }

private boolean isColumnTable(String tableName) throws SQLException { boolean exists = false; boolean columnTable = false; Connection connection = ds.getConnection(); String tableTypeStart = null; try { PreparedStatement stmt = connection.prepareStatement(SQL_GET_TABLE_TYPE); stmt.setString(1, tableName); ResultSet rs = stmt.executeQuery(); while (rs.next()) { exists = true; tableTypeStart = rs.getString(2); break; } rs.close(); if (!exists) { throw new SQLException("Table " + tableName + " does not exist"); } if (tableTypeStart.equalsIgnoreCase("COLUMN")) { columnTable = true; } } finally { connection.close(); } return columnTable; }}

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 455

Page 456: Hana Cloud

1.3.6.5 Changing the Local Database

Context

An application developed for SAP HANA Cloud may be executed in different environments, where development and testing typically occur on a developer's PC, regression testing on a build server, and deployment on the Cloud platform.

The persistence service allows an application to abstract from the different execution environments by externalizing the connection data. It automatically establishes connections to the default databases Apache Derby (local development) and SAP MaxDB or the SAP HANA database (deployment in the cloud). You have the option of replacing your local embedded Derby instance with SAP MaxDB (version 7.8.02.23).

NoteSince the SAP HANA Cloud SDK includes the MaxDB JDBC driver, you do not need to explicitly add the JDBC driver JAR to the WEB-INF/lib folder of your Web application project.

Procedure

1. In the Project Explorer view, open the folder Servers/SAP HANA Cloud local runtime/config_master/connection_data and select connection.properties.

2. From the context menu, choose Open With Properties File Editor .3. Comment out the connection parameters for the local Derby database connection and instead comment in

those for SAP MaxDB. (This also changes the target database for EclipseLink.)4. Specify the parameters for host, instance, user, and password according to your system setup.5. Save the file.

1.3.6.6 Using the SQL Trace

Overview

The SQL trace provides a log of selected SQL statements. It allows you to identify inefficient SQL statements used in your applications and investigate performance issues, irrespective of whether you are using JPA or plain JDBC. The SQL trace records are integrated in the standard trace log files written at runtime and contain information about when the statement was executed and its duration.

456P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 457: Hana Cloud

Enabling the SQL Trace

The SQL trace is a tool that you use to check the behavior of a particular application and is disabled by default. Generally, you enable it when you require SQL trace information for a specific application and disable it again once you have completed your investigation. The SQL trace is not intended for general performance monitoring.

To enable the SQL trace, set the log level of the logger com.sap.core.persistence.sql.trace to the log level DEBUG. Use any of the options below:

● Eclipse IDEYou can set the log level for applications deployed locally or in the cloud as follows:

1. When you have deployed an application, double-click the started server in the Servers view.2. Switch to the Loggers tab and enter com.sap.core.persistence.sql.trace in the filter field.3. In the relevant row, select the log level DEBUG from the dropdown list.4. Save your changes.

● CockpitYou can set the log level for applications deployed in the cloud as follows:

1. Log into the cockpit from the SAP HANA Cloud landing page:

○ Customer and partner accounts: https://account.hana.ondemand.com○ Developer accounts: https://account.hanatrial.ondemand.com

2. Choose Applications in the navigation area and click the relevant application to go to the dashboard.3. In the navigation area, choose Logging.4. In the Log Settings section in the content area, a list of all loggers used by the application is shown with

the log levels that are currently applicable.5. Enter com.sap.core.persistence.sql.trace in the Filter field.6. In the relevant row, select the log level Debug from the dropdown list.

● Console clientYou can use the SAP HANA Cloud console client to set the log level as follows:

○ As a deployment property: Use the command neo deploy with the log parameter severity <log_level>.

NoteIf you use the deployment property to set the log level, the same log level will apply to all loggers, including the SQL trace, therefore potentially writing a large amount of log information.

○ As a logging property for applications you have deployed: Use the command neo set-log-level with the log parameters logger <logger_name> and level <log_level>.

Alternatively, the settings can be specified in a .properties file, which can then be entered as a command line parameter.For more information about deployment and logging, including where to find sample property files, see Deploying on the Cloud with the Console Client [page 537] and Managing Application Logs Using the Console Client [page 554] respectively.

● ProgrammaticallyYou can set the log level programmatically in your application as follows:

import org.apache.log4j.Level;

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 457

Page 458: Hana Cloud

import org.apache.log4j.Logger;

...

Logger logger = Logger.getLogger("com.sap.core.persistence.sql.trace");logger.setLevel(Level.DEBUG);

Displaying the SQL Trace Records

You can display the trace information as follows:

● Eclipse IDE

1. In the Servers view, select the server you have started, and from the context menu choose Show In Server Logs .

2. In the Server Logs view, double-click the relevant default trace log to display the SQL trace information.● Cockpit

1. Click the application for which you have enabled SQL tracing to go to the dashboard. The newest logs are listed in the Most Recent Logging screen area. The SQL trace records are integrated in the default trace logs (file name prefix ljs_trace_vsa).

2. Click the file name to display the log.

SQL Trace Information

The SQL trace records the following actions with their date and time, as well as a timestamp in nanoseconds for additional precision:

● Opening a database connection: Name of the SQL statement (interface and method) and the ID of the resulting database connection.

● Start of the execution of an SQL statement: Name of the SQL statement (interface and method) and, where applicable, the SQL statement text.

● Completion of the execution of an SQL statement: Name of the SQL statement (interface and method) and the duration of the statement in milliseconds with microsecond precision.

Related LinksLogging in Applications [page 550]

1.3.6.7 EclipseLink Weaving

Overview

EclipseLink provides weaving as a means of enhancing JPA entities and classes for performance optimization. At present, the SAP HANA Cloud platform supports static weaving only. Static weaving occurs at compile time and is

458P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 459: Hana Cloud

available in both the SDK 1.x and SDK 2.x environments. Note that dynamic weaving is currently not supported on theSAP HANA Cloud platform.

Prerequisites

For static weaving to work, the entity classes have to be listed in the persistence.xml file.

EclipseLink Library

To use the EclipseLink weaving options in your Web applications, you need to add the EclipseLink library to the classpath:

● SDK 1.xThe EclipseLink library has already been added to the WebContent/WEB-INF/lib folder, since it is required for the JPA persistence scenario.

● SDK 2.xThe EclipseLink library is already part of the SDK 2.x, allowing you to run JPA scenarios without any additional steps. To use the weaving options, however, you need to add the EclipseLink library to the classpath, as described below.

SDK 2.x: Adding the EclipseLink Library to the Classpath

1. In the Eclipse IDE in the Project Explorer view, select the Web application project node and from the context menu choose Properties.

2. In the tree, select JPA.3. In the Platform section, select the correct EclipseLink version from the dropdown list. It should match the

version available in the SDK (currently 2.4.x).4. In the JPA implementation section, select the type User Library from the dropdown list.5. To the right of the user library list box that is now visible, choose the Download library button.6. In the dialog box, select the correct version of the EclipseLink library (currently EclipseLink 2.4.1 –

Juno) and choose Next.7. Accept the EclipseLink license and choose Finish to close the wizard.8. The new user library now appears in the list box. Make sure that the checkbox is selected.9. Deselect the Include libraries with this application checkbox just below the user library box and choose OK.

Enabling Static Weaving in Eclipse

1. In the Eclipse IDE in the Project Explorer view, select the Web application project node and from the context menu choose Properties.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 459

Page 460: Hana Cloud

2. In the tree, select JPA EclipseLink .3. In the Static weaving section, select the Weave classes on build checkbox.4. The default values for the source classes, target classes, and persistence XML root can generally be left as

they are, but you might need to adapt them if you have a non-standard Web application project layout. Choose OK to complete the step.

NoteIf you change the target class settings, make sure you deploy these classes.

Your Web application project will be rebuilt so that the JPA entity class files contain weaving information. This will also occur on each (incremental) project build. The woven entity classes will be used whenever you publish the Web application to the SAP HANA Cloud platform.

More Information

For information about using an ant task or the command line to perform static weaving, see the EclipseLink User Guide.

1.3.6.8 Remote Database Access

The remote database access solution allows you to remotely access the relational databases used on the SAP HANA Cloud platform. This not only lets you investigate and repair application data, but also allows you to remotely create, drop, or modify an application’s database objects by issuing DDL statements, such as ALTER TABLE or CREATE INDEX.

The Remote Database Access Tool provides a JDBC driver, which is used on the client side, and a servlet, which is deployed on the server side. The two sides communicate via HTTPS and tunnel the JDBC commands and data over the Internet, bypassing firewalls. This approach allows you to use the Eclipse Data Tools (DTP) to accomplish the tasks outlined above. Although you can use the provided JDBC driver to perform database maintenance tasks remotely, you need to bear in mind that there are limitations and differences compared with using a real JDBC driver. A high-level overview is shown below:

460P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 461: Hana Cloud

NoteAt present, this functionality is available for SAP MaxDB only.

CautionThe functionality currently available is a beta version. Since you could potentially destroy database content while using the Remote Database Access Tool, we recommend that you use it solely in a non-production environment. Bear in mind that you are fully responsible for how you use the tool. We cannot offer any support or help in restoring destroyed data.

Security Considerations

The remote database access functionality is made available by a remote access servlet, which you deploy together with your Web application. Since the remote access servlet is deployed as part of your Web application, it means that you are fully responsible for all security aspects involved when deploying the servlet. In the scenario described in this section, basic authentication and administrative authorization have been added to the application, and the remote access servlet has been protected against cross-site request forgery (CSRF).

It is highly advisable to undeploy the remote access servlet as soon as it is no longer needed. To do this, simply redeploy a "pure" version of your application.

Binaries

To use the Remote Database Access Tool, you require two components:

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 461

Page 462: Hana Cloud

● JDBC driver JAR: dbaccess-beta.client.jar● Remote access servlet:

○ dbaccess-beta.server.jar○ dbaccess-beta.war

The binaries are delivered as part of the SDK 2.x and are contained in the <sdk 2.x>/add-ons/dbaccess folder.

Related LinksAdding the Remote Access Servlet to the Application [page 462]So that both the Web application and the remote access servlet access the same database schema, you need to add the servlet to your Web application and deploy them together.

Authorizing Remote Access to the Deployed Application [page 465]To allow a user remote access to the deployed Web application, they need to be assigned the administrator role jdbc_remote_access_admin for the Web application you have deployed.

Testing the Remote Access Servlet [page 465]To use the remote access functionality, the remote access servlet has be running. It displays a text containing the JDBC driver URL you require to remotely connect to the database in the cloud.

Connecting to the Remote Database [page 468]You use the Eclipse Data Tools (DTP) to connect to the database in the cloud.

Logging [page 469]The remote access tool supports both server-side logging and client-side logging.

Restrictions [page 470]When working with the Remote Database Access Tool, you should be aware of certain restrictions.

1.3.6.8.1 Adding the Remote Access Servlet to the Application

So that both the Web application and the remote access servlet access the same database schema, you need to add the servlet to your Web application and deploy them together.

Context

This step is necessary because the data from your database schema is only visible to applications on the same virtual machine (VM), and in the current standard landscape setup only one Web application can be deployed on a virtual machine at any one time.

You have two options for adding the servlet to your Web application:

● Deploy the remote access servlet dbaccess-beta.war in parallel to your existing Web application using the SAP HANA Cloud console client

● Modify your Web application to contain the remote access servlet dbaccess-beta.server.jar using the Eclipse IDE

Related Links

462P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 463: Hana Cloud

Deploying the Remote Access Servlet in Parallel to the Application [page 463]You use the SAP HANA Cloud console client to deploy the Web application and remote access servlet together on the same virtual machine.

Including the Remote Access Servlet in the Application [page 463]You use the Eclipse IDE to modify your Web application to contain the remote access servlet.

Deploying the Remote Access Servlet in Parallel to the Application

You use the SAP HANA Cloud console client to deploy the Web application and remote access servlet together on the same virtual machine.

Procedure

1. Create a WAR archive for your Web application.2. To deploy both the Web application and remote access servlet from the same folder, copy your WAR archive

and the remote access servlet dbaccess-beta.war (contained in the add-ons/dbaccess folder of the SAP HANA Cloud SDK 2.x) to a separate folder in your local file system.

3. Deploy the application and servlet using the console client.

Related LinksDeploying on the Cloud with the Console Client [page 537]Deploying an application publishes it to SAP HANA Cloud. During deploy, you can define various specifics of the deployed application using the deploy command optional parameters.

Including the Remote Access Servlet in the Application

You use the Eclipse IDE to modify your Web application to contain the remote access servlet.

Procedure

1. Add dbaccess-beta.server.jar to the lib folder of your Web application:

a) In the Eclipse IDE in the Project Explorer view, select the <project name>/WebContent/WEB-INF/lib node.

b) From the context menu, choose Import General File System and then Next.c) Browse to the local directory where you downloaded and unpacked the 2.x SDK, select the add-ons/

dbaccess directory, and choose OK.d) Select the checkbox dbaccess-beta.server.jar and choose Finish.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 463

Page 464: Hana Cloud

2. Open the web.xml file of your Web application in the <project name>/WebContent/WEB-INF folder and add the following code:

<servlet> <description></description> <display-name>RemotingServlet</display-name> <servlet-name>RemotingServlet</servlet-name> <servlet-class>com.sap.core.jdbc.remoteaccess.server.RemotingServlet</servlet-class></servlet><servlet-mapping> <servlet-name>RemotingServlet</servlet-name> <url-pattern>/RemotingServlet/*</url-pattern></servlet-mapping>

<security-constraint> <web-resource-collection> <web-resource-name>Protected Tunnel</web-resource-name> <url-pattern>/RemotingServlet/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>jdbc_remote_access_admin</role-name> </auth-constraint></security-constraint><login-config> <auth-method>BASIC</auth-method></login-config><security-role> <description>Administrators</description> <role-name>jdbc_remote_access_admin</role-name></security-role>

3. Add the following code to the web.xml file to apply a filter that protects the tool from cross-site request forgery (CSRF):

<!-- This filter protects the remote access servlet from cross-site request forgery and must be added for security reasons. The remote access servlet checks that the filter exists and fails if it is not registered. --> <filter> <filter-name>RestCSRF</filter-name> <filter-class>com.sap.core.js.csrf.RestCsrfPreventionFilter</filter-class> </filter> <filter-mapping> <filter-name>RestCSRF</filter-name> <servlet-name>RemotingServlet</servlet-name> </filter-mapping>

4. Make sure that the web.xml file contains a valid data source specification, similar to that shown below:

<resource-ref> <res-ref-name>jdbc/DefaultDB</res-ref-name> <res-type>javax.sql.DataSource</res-type></resource-ref>

5. Deploy your modified Web application on SAP HANA Cloud (select the servlet and choose Run As Run On Server ).

464P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 465: Hana Cloud

1.3.6.8.2 Authorizing Remote Access to the Deployed Application

To allow a user remote access to the deployed Web application, they need to be assigned the administrator role jdbc_remote_access_admin for the Web application you have deployed.

Context

To assign yourself the role, use the authorization functionality available from the cockpit.

Procedure

1. Open the cockpit:https://account.hanatrial.ondemand.com

2. Choose Authorizations in the navigation area.3. Assign the role jdbc_remote_access_admin to your user.

For more information about how to proceed, see Managing Role Assignments [page 501].

NoteThe administrator role jdbc_remote_access_admin allows full read and write access, meaning that all JDBC features can be used, subject to certain restrictions related to the tool. Users not assigned to this role will not be granted remote access. Do not change the role name in the web.xml file, since the remote access servlet checks that the user is a member of this particular role.

Related LinksRestrictions [page 470]When working with the Remote Database Access Tool, you should be aware of certain restrictions.

1.3.6.8.3 Testing the Remote Access Servlet

To use the remote access functionality, the remote access servlet has be running. It displays a text containing the JDBC driver URL you require to remotely connect to the database in the cloud.

Procedure

1. Open the cockpit (https://account.hanatrial.ondemand.com):

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 465

Page 466: Hana Cloud

○ If you have deployed the remote access servlet in parallel as a WAR file, the URLs link for your application should have two entries, one for the Web application and one for the remote access servlet. Click the remote access servlet URL, typically formed as follows:

https://<your app name><your account name>.hanatrial.ondemand.com/com.sap.core.jdbc.remoteaccess.server

○ If you have included the remote access servlet as a JAR file in your application, you will have one URL link for your application. Click the application URL and then add "RemotingServlet", as follows:

https://<your app name><your account name>.hanatrial.ondemand.com/<your app context root>/RemotingServlet

Alternatively, simply enter this URL directly in a browser.2. When prompted, enter your authentication details.

A popup appears confirming that the remote access servlet (remoting servlet) is running. It includes the driver URL details, which you will need later on:

○ WAR file version

Driver URL: jdbc:remotedb:https://<your app name><your account name>.hanatrial.ondemand.com/com.sap.core.jdbc.remoteaccess.server/RemotingServlet

○ JAR file version

Driver URL: jdbc:remotedb:https://<your app name><your account name>.hanatrial.ondemand.com/<your app context root>/RemotingServlet

3. Leave the web page open or, alternatively, make a note of the JDBC driver URL, as shown on the page. You will need it in the next section.

1.3.6.8.4 Proxy Settings

If you are running the Eclipse IDE on a machine that requires a proxy to access the Internet or other networks, you need to provide your proxy settings so that the remote access servlet deployed as part of your application can be reached from the JDBC driver.

When using the Eclipse Data Tools (DTP), we recommend that you provide your proxy settings as system properties. The following proxy settings are needed:

https.proxyHost=<host name of your proxy server, for example, proxy>https.proxyPort=<port number of your proxy server, for example, 8080>

The easiest way to set these properties is to use the Eclipse Preferences page for Network Connections (in the main menu, choose Window Preferences General Network Connections . Eclipse promotes the settings made on this page to Java system properties. The settings required are shown below. In the example, proxyHost has been set to proxy and proxyPort to 8080. Note that the Active Provider field needs to be set to Manual:

466P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 467: Hana Cloud

Alternatively, you can define the settings as system or user-specific environment variables for your computer. Under Windows you can do this by clicking Start Control Panel System and Security System Advanced System Settings Environment Variables . Create the variables given above with the values required for your proxy server.

Further Options for Proxy Settings

Besides using system properties, as described above, proxy settings can also be defined as URL or connection parameters:

● URL parameters: The driver URL you set for the driver can be extended with parameters that define the proxy. To do this, simply add the following at the end of your URL:

?https.proxyHost=<host name>&https.proxyPort=<port number>

● Connection parameters: The connection properties passed to the connect method of the driver class can also contain proxy definitions, which are passed with the following parameters:

https.proxyHost=<host name>https.proxyPort=<port number>

Whether you can define these parameters and where you do it depends on the tool you are using. The DTP allows the parameters to be defined when you create a new connection or connect to an existing one (Optional tab of the Connection Properties dialog box):

The Remote Database Access Tool checks for proxy definitions in the following order:

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 467

Page 468: Hana Cloud

1. URL parameters2. Connections parameters3. System properties

The first definition found is used and any subsequent definitions are ignored. If no parameters are set, the tool connects directly to the servlet and bypasses any proxies.

1.3.6.8.5 Connecting to the Remote Database

You use the Eclipse Data Tools (DTP) to connect to the database in the cloud.

Prerequisites

You have defined your proxy settings. For more information, see Proxy Settings [page 466].

Procedure

1. Define a new database driver:

a) In the Eclipse main menu, choose Window Preferences Data Management Connectivity Driver Definitions .

b) Choose the Add button.c) As the driver template, select MaxDB JDBC Driver Version 7.7.d) Enter a driver name, for example, Remote Access JDBC Driver.e) On the JAR List tab, add the path to the driver JAR file, <sdk 2.x>/add-ons/dbaccess/dbaccess-

beta.client.jar, and remove the predefined one.f) Choose OK to confirm and then OK again to complete this step.

2. Define a new database connection:a) Open the Data Source Explorer view.b) Select the Database Connections node, and from the context menu choose New.c) Select the connection profile type MaxDB.d) Enter a connection name, for example, Remote Access to MaxDB, and choose Next.e) Select the JDBC driver you defined in step 1(d), for example, Remote Access JDBC Driver.f) In the URL field, enter the driver URL shown in the remote access servlet, as in the examples below:

○ jdbc:remotedb:https://<your app name><your account name>.hanatrial.ondemand.com/<your context root>/RemotingServlet

○ jdbc:remotedb:https://<your app name><your account name>.hanatrial.ondemand.com/com.sap.core.jdbc.remoteaccess.server/RemotingServlet

g) Enter a valid SCN user and password. The user must be member of the role jdbc_remote_access_admin.

468P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 469: Hana Cloud

h) Choose Test Connection to check that a connection can be created.i) Choose Finish.j) Select the new database connection, and from the context menu choose Connect. You will need to enter

your password again.The schema belonging to your Web application is now shown in the Data Source Explorer view. Open the schema and navigate down to your Web application’s database tables, where you can display their properties and data and use the SQL Scrapbook editor.

1.3.6.8.6 Logging

The remote access tool supports both server-side logging and client-side logging.

Server-Side Logging

You can display server logs from the cockpit at https://account.hanatrial.ondemand.com.

For more information, see Applications [page 52], section Viewing the Logs.

Client-Side Logging

To enable client-side logging for output to a console and file (for example, c:/temp/log4j.log), you can do the following:

1. Create a configuration file with a name such as mylog4j.properties and insert the following content:

# Root logger has level INFOlog4j.rootLogger=INFO, stdout, file# Appender for consolelog4j.appender.stdout=org.apache.log4j.ConsoleAppender# Layout for appenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=[%t] %-5p %c - %m%n# Configuration of log filelog4j.appender.file=org.apache.log4j.RollingFileAppenderlog4j.appender.file.File=c:/temp/log4j.loglog4j.appender.file.MaxFileSize=500KB# Store one back up filelog4j.appender.file.MaxBackupIndex=1# Display additionally date in ISO-Format ISO-8601log4j.appender.file.layout=org.apache.log4j.PatternLayoutlog4j.appender.file.layout.ConversionPattern=%d [%t] %p %c - %m%n

2. Activate logging with a VM argument. For example, you could create a shortcut for lauching your IDE and then add following line to the shortcut target:

-vm C:\<jre_path>\bin\java.exe -vmargs -Dlog4j.configuration=file:/C:/temp/mylog4j.properties

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 469

Page 470: Hana Cloud

1.3.6.8.7 Restrictions

When working with the Remote Database Access Tool, you should be aware of certain restrictions.

In particular, bear in mind the following points:

● The tool always uses auto-commit mode and closes server-side database connections directly after each client-server roundtrip. Transactions are not supported and there is therefore no commit, rollback, or other globally effective settings.

● It does not support the import or export of huge amounts of data.

The current restrictions are listed by interface in the sections below.

java.sql.Connection

● Connection lives only for one roundtrip with auto commit. There is therefore no state on the client.● No commit, rollback, transaction isolation, save point, type map● No holdability, warnings, client info, read only, valid, native SQL● No creators for Blob, Clob, NClob, SQLXML, Struct, Array● No creators for statements with auto-generated keys, result set type, result set concurrency, result set

holdability● Not all meta data is returned

java.sql.Statement

● No connection, batch, pool, warnings, generated keys, query timeout, escape processing● No result set concurrency, result set holdability, result set type● No fetch, set max rows, cursor name, max field size

java.sql.PreparedStatement

● No result set meta data, parameter meta data● No Array, Blob, Clob, NClob, Date with calendar, NCharaterStream, NString with length, Object with target

SQL type and scale or length, Ref, row id, SQLXML, Time with calendar, UnicodeStream, URL

java.sql.CallableStatement

● No setter methods, no getter methods with parameter name● No Array, BigDecimal, Blob, Byte, CharacterStream, Clob, Date with calendar, NCharacterStream, NClob,

NString, Object, Ref, row id, SQLXML, Time with calendar, TimeStamp with Calendar, URL No wasNull

470P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 471: Hana Cloud

java.sql.ResultSet

● No absolute, after last, before first, first, last, previous, relative● No fetch methods● No cursor name● No warnings● No Array, AsciiStream, BinaryStream, Blob, CharacterStream, Clob, NCharacterStream, NClob, NString,

Object with SQL type, Ref, Row id, SQLXML, UnicodeStream● No delete row, insert row, refresh row, row deleted, row inserted, move to current row, move to inserted row● No update methods SAP HANA database: get server processing time always returns 0

Large Streams

Streams cannot be large, they have to fit into memory

1.3.6.9 JPA and JDBC APIs

API Description

JPA (Java Persistence API) http://download.oracle.com/otndocs/jcp/persistence-2.0-fr-oth-JSpec

javax.persistence http://download.oracle.com/javaee/6/api/javax/persistence/package-summary.html

EclipseLink framework http://wiki.eclipse.org/EclipseLink/UserGuide/JPA

JDBC (Java Database Connectivity API) http://download.oracle.com/javase/7/docs/technotes/guides/jdbc/

java.sql http://download.oracle.com/javase/7/docs/api/java/sql/package-summary.html

javax.sql http://download.oracle.com/javase/7/docs/api/javax/sql/package-summary.html

1.3.6.10 Frequently Asked Questions

Does the persistence service provide access to a NoSQL database?

The persistence service currently provides access to a relational database only.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 471

Page 472: Hana Cloud

Which database platforms are available in the cloud?

SAP HANA Cloud offers SAP MaxDB and the SAP HANA database.

How often does a backup occur? How much data can I lose in the worst case?

For productive databases, a full or incremental backup of the database files is triggered at least every 30 minutes. The corresponding data or log files are moved to a backup device every two hours.

In the case of a disk drive crash or file system corruption that requires recovery from a backup device, data that is younger than 2 ½ hours might be lost. However, in the rare case that a corrupt backup coincides with a fatal database problem you could theoretically lose even more data.

Backups are kept for 14 days and deleted afterwards. Recovery is therefore only possible within a time frame of 14 days.

I am using JPA with EclipseLink and have denoted a property of type String with @Lob. Why is a VARCHAR column of limited length created in the database?

Due to the EclipsLink bug 317597, the @Lob annotation is ignored when the corresponding table column is created in the database. In order to enforce the creation of a CLOB column, you have to additionally specify @Column(length=4001) for the property concerned. In fact, any value may be chosen as long as it is at least 4001 for SAP MaxDB or 2001 for the SAP HANA database.

I tested my app locally with the Apache Derby database, so why do I run into SQL exceptions when deploying it in the cloud?

Different database systems use different system tables and reserved words. As an application developer, you have to make sure that the application does not use any of these reserved words for its own table and column names.

JPA does also not shield the application from this. If, for example, your entity class contains an attribute named "date", this will clash with the reserved word DATE on SAP MaxDB and cause the schema creation to fail upon deployment. In such a case, the attribute should either be renamed to something else, or be mapped to another column name in the database. This can be done using the @Column annotation like this:

@Column(name="THEDATE")private String date;

Tips:

● Check the root cause in the application log. (A link to the log is provided on the Applications view of the cockpit. For more information, see Managing Deployed Applications.)

472P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 473: Hana Cloud

● For a complete list of reserved words, refer to the relevant database documentation (SAP MaxDB SQL Reference Manual, Apache Derby Documentation).

1.3.7 Consuming the Document Service

In this section you will learn how to use the SAP HANA Cloud document service in order to store unstructured or semistructured data in the context of your SAP HANA Cloud application.

Related LinksDocument Service Concepts [page 473]Document Service [page 15]

1.3.7.1 Document Service Concepts

Document Service Client API

The document service is exposed using the OASIS standard protocol Content Management Interoperability Service (CMIS) and can be consumed by any application that supports this protocol standard. The SAP HANA Cloud platform provides a document service client API that makes it much easier to consume the document service. The document service client API is based on the Open Source library OpenCMIS that is provided by the Apache Chemistry Project. To be able to manage documents in the SAP HANA Cloud document service, an application must be connected to a repository of the document service. A repository is a logical area containing the documents for your application. It has a unique name by which it can later be queried, and is secured by a key provided by the application. Only applications using this key are allowed to connect to this repository. Repositories can be created using the method EcmFactory.createRepository(repositoryOptions) and connected to using the method EcmFactory.connect(uniqueName,key) or EcmFactory.connect(uniqueName, key, user).

Once you are connected to the repository, you get an OpenCMIS session object to manage documents and folders in the connected repository. From here, you work only with the Open Source library OpenCMIS. For more information, including JavaDoc, a Developer's Guide, and sample code for OpenCMIS, see the Apache Chemistry pages linked in the section below.

User Management

The document service is not connected to a user management system and, therefore, does not perform any user authentication. The service treats user names as opaque strings that are defined by the application. When an application connects to the document service it can provide a user name by using the EcmFactory.connect(uniqueName, key, user) method. If the EcmFactory.connect(uniqueName, key) method is used, the user name of the user currently logged in is sent.

All actions in the document service are executed in the context of this user. That is, the service sets the properties cmis:createdBy and cmis:lastModifiedBy to the provided user name. It also uses the user name to evaluate Access Control Lists (ACLs). For more information, see the CMIS specification.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 473

Page 474: Hana Cloud

Repository Naming and Data Isolation

Repositories are identified either by their unique name or by their ID. The unique name is a human-readable name that should be constructed with Java package-name semantics, for example, com.foo.MySpecialRepository, to avoid name conflicts. The ID is computed by the document service and can also be used to connect to this repository. Repositories in the document service are secured by a key provided by the application. When a repository is first created, a key must be supplied. Any further attempts to connect to this repository will only succeed if the key provided by the connecting application matches the key that was used to create the repository. Therefore this key should be stored in a secure manner, for example, by using the Java KeyStore API. It is, however, up to the application to decide whether to share this key with other applications from the same account to implement data-sharing scenarios.

Multiple applications can access the same repository. However, it is only possible for applications to connect to the same repository with the unique name assigned to this repository if they are deployed within the same account, whereas applications that are deployed in a different account are not able to access this repository. A consequence of having repositories isolated within an account is that data cannot be shared across different accounts.

Example of Account Isolation

Repository ABC is created when Application 1 is deployed in Account 1. Application 2 is located in the same Account 1 as Application 1; therefore, Application 2 can also access the same repository by using its unique name ABC. Application 3 is deployed in Account 2. Application 3 calls a repository that has the same unique name ABC as the other repository that belongs to Account 1. However, by using the identical unique name, Application 3 will not be able to access the Repository ABC that belongs to Account 1 because the repositories are isolated within the account. Therefore, Application 3 in Account 2 will connect to another Repository ABC that belongs to Account 2. In summary, a repository is accessible only by applications that are deployed in the same account as the application that created the repository.

Related Linkshttp://chemistry.apache.org/http://chemistry.apache.org/java/developing/guide.htmlhttp://chemistry.apache.org/java/0.8.0/maven/apidocs/http://chemistry.apache.org/java/examples/index.htmlhttp://docs.oasis-open.org/cmis/CMIS/v1.1http://docs.oracle.com/javase/6/docs/api/java/security/KeyStore.html

1.3.7.2 Handling CMIS Metadata

One benefit of CMIS compared to a file system is the extended handling of metadata. Metadata give the ability to structure content and make it easier to find documents in a repository even if it contains millions of documents. In the CMIS domain model metadata are structured using types. A type contains the set of allowed or required properties, for example a type Invoice having the properties InvoiceNo and CustomerNo.

A type is described in a type definition and contains a list of property definitions. CMIS defines a set of predefined types and predefined properties. Custom-specific types and additional custom properties can extend the

474P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 475: Hana Cloud

predefined types. When a type is created it is derived from a parent type and extends the set of the parent properties. In this way a hierarchy of types is built. The base types do not have a parent. Base types are defined in the CMIS specification. The most important base types are cmis:document and cmis:folder.

Predefined properties contain metadata that are usually available in most of the existing repositories. These are, for example, cmis:name, cmis:createdBy, cmis:modifiedBy, cmis:createdAt, and cmis:modifiedAt. They contain the name of the author, the creation date, and the date of last modification. Some properties are type-specific, for example a folder has a parent folder and a document has a content-length property.

Each property has a data format (String, Integer, Date, Decimal, Id,…) and can define additional constraints such as:

● Required (must have a value)● Read-only (cannot be updated)● Value range (minimum value, maximum value)● Value list (value must be one of a fixed list of values)

A property is also either single-valued or multi-valued.

Each object stored in a CMIS repository has a type and a set of properties. Types and properties provide the mechanism how objects can be found using CMIS queries.

Metadata in the SAP HANA Cloud Document Service

The document store in SAP HANA Cloud supports the types cmis:document and cmis:folder. It also has a built-in subtype for versioned documents. The types can be investigated using the Apache CMIS workbench as tool.

In addition to the standard CMIS properties, the document service of HANA Cloud supports additional SAP properties. The most important ones are sap:owner (the owner of a document) and sap:tags. Sap:owner is used for ACLs (access control) and sap:tags is a multi-valued attribute used for tagging the content.

Related Linkshttp://docs.oasis-open.org/cmis/CMIS/v1.0/cmis-spec-v1.0.htmlhttp://chemistry.apache.org/java/download.html

1.3.7.2.1 Creating Metadata

Context

You can pass metadata when documents are created. The CMIS client API uses a map to pass properties. The key of the map is the property ID and the value is the actual value to be passed. The properties cmis:name and cmis:objectTypeId are mandatory.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 475

Page 476: Hana Cloud

Procedure

1. Use a name that is unique within the folder and a type ID that is a valid type from the repository.2. Run the exemplary code.

// propertiesMap<String, Object> properties = new HashMap<String, Object>();properties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document");properties.put(PropertyIds.NAME, "Document-1");

// contentbyte[] content = "Hello World!".getBytes();InputStream stream = new ByteArrayInputStream(content);ContentStream contentStream = new ContentStreamImpl(name, BigInteger.valueOf(content.length), "text/plain", stream);

// create a documentFolder root = session.getRootFolder();Document newDoc = folder.createDocument(properties, contentStream, VersioningState.NONE

You can inspect the document in the CMIS workbench.

You can see that various other properties have been set from the system, like the ID, the creation date, and the creating user.

1.3.7.2.2 Updating Properties

Context

The following procedure focuses on the use case that you want to use the sap:tags property to mark the document. This is a multi-value attribute, so you can assign more than one tag.

Procedure

1. To assign the tags “Hello” and “Tutorial” to our document, use the following code:

List<String> tags = Arrays.asList("Hello", "Tutorial");Map<String, Object> properties = new HashMap<String, Object>();properties.put("sap:tags", tags);

doc.updateProperties(properties);

2. Refresh the document in the CMIS workbench.You can see the following property:

476P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 477: Hana Cloud

Name Id Type Value

sap:tags sap:tags string Hello

Tutorial

1.3.7.2.3 Querying Properties

This section can only a give a very brief introduction. The CMIS Client API has much more capabilities like for example paging the results. For more information please consult the CMIS JavaDoc and the examples on the Apache Chemistry web site.

Context

The following procedure focuses on the use case that you have created a second folder and a couple of more documents. The repository then looks like this:

Hello-Document and Hi-Document have the tags Hello and Tutorial, Lorem-Ipsum has no tags.

Procedure

1. Use the CMIS query to search documents in the system based on their properties.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 477

Page 478: Hana Cloud

Note:The CMIS query language CMISQL is similar to SQL.

SELECT cmis:name, cmis:objectId, cmis:createdBy, sap:owner FROM cmis:document WHERE cmis:createdBy='john'

This query returns the following result set:

cmis:createdBy cmis:name sap:owner cmis:objectId

john Lorem Ipsum john <ID>

john Hi Document john <ID>

john Hello Document john <ID>

2. Query all documents with the tag Hello.

SELECT cmis:name, cmis:objectId, cmis:createdBy, sap:tags, sap:owner FROM cmis:document WHERE ANY sap:tags IN ('Hello')

Note: In this case, the workbench displays only the first value of multi-valued properties:

cmis:createdBy cmis:name sap:owner sap:tags cmis:objectId

john Lorem Ipsum john Hello

Tutorial

<ID>

john Hi Document john Hello

Tutorial

<ID>

3. Execute the query with the following code:

String query = "SELECT cmis:name, cmis:objectId, cmis:createdBy, " + "sap:tags, sap:owner FROM cmis:document WHERE ANY sap:tags " +"IN ('Hello')";

ItemIterable<QueryResult> results = session.query(query, false););

System.out.println("Name | Object-Id | Author | Tags");System.out.println("---------------------------------");for (QueryResult result : results) { String name = result.getPropertyValueByQueryName("cmis:name"); String id =result.getPropertyValueByQueryName("cmis:objectId"); String author = result.getPropertyValueByQueryName("cmis:objectId"); List<String> tags = result.getPropertyMultivalueByQueryName("sap:tags");

System.out.println(name + " | " + id + " | " + author + " | " + tags);}

This query produces the following output:

Name | Object-Id | Author | Tags --------------------------------- Hello-Document | 7L8S0XYG9dh7O1gGgkiA9gWl3gSIzYkYpYds6vnxA-M | john | [Hello, Tutorial] Hi-Document | 3ovtYi1sqWyUmXW3-zGg30OT-e2U12qiD_o-kf595YA | john | [Hello, Tutorial]

Related Linkshttp://chemistry.apache.org/java/0.8.0/maven/apidocs/http://chemistry.apache.org/java/examples/index.html

478P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 479: Hana Cloud

1.3.7.3 Accessing Document Service from External Applications

Overview

The services in the SAP HANA Cloud platform can be consumed by applications that are deployed within SAP HANA Cloud but not from external applications. There are cases, however, where applications want to access content in the cloud but cannot be deployed in the cloud.

Features

The figure below describes a mechanism how this scenario can be supported and is followed by an explanation:

This can be addressed by deploying an application in SAP HANA Cloud that accepts incoming requests from the Internet and forwards them to the ECM service. We refer to this type of application as a proxy bridge. The proxy bridge is deployed in SAP HANA Cloud and runs in an account using the common SAP HANA Cloud patterns. The proxy bridge is responsible for user authentication and is relevant for billing the resources consumed in the ECM service.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 479

Page 480: Hana Cloud

For more information, see the section about user propagation in Document Service Concepts linked below.

Related LinksDocument Service Concepts [page 473]

1.3.7.3.1 Building a Proxy Bridge

Context

All the standard mechanisms of the ECM service apply. The SAP HANA Cloud SDK provides a base class (a Java servlet) that provides the proxy functionality out-of-the-box. This can easily be extended to customize the behavior. The proxy bridge performs a 1:1 mapping from source CMIS calls to target CMIS calls. CMIS bindings can be enabled or disabled. Further modifications of the incoming requests, such as allowing only certain operations or modifying parameters, are not supported. The Apache OpenCMIS project contains a bridge module that supports such advanced scenarios.

Procedure

1. Create an SAP HANA Cloud application as described in Creating an SAP HANA Cloud Application linked below.2. Create a web.xml file and a servlet class.

3. Derive your servlet from class com.sap.ecm.api.AbstractCmisProxyServlet.

4. Add a servlet mapping to your web.xml file using a URL pattern that contains a wildcard as follows, for example:

<servlet> <servlet-name>cmisproxy</servlet-name> <servlet-class>my.app.CMISProxyServlet</servlet-class> </servlet>

<servlet-mapping> <servlet-name>cmisproxy</servlet-name> <url-pattern>/cmis/*</url-pattern> </servlet-mapping>

You can use prefixes other than /cmis and you can add more servlets according to your needs. The URL pattern for your servlet derived from class AbstractCmisProxyServlet must contain a /* suffix.

5. Override the two abstract methods provided by the AbstractCmisProxyServlet class: getRepositoryUniqueName() and getRepositoryKey().

These methods return a string containing the unique name and the secret key of the repository to be accessed. You can override a third method getDestinationName() also returning a string. If this method is overridden it should return the name of a destination deployed for this application to connect to the service. This is useful if a service user is used, for example. Ensure that you have then deployed this destination on the virtual machine.

480P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 481: Hana Cloud

6. Optionally, you can override the getServletConfig() method. To do so, call the superclass.

Do not override the following methods:

○ service()○ doGet()○ doPost()○ etc.

7. Optionally, you can restrict the proxy bridge to restrict the exposed bindings by overriding one or more of the following methods:

○ supportWebServicesBinding()○ supportAtomPubBinding()○ supportBrowserBinding()

At least one of the methods must return true.8. Optionally, you can override two more methods to customize timeout values for reading and connecting:

getConnectTimeout() and getReadTimeout().

It should only be necessary to use these methods if frequent timeout errors occur.The following code is an example of a proxy servlet:

package my.app;

import com.sap.ecm.api AbstractCmisProxyServlet;

public class CMISProxyServlet extends AbstractCmisProxyServlet {

@Override protected String getRepositoryUniqueName() { return "MySampleRepository"; }

@Override //For productive applications, use a secure location to store the secret key. protected String getRepositoryKey() { return "abcdef0123456789"; }

}

Related LinksUsing Java EE 6 Web Profile [page 65]

1.3.7.4 Getting Prepared for Local Development

Context

To use the document service in a Web application, download the SDK and install the MongoDB database. To install the MongoDB database, follow the steps described below:

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 481

Page 482: Hana Cloud

Procedure

1. Download the MongoDB database from http://www.mongodb.org/downloads.2. Unpack the file to a local directory (for example, c:\mongodb).

3. Create an empty directory (for example, c:\mongodb_data).

4. Start the MongoDB server and proceed as follows:a) Open a command prompt.b) Switch to the MongoDB bin directory (for example, c:\mongodb\bin).c) Enter the following command: mongod --dbpath C:\mongodb_data

Related LinksNext StepsUsing the Document Service in a Web Application [page 482]

1.3.7.5 Using the Document Service in a Web Application

Prerequisites

● You have downloaded and configured the SAP Eclipse platform. For more information, see Setting Up the Tools and SDK linked below.

● You have created a HelloWorld Web application as described in the Creating a HelloWorld Application tutorial linked below.

● You have downloaded the SDK used for local development.● You have installed MongoDB as described in Getting Prepared for Local Development.

Context

This tutorial describes how to extend the HelloWorld Web application to use the SAP HANA Cloud document service to manage unstructured content in your application. You test and run the Web application on your local server and the SAP HANA Cloud.

Procedure

1. Connect the HelloWorld Web application to the document service.The document service client library is used to connect to the document service. It connects to the local or central document service and returns an authenticated OpenCMIS session. If you are running your application locally in Eclipse IDE, the document service client library connects to a local document service of the SAP HANA Cloud SDK that is connected to your local MongoDB. If your application is deployed on SAP HANA Cloud, the document service client library connects to the document service that belongs to the corresponding system landscape.

482P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 483: Hana Cloud

2. Configure your Web application in the following way to enable user authentication if your application needs authenticated users and these users should be automatically propagated to the document service:a) Expand the HelloWorld/WebContent/WEB-INF node.b) Select the web.xml file and, from the context menu, choose Open.c) Enable authentication for your application.For more information on authentication see User Authentication linked below.

3. Connect to the document service and create a folder and a document.a) Expand the HelloWorld/Java Resources/src/hello node.b) Select the HelloWorldServlet.java file and, from the context menu, choose Open.c) Add the following code to HelloWorldServlet.java:

package hello;

import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStream;import java.util.HashMap;import java.util.Map;

import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

import org.apache.chemistry.opencmis.client.api.CmisObject;import org.apache.chemistry.opencmis.client.api.Document;import org.apache.chemistry.opencmis.client.api.Folder;import org.apache.chemistry.opencmis.client.api.ItemIterable;import org.apache.chemistry.opencmis.client.api.Session;import org.apache.chemistry.opencmis.commons.PropertyIds;import org.apache.chemistry.opencmis.commons.data.ContentStream;import org.apache.chemistry.opencmis.commons.enums.VersioningState;import org.apache.chemistry.opencmis.commons.exceptions.CmisNameConstraintViolationException;import org.apache.chemistry.opencmis.commons.exceptions.CmisObjectNotFoundException;

import com.sap.ecm.api.RepositoryOptions;import com.sap.ecm.api.RepositoryOptions.Visibility;import com.sap.ecm.api.EcmService;import javax.naming.InitialContext;

/** * Servlet implementation class HelloWorldServlet */public class HelloWorldServlet extends HttpServlet { private static final long serialVersionUID = 1L;

/** * @see HttpServlet#HttpServlet() */ public HelloWorldServlet() { super(); }

/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request,

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 483

Page 484: Hana Cloud

HttpServletResponse response) throws ServletException, IOException { response.getWriter().println("<html><body>"); try { // Use a unique name with package semantics e.g. com.foo.MyRepository String uniqueName = "com.foo.MyRepository"; // Use a secret key only known to your application (min. 10 chars) String secretKey = "my_super_secret_key_123"; Session openCmisSession = null; InitialContext ctx = new InitialContext(); String lookupName = "java:comp/env/" + "EcmService"; EcmService ecmSvc = (EcmService) ctx.lookup(lookupName); try { // connect to my repository openCmisSession = ecmSvc.connect(uniqueName, secretKey); } catch (CmisObjectNotFoundException e) { // repository does not exist, so try to create it RepositoryOptions options = new RepositoryOptions(); options.setUniqueName(uniqueName); options.setRepositoryKey(secretKey); options.setVisibility(Visibility.PROTECTED); ecmSvc.createRepository(options); // should be created now, so connect to it openCmisSession = ecmSvc.connect(uniqueName, secretKey); } response.getWriter().println( "<h3>You are now connected to the Repository with Id " + openCmisSession.getRepositoryInfo().getId() + "</h3>");

// access the root folder of the repository Folder root = openCmisSession.getRootFolder();

// create a new folder Map<String, String> newFolderProps = new HashMap<String, String>(); newFolderProps.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder"); newFolderProps.put(PropertyIds.NAME, "SapHANANeo"); try { root.createFolder(newFolderProps); } catch (CmisNameConstraintViolationException e) { // Folder exists already, nothing to do }

// create a new file in the root folder Map<String, Object> properties = new HashMap<String, Object>(); properties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document"); properties.put(PropertyIds.NAME, "HelloWorld.txt"); byte[] helloContent = "Hello World!".getBytes("UTF-8"); InputStream stream = new ByteArrayInputStream(helloContent); ContentStream contentStream = openCmisSession.getObjectFactory() .createContentStream("HelloWorld.txt", helloContent.length, "text/plain; charset=UTF-8", stream); try { root.createDocument(properties, contentStream, VersioningState.NONE); } catch (CmisNameConstraintViolationException e) { // Document exists already, nothing to do }

// Display the root folder's children objects ItemIterable<CmisObject> children = root.getChildren(); response.getWriter().println("The root folder of the repository with id " + root.getId() + " contains the following objects:<ul>"); for (CmisObject o : children) { response.getWriter().print("<li>" + o.getName()); if (o instanceof Folder) {

484P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 485: Hana Cloud

response.getWriter().println(" createdBy: " + o.getCreatedBy() + "</li>"); } else { Document doc = (Document) o; response.getWriter().println(" createdBy: " + o.getCreatedBy() + " filesize: " + doc.getContentStreamLength() + " bytes" + "</li>"); } } response.getWriter().println("</ul>"); } catch (Exception e) { throw new ServletException(e); } finally { response.getWriter().println("</body></html>"); } }

/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub }

}

For more information about using the OpenCMIS API, see the Apache Chemistry documentation linked below.During execution, this servlet does the following:

1. Connects to a repository and creates the repository if it does not yet exist2. Creates a subfolder3. Creates a document4. Displays the children of the root folder

4. Add the resource reference description to the web.xml file.

a) In the Project Explorer view, expand the HelloWorld/WebContent/WEB-INF node.

b) Select the web.xml file and from the context menu choose Open With Text Editor .c) Insert the following content after the <servlet-mapping> elements:

<resource-ref> <res-ref-name>EcmService</res-ref-name> <res-type>com.sap.ecm.api.EcmService</res-type></resource-ref>

5. Test the Web application locally or in the SAP HANA Cloud. For testing, proceed as described in Deploying from the Eclipse IDE linked below.

Related LinksSetting Up the Tools and SDK [page 27]Creating a HelloWorld Application [page 36]Getting Prepared for Local Development [page 481]http://chemistry.apache.org/java/opencmis.htmlUser Authentication [page 506]http://chemistry.apache.org/

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 485

Page 486: Hana Cloud

http://chemistry.apache.org/java/developing/guide.htmlhttp://chemistry.apache.org/java/0.8.0/maven/apidocs/http://chemistry.apache.org/java/examples/index.htmlDeploying from the Eclipse IDE

1.3.8 Securing Applications

SAML 2.0 Authentication

SAP HANA Cloud uses the Security Assertion Markup Language (SAML) 2.0 protocol for authentication and single sign-on.

By default, SAP HANA Cloud is configured to use SAP ID service as identity provider (IdP), as specified in SAML 2.0. You can configure trust to your custom IdP, to provide access to the cloud using your own user database.

Java EE Identity and Access Management

SAP ID Service provides Identity and Access Management for Java EE Web applications hosted on SAP HANA Cloud through the mechanisms described in Java EE Servlet specification and through dedicated APIs.

Protecting Applications from Cross-Site Scripting (XSS)

Cross-site Scripting (XSS) is one of the most common types of malicious attacks to Web applications. In order to help protecting against this type of attacks, SAP HANA Cloud provides a common output encoding library to be used from applications.

Protecting from Cross-Site Request Forgery (CSRF)

Cross-Site Request Forgery (CSRF) is another common type of attack to Web applications. You can protect applications running on SAP HANA Cloud from CSRF, based on the Tomcat Prevention Filter.Related LinksUsing a Custom Identity Provider [page 487]Using a Local Test Identity Provider [page 494]You can use a local test identity provider (IdP) to test Single Sign On (SSO) and Identity Federation of an SAP HANA Cloud application end-to-end.

Managing Role Assignments [page 501]User Authentication [page 506]Protecting from Cross-Site Scripting (XSS) [page 527]

486P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 487: Hana Cloud

Protecting from Cross-Site Request Forgery (CSRF) [page 530]

1.3.8.1 Using a Custom Identity Provider

Overview

The SAP HANA Cloud platform uses the Security Assertion Markup Language (SAML) 2.0 protocol for authentication of users and single sign-on (SSO). SAP HANA Cloud acts as a service provider (SP), as specified by this protocol. This means that SAP HANA Cloud provides applications that users can consume, and those applications are restricted to the users that are authorized to consume them (no strangers accepted). However, we need someone to verify the identity of users to ensure access is not granted to unauthorized users. This someone is called identity provider (IdP), as specified by SAML 2.0. The IdP stores in its database a list of all users that can access the SP, along with their credentials. The simplest credential is the user's password but there may also be others for even stronger security protection, such as a digital certificate, PIN code, biometrics, or a combination of credentials.

SAP HANA Cloud has no permanent storage for the users, their attributes, or their credentials. This is the IdP's job. SAP HANA Cloud merely trusts that the IdP has the correct user information and knows how to verify the identity of users. When a user attempts to access an application on SAP HANA Cloud for the first time, SAP HANA Cloud redirects the user to the IdP for identification. From then on, the user session is kept active, and the user is no longer prompted for credentials, whether she accesses the same application or another one running on SAP HANA Cloud. This is called single sign-on (SSO).

Moreover, as SAP HANA Cloud has no permanent user storage, it has no permanent record of the permissions for each user. Permissions are therefore calculated dynamically using the information contained in the SAML 2.0 assertion that the IdP issues for that user. This information could be a first name, a last name, an e-mail, or a company position, for example. You define a set of rules for mapping each logged user to a certain role defined on SAP HANA Cloud. Such a rule, translated in human-readable form, could be something like this: "If a user authenticated by this IdP has a SAML 2.0 assertion with the attribute pstn=Manager, add it to the group Managers on SAP HANA Cloud", or "If a user has an attribute e-mail ending with sap.com, add it to the group Internal", or "If a user is authenticated by this IdP, add it to the group MyCompany" (if we know that this IdP recognizes only accounts from MyCompany).

By default, SAP HANA Cloud uses SAP ID service as an IdP. SAP ID service recognizes users registered on SAP Community Network (SCN). If you want to use a custom IdP that contains your custom user database (for example, your corporate IdP, which can authenticate your company's employees), you need to change the default IdP settings of SAP HANA Cloud. This document describes how to do this.

Prerequisites

● You have a key pair and certificate for signing the information you exchange with the IdP on behalf of SAP HANA Cloud. This ensures the privacy and integrity of the data exchanged. Optionally, you can generate a key pair and certificate with SAP HANA Cloud. However, this key pair should not be used in a productive environment since its certificate is only self-signed. A key pair and certificate signed by a trusted Certificate Authority (CA) are strongly recommended for use in a productive environment. You create these using external certificate and key generation tools.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 487

Page 488: Hana Cloud

● You have provided the IdP with the above certificate. This allows the IdP administrator to configure its trust settings.

● You have the IdP signing certificate to enable you to configure the cloud trust settings.● You have negotiated with the IdP administrator which information the SAML 2.0 assertion will contain for

each user. For example, this could be a first name, last name, company, position, or an e-mail.● You know the authorizations and attributes the users logged by this IdP need to have on SAP HANA Cloud.

1. Configure SAP HANA Cloud Own Trust Settings

1. In your Web browser, open the SAP HANA Cloud cockpit and choose the TRUST tab page.2. Choose the Local Service Provider subtab.3. Choose Edit. You can now specify the local provider configuration type:

○ Default - the local provider's own trust settings will inherit the SAP HANA Cloud default configuration (which is trust to SAP ID service).

○ None - the local provider will have no trust settings, and it will not participate in any identity federation scenario

○ Custom - the local provider settings will have a specific configuration, different from the default configuration for SAP HANA Cloud.

Specifying Custom Local Provider Settings

1. Enter the local provider name.2. In Signing Key, copy the Base64-encoded signing key of SAP HANA Cloud (you should have a key generated

from an external key generation application). Optionally, you can choose Generate Key Pair to generate a new signing key and self-signed certificate. Please note that this generated signing key and certificate should not be used in a productive environment. Instead, use a key pair and certificate signed by a trusted CA.

3. In Signing Certificate, copy the textual content of the certificate identifying SAP HANA Cloud (you should have a certificate generated from an external application and signed by a trusted CA).

4. Choose the required value of the Principal Propagation option. If you set it to Enabled, you enable applications to propagate principal information to each other. Choose this value if you want to enable application-to-application single sign-on. Otherwise, set this option to Disabled.

5. Choose the required value of the Force authentication option. If you set it to Enabled, you enable force authentication for your application and not rely on Single Sign-On. Otherwise, set this option to Disabled.

488P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 489: Hana Cloud

6. When ready, choose Save.7. Choose Get Metadata to download the SAML 2.0 metadata describing SAP HANA Cloud as a service provider.

You will have to import this metadata into the IdP to configure trust to SAP HANA Cloud.

Specifying Default Local Provider Settings

There are two additional options you need to specify here:

● Principal Propagation - if you set it to Enabled, you enable applications to propagate principal information to each other. Choose this value if you want to enable application-to-application Single Sign-On. Otherwise, set this option to Disabled.

● Force Authentication - if you set it to Enabled, you enable force authentication for your application and not rely on Single Sign-On. Otherwise, set this option to Disabled.

When ready, save the changes.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 489

Page 490: Hana Cloud

(Optional) Configuring Service Provider Registration with SAP ID Service

1. Choose Custom as Configuration Type.2. Mark the SAP ID Service Registration option.3. Save the changes.4. If you need to configure SP registration further, open the SAP ID Service Administration Console and make

the required configuration there.

NoteOn registering the SP with SAP ID Service, the currently logged user gets administrative rights in the SAP ID Service Administration Console.

When you perform these steps, SAP ID Service is added automatically to the list of Trusted Identity Providers, configured with all settings necessary for communication (endpoints, bindings, certificates and so on).

If you delete the SAP ID Service entry from the list of Trusted Identity Providers, the respective service provider is automatically deleted from SAP ID Service.

If you unmark the SAP ID Service Registration option, the respective service provider is automatically deleted from SAP ID Service.

2. Configure Trust on SAP HANA Cloud to the SAML Identity Provider

2.1. Add an SAML 2.0 Identity Provider

1. Open the SAP HANA Cloud cockpit in your Web browser and choose the TRUST tab page.2. In the GENERAL tab, upload the IdP metadata xml file or manually enter he communication settings

negotiated between SAP HANA Cloud and the IdP. On IdP metadata upload, the fields are populated with the parsed data from the xml file. The minimum configuration is to complete all required fields.

490P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 491: Hana Cloud

Field Description

Metadata File The metadata XML file of the identity provider .

Name The entity ID of the IdP, also known as the issuer.

Description A short description of the IdP.

Assertion Consumer Service The endpoint (URL) to which the IdP's response with the SAML assertion is sent. By default, select Application Root for the cloud application's root URL.

Single Sign-on URL The IdP's endpoint (URL) to which the SP's authentication request will be sent.

Single Sign-on Binding The SAML-specified HTTP binding used by the SP to send the authentication request.

Single Logout URL The IdP's endpoint (URL) to which the SP's logout request will be sent.

Signature Algorithm The cryptographic algorithm used to compute the digest of the digital signatures in the SAML protocol messages.

Signing Certificate The X.509 certificate used by the IdP to digitally sign the SAML protocol messages.

User ID Source Location in the SAML assertion from where the user's unique name (ID) is taken when logging into the Cloud. If you choose subject, this is taken from the name identifier in the assertions's subject (<saml:Subject>) element. If

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 491

Page 492: Hana Cloud

Field Description

you choose attribute, the user's name is taken from an SAML attribute in the assertion.

Source Value Name of the SAML attribute that defines the user ID on the cloud.

User ID Prefix An optional prefix added to the user ID on the cloud.

User ID Suffix An optional suffix appended to the user ID on the cloud.

Enabled By default, any custom IdP is enabled.

3. In ATTRIBUTES, enter the default user attributes for all users logged by this IdP, and the user attributes determined based on the assertion attributes (see the steps below).

4. In GROUPS, enter the default groups to which the users logged by this IdP will belong and the groups determined based on assertion attributes (see the steps below).

5. Save the changes.

2.2. Configure the User Attributes for this Identity Provider

User attributes can contain any other information in addition to the user ID.

Default attributes are user attributes that all users logged by this IdP will have. For example, if we know that "My IdP" is used to authenticate users from MyCompany, we can set a default user attribute for that IdP "company=MyCompany".

To add a default attribute, proceed as follows:

1. On the ATTRIBUTES tab page, choose Add Default Attribute.2. Enter the attribute name and attribute value in the respective fields.

You can use assertion-based attributes to define a mapping between attributes in the SAML assertion and user attributes on the cloud. This allows you to essentially map any attribute (name) exposed by the IdP to a common name in your application, so that you don’t have to change your application code.

To add an assertion-based attribute, proceed as follows:

1. On the ATTRIBUTES tab page, choose Add Assertion-Based Attribute.2. In Assertion Attribute, enter the name of the attribute contained in the SAML 2.0 assertion issued by the IdP.

When this IdP logs a user on SAP HANA Cloud, the value of this attribute is mapped as the value for the specified user attribute (Principal Attribute).

3. In Principal Attribute, enter the name of the user attribute on SAP HANA Cloud.

492P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 493: Hana Cloud

In the screenshot above, all users authenticated by this IdP will have an attribute company="ITelO Corp.". In addition, several attributes from the SAML assertion will also be added to authenticated users. For some of these, the attribute name on the cloud is the same as the name provided by the IdP. Others are mapped to a different name.

For more information about using user attributes in your application, see User Authentication [page 506].

2.3. Configure the User Groups for This Identity Provider

Groups that you define on the cloud are later mapped to Java EE application roles. As specified in Java EE, in the web.xml, you define the roles authorized to access a protected resource in your application. You therefore define the groups that exist there and the roles to which each group is mapped via the Groups tab in the cockpit. For each different IdP, you then define a set of rules specifying to which groups a user logged by this IdP belongs.

For more information about configuring groups, see Managing Groups and Roles.

NoteYou must have defined groups in advance before you define default or assertion-based groups for this IdP.

Default groups are the groups all users logged by this IdP will have. For example, all users logged by the company IdP can belong to the group "Internal".

To add a default group, proceed as follows:

1. On the GROUPS tab page, choose Add Default Group.2. From the dropdown list that appears, choose the required group.

Assertion-based groups are groups determined by values of attributes in the SAML 2.0 assertion. For example, if the assertion contains the attribute "contract=temporary", you may want all such users to be added to the group "TEMPORARY".

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 493

Page 494: Hana Cloud

To add an assertion-based group, proceed as follows:

1. On the GROUPS tab page, choose Add Assertion-Based Group. A new row appears and a new mapping rule is now being created.

2. Enter the name of the group to which users will be mapped. Then define the rule for this mapping.3. In the first field of the Mapping Rules section, enter the SAML 2.0 assertion attribute name to be used as the

mapping source. In other words, the value of this attribute will be compared with the value you specify (in the last field of Mapping Rules).

4. Choose the comparison operator.5. In the last field of Mapping Rules, enter the value with which you compare the specified SAML 2.0 assertion

attribute.6. You can specify more than one mapping rule for a specific group. Use the plus button to add as many rules as

required. In this case, mapping is based on a logical OR operation for all rules, that is, if one of your rules applies, the user is added to the group.

In the screenshot above, all users logged by this IdP are added to the group Employees. However, only the employees that correspond to one of the specified two conditions are added to the group Managers.

1.3.8.2 Using a Local Test Identity Provider

You can use a local test identity provider (IdP) to test Single Sign On (SSO) and Identity Federation of an SAP HANA Cloud application end-to-end.

This scenario offers simplified testing in which developers establish trust to an application deployed in the cloud with an easy-to-use local test identity provider .

494P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 495: Hana Cloud

For more information about the identity provider concept in SAP HANA Cloud, see Using a Custom Identity Provider [page 487].

Prerequisites

● You have set up and configured the Eclipse IDE for Java EE Developers and SAP HANA Cloud Tools for Java.For more information, see Setting Up the Tools and SDK.

● You have developed and deployed your application on SAP HANA Cloud.For more information, see Creating an SAP HANA Cloud Application.

Procedure

Using the local test identity provider involves the following steps:

Setting up the local test IdP

1. Open the Eclipse IDE and add a local server. In the Servers view, from the context menu, choose NewServer . In the Define a new server wizard, choose SAP HANA Cloud local runtime. Start the server.The local test IdP is packaged within the SDK, so when you start the server, it will start as well.

2. To define local test IdP users and their attributes, use the Eclipse IDE Users editor as follows:

a. In the Eclipse IDE, open the Servers view.b. Double-click on the Local Server node. The local server editor opens.c. Go to the Users tab.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 495

Page 496: Hana Cloud

For more information about the Users editor, see Testing User Authentication on the Local Server.

Configuring the service provider of your account in SAP HANA Cloud

1. In a Web browser, open the SAP HANA Cloud cockpit and choose the TRUST tab page.2. In the Local Service Provider subtab, choose Edit.3. For Configuration Type, choose Custom.4. Choose Generate Key Pair to generate a new signing key and self-signed certificate.5. For the rest of the fields, leave the default values.6. Choose Save.7. Choose Get Metadata to download and save the SAML 2.0 metadata identifying your SAP HANA Cloud

account as a service provider. You will have to import this metadata into the local test IdP to configure trust to SAP HANA Cloud in the procedure that follows.

496P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 497: Hana Cloud

Configuring trust on SAP HANA Cloud to the local test IdP

The trust settings on SAP HANA Cloud for the local test IdP are configured in the same way as with any other productive IdP.

1. During the configuration, use the local test IdP metadata that can be requested under the following link: http://<idp_host>:<idp_port>/saml2/localidp/metadata,where <idp_host> and <idp_port> are the local server host and portTo find the <idp_port>, go to Servers, double click on the local server and choose Overview tab Ports configuration .

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 497

Page 498: Hana Cloud

2. Configure trust on the cloud to the local test IdP.

a. Open the cockpit in a Web browser, choose the TRUST tab page, Trusted Identity Providers subtab and then click on Add Trusted Identity Provider.

b. In GENERAL tab page, use the Metadata File Browse button to add the local test IdP metadata.All the needed values are filled in automatically.

c. Choose Save & Close.

498P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 499: Hana Cloud

For more information, see Using a Custom Identity Provider [page 487]3. Configure the User Attributes.

Assertion-based attributes are used to define a mapping between attributes in the SAML assertion issued by the local test IdP and user attributes on the Cloud.

This allows you to essentially pass any attribute exposed by the local test IdP to an attribute used in your application in the cloud.

Define user attributes in the local test IdP by using the Eclipse IDE Users editor for SAP HANA Cloud as is described in Setting up the local test IdP.

To add an assertion-based attribute, proceed as follows:

1. Open the cockpit in a Web browser, choose the TRUST tab page and then Trusted Identity Providers subtab.2. From the table, choose the entry localidp, open the ATTRIBUTES tab page, and click on Add Assertion-Based

Attribute.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 499

Page 500: Hana Cloud

3. In Assertion Attribute, enter the name of the attribute contained in the SAML 2.0 assertion issued by the local test IdP. These are the same user attributes you defined in the Eclipse IDE Users editor when setting the local test IdP.

4. In Principal Attribute, enter the name of the user attribute as referred in the tested application.

5. Choose Save & Close.

Generating self sign key pair and certificate for the local test IdP (optional)

If an error occurs while requesting the IdP metadata and the metadata cannot be generated, you can do the following:

1. Generate a localidp.jks keyfile manually. The key and certificate are needed for signing the information that the local test IdP will exchange with SAP HANA Cloud.

2. Open the directory <JAVA_HOME>/jre/bin/keytool3. Open a command line and execute the following command:

keytool -genkeypair -dname "CN=localidp" -keyalg "RSA" -validity 3650 -alias localidp -storepass localidp -keypass localidp -keystore <fullpath_dir_name>\localidp.jks

where <fullpath_dir_name> is the directory path where the jks will be saved after the creation.4. Under the Server directory, go to config_master\com.sap.core.jpaas.security.saml2.cfg and

create a directory with name localidp.5. Copy the localidp.jks file under localidp directory.

Configuring trust on the local test IdP to SAP HANA Cloud

1. In the Eclipse IDE, go to the already set up local test IdP Server.2. Copy the file with the metadata describing SAP HANA Cloud as a service provider under the local server

directory config_master/com.sap.core.jpaas.security.saml2.cfg/localidp. To get this metadata, in the cockpit, choose Get Metadata TRUST Local Service Provider .

500P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 501: Hana Cloud

As a result, you can now access your application deployed on the SAP HANA Cloud and test it against the local test IdP and its defined users and attributes.

1.3.8.3 Managing Role Assignments

Overview

On SAP HANA Cloud, roles allow you to control the access to application resources (role-based authorizations). You define the roles authorized to access a particular resource in the web.xml of your application. For more

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 501

Page 502: Hana Cloud

information about defining roles, see User Authentication [page 506]. After you deploy the application to SAP HANA Cloud, the role becomes visible in the Cockpit, and you can assign groups or individual users to that role. If you undeploy your application, these roles are removed.

NoteGroups are collections of roles that allow the definition of business-level functions within your account. They are similar to the actual business roles existing in an organization, such as "manager", "employee", "external" and so on. They help you to get better abstraction from/alignment between technical web roles and organizational roles.

For each different identity provider (IdP) for your account, you then define a set of rules specifying the groups a user for this IdP belongs to. For more information about configuring identity providers, see Using a Custom Identity Provider. When a user for an IdP is authenticated, SAP HANA Cloud assigns to it the groups specified. When that user requests a cloud resource, SAP HANA Cloud checks if these groups are assigned roles authorized to access that resource.

The current document describes how to assign roles using the AUTHORIZATIONS tab of the SAP HANA Cloud Cockpit. The Users and Groups tabs allow you to manage the roles a user or group has respectively, and provide you with role or group-based view respectively. The Roles tab allows practically the same operations, providing you with a role-based view.

NoteWhen a user logs in, its roles are stored in the user's current browser session. They are not updated dynamically, and removed from there only if the session is terminated or invalidated. This means if you change the set of roles for a user currently logged, they will take effect only after logout or session invalidation.

Assigning Users to Roles

In the Users subtab, you can view and manage the roles an individual user has. Use this procedure to assign roles ro a user regardless of the IdP authorizing it.

1. In the SAP HANA Cloud Cockpit, enter the AUTHORIZATIONS tab.2. Enter the Users subtab.3. In the User field, enter the name of the required group, and choose Show Roles. The table below shows all

roles that are already assigned to this group.

502P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 503: Hana Cloud

4. Choose Assign.Choose the required application and the role the user will have. In these lists, you can choose from the already subscribed applications, and the roles defined by the application itself. For more information, see User Authentication.

5. Save the changes.

Assigning Roles to Groups

In the Groups subtab, you can view and manage the roles a specific group has. Use this procedure to manage role assignments depending on the IdP authorizing a user.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 503

Page 504: Hana Cloud

1. In the SAP HANA Cloud cockpit, enter the AUTHORIZATIONS tab.2. Enter the Groups subtab.3. In the Group field, enter the name of the required group. If you want to create a new group, simply assign the

required roles from here.4. Choose Show Roles. The table below shows all roles that are already assigned to this group.

5. To assign a new role, choose Assign.6. Choose the required application and the role the group will have. In these lists, you can choose from the

already subscribed applications, and the roles defined by the application itself. For more information, see User Authentication.

7. Save the changes.

504P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 505: Hana Cloud

Assigning Users or Groups to Roles

In the Roles subtab, you can view and manage the list of users and groups currently assigned to a specific role. Use this procedure if you want to get a role-based view of role assignments (as opposed to having user or group-based view).

1. In the cockpit, enter the AUTHORIZATIONS tab.2. Enter the Roles subtab.3. Choose the required application and role. In these lists, you can choose from the already subscribed

applications, and the roles defined by the application itself. For more information, see User Authentication.4. Choose Show. The table below lists all users or groups that have that role on the specified application.

5. To assign a new user or group, choose Assign.

6. Enter the user or group name.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 505

Page 506: Hana Cloud

7. Save the changes.

1.3.8.4 User Authentication

Overview

This section describes how to provide authentication in your applications. There are two ways to define user authentication

● DeclarativeYou declare protected resources in the web.xml, as specified by Java EE. For more information, see Adding Declarative Authentication to a Web Application.

● ProgrammaticYou use the SAP HANA Cloud identity service API to invoke authentication wherever needed. For more information, see Adding Programmatic Authentication to a Web Application.

Using the SAP ID service API, you can also invoke programmatic logout (see Adding Programmatic Logout), or retrieve user profile attributes (see Working with User Profile Attributes).

The SAP HANA Cloud Tools for Java provide convenient tools for local testing of user authentication. With local testing, you you can test the application behavior without re-deploying to SAP HANA Cloud, and without connection to SAP ID service. For more information, see Testing User Authentication on the Local Server.

Prerequisites

● You have downloaded and configured the SAP HANA Cloud Tools for Java. For more information, see Setting Up the Tools and SDK [page 27].

● You have created a simple HelloWorld application, as described in Creating a HelloWorld Application [page 36].

● If you want to use Java EE 6 Web Profile features in your application, you have downloaded the beta SDK. For more information, see Using Java EE 6 Web Profile [page 65]

Adding Declarative Authentication to a Web Application

The Java EE servlet specification allows the security mechanisms for an application to be declared in a deployment descriptor outside the Java code. Deployment descriptors describe the Java EE application's security policy, including security roles, access control, and authentication requirements.

Applications deployed using SAP HANA Cloud may declare authentication requirements in their web.xml deployment descriptor (see the XML schema for the servlet 2.5 deployment descriptor). The web.xml deployment descriptor can be found in the WebContent/WEB-INF directory in the application project of the Eclipse IDE.

The following authentication methods are supported with SAP HANA Cloud:

506P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 507: Hana Cloud

● FORM - Delegates authentication to the SAP ID service according to the Security Assertion Markup Language (SAML) 2.0 protocol. This is the recommended authentication mechanism for SAP HANA Cloud applications.

● BASIC - HTTP "basic" authentication scheme according to RFC 2617. Web browsers prompt users to enter a user name and password. The actual authentication is still delegated to the SAP ID service.

NoteAny other methods (DIGEST, CLIENT-CERT, or custom) that you specify in the web.xml are executed as FORM.

NoteWhen testing in the local scenario, and your application has Web-ContextPath: /, you might experience the following problem with Internet Explorer:

After authentication you see:

HTTP Status 405 - HTTP method POST is not supported by this URL.

If you see such issues, you will have to add the following code into your protected resource:

@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException { doGet(req, resp); }

The following example illustrates a change in the web.xml file that enables SAML2 authentication. It requires all users to authenticate before accessing the protected resource. It does not, however, manage authorizations according to the user roles - it authorizes all authenticated users.

<login-config> <auth-method>FORM</auth-method></login-config><security-constraint> <web-resource-collection> <web-resource-name>Protected Area</web-resource-name> <url-pattern>/index.jsp</url-pattern> <url-pattern>/a2asso.jsp</url-pattern> </web-resource-collection> <auth-constraint> <!-- Role Everyone will not be assignable --> <role-name>Everyone</role-name> </auth-constraint></security-constraint><security-role> <description>All SAP HANA Cloud users</description> <role-name>Everyone</role-name></security-role>

NoteAll authenticated users implicitly have the Everyone role. You cannot remove or edit this role. In the SAP HANA Cloud Cockipt, the Everyone role is not listed in role mapping (see Managing Role Assignments [page 501] ).

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 507

Page 508: Hana Cloud

If you want to manage authorizations according to user roles, you should define the corresponding constraints in the web.xml. The following example defines a resource available for users with role Developer, and another resource for users with role Manager:

<security-constraint> <web-resource-collection> <web-resource-name>Developer Page</web-resource-name> <url-pattern>/developer.jsp</url-pattern> </web-resource-collection> <auth-constraint> <role-name>Developer</role-name> </auth-constraint> </security-constraint> <security-constraint> <web-resource-collection> <web-resource-name>Manager Page</web-resource-name> <url-pattern>/manager.jsp</url-pattern> </web-resource-collection> <auth-constraint> <role-name>Manager</role-name> </auth-constraint> </security-constraint> <login-config> <auth-method>FORM</auth-method> </login-config>

Procedure

The following are the steps you need to complete to enable and test declarative authentication in your application:

1. Open your application web.xml file and add security constraints and login configuration information.2. Test your application on the local server, which is much faster and does not require a connection to the SAP

ID service or another identity provider. For more information, see Testing User Authentication on the Local Server.

○ When FORM authentication is used, you see a local login page and are prompted to enter your user name and password. Upon successful authentication, the servlet content is displayed.

○ When BASIC authentication is used, you see a popup window and are prompted to enter your user name and password. Upon successful authentication, the servlet content is displayed.

3. Deploy the application to SAP HANA Cloud.

○ When FORM authentication is used, you are redirected to the SAP ID service or another identity provider, where you are authenticated with your user name and password. The servlet content is then displayed.

○ When BASIC authentication is used, you see a popup window and are prompted to enter your credentials. The servlet content is then displayed.

Adding Programmatic Authentication to a Web Application

With programmatic authentication, you do not need to declare constrained resources in the web.xml file of your application. Instead, you declare the resources as public, and you decide in the application logic when to trigger authentication. In this case, you have to invoke the authentication framework API explicitly before executing any application code that should be protected. You also need to check whether the user is already authenticated, and should not trigger authentication if the user is logged on, except for certain scenarios where explicit re-authentication is required.

508P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 509: Hana Cloud

If you trigger authentication in an SAP HANA Cloud application protected with FORM, the user is redirected to the SAP ID service for authentication and is then returned to the original application that triggered the authentication.

If you trigger authentication in an SAP HANA Cloud application protected with BASIC, the Web browser displays a popup window to the user, prompting him or her to provide a user name and password.

package hello;

import java.io.IOException;

import javax.security.auth.login.LoginContext;import javax.security.auth.login.LoginException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

import com.sap.security.auth.login.LoginContextFactory;

public class HelloWorldServlet extends HttpServlet { ...

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String user = request.getRemoteUser(); if (user != null) { response.getWriter().println("Hello, " + user); } else { LoginContext loginContext; try { loginContext = LoginContextFactory.createLoginContext("FORM"); loginContext.login(); response.getWriter().println("Hello, " + request.getRemoteUser());

} catch (LoginException e) { e.printStackTrace(); } } ... } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } ...}

In the example above, you create LoginContext and call its login() method.

NoteAll the steps below are described using the FORM authentication method, but they can also be applied to BASIC.

Procedure

1. Open the source code of your HelloWorldServlet class. Add the code for programmatic authentication to the doGet() method.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 509

Page 510: Hana Cloud

2. Make the doPost() method invoke programmatic authentication. This is necessary because the SAP ID service always returns the SAML2 response over an HTTP POST binding, and in order to be processed correctly, the LoginContext login must be called during the doPost() method. The authentication framework is responsible for restoring the original request using GET after successful authentication. Another alternative is that your doPost() method simply calls your doGet() method.

3. Test your application on the local server. It does not need to be connected to the SAP ID service, and authentication is done against local users. For more information, see Testing User Authentication on the Local Server.

4. Deploy the application to SAP HANA Cloud. You are redirected to the SAP ID service or another identity provider, where you are authenticated with your user account. The servlet content is then displayed and you should be able to see the content returned by the hello servlet.When BASIC authentication is used, you should see a popup window prompting you to provide credentials to authenticate. Once these are entered successfully, the servlet content is displayed.

Adding Programmatic Authorizations

Use the isUserInRole method of the servlet request (javax.servlet.HttpServletRequest) to manage authorizations for users. The following example returns a 403 eror if the user accessing this servlet does not have role Developer:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); if(!request.isUserInRole("Developer")){ response.sendError(403, "Logged in user does not have role Developer"); return; } else { out.println("Hello developer"); } }

Adding Programmatic Logout

You can provide a logout operation for your application by adding a logout button or logout link. When a logout is triggered in an on-demand application, the user is redirected to the central identity provider for the logout and is then returned to the original application URL that triggered the authentication.

The following code provides an example of the code to be added to trigger the logout:

import javax.security.auth.login.LoginContext;import javax.security.auth.login.LoginException;import com.sap.security.auth.login.LoginContextFactory;...

public class LogoutServlet extends HttpServlet {. . . //Call logout if the user is logged in LoginContext loginContext = null; if (request.getRemoteUser() != null) {

510P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 511: Hana Cloud

try { loginContext = LoginContextFactory.createLoginContext(); loginContext.logout(); } catch (LoginException e) { // Servlet container handles the login exception // It throws it to the application for its information response.getWriter().println("Logout failed. Reason: " + e.getMessage()); } } else { response.getWriter().println("You have successfully logged out."); }. . . }

We add a logout link to the HelloWorld servlet, which references this logout servlet:

response.getWriter().println("<a href=\"LogoutServlet\">Logout</a>");

Preventing Common Logout Problems

Unprotect the Logout Servlet

For efficient logout to work, the servlet handling logout must not be protected in the web.xml. Otherwise, requesting logout will result in a login request. The following example illustrates how to unprotect successfully a logout servlet. The additional <security-constraint>...</security-constraint> section explicitly enables access to the logout servlet.

<security-constraint> <web-resource-collection> <web-resource-name>Start Page</web-resource-name> <url-pattern>/*</url-pattern> </web-resource-collection><auth-constraint> <role-name>Everyone</role-name></ auth-constraint> </security-constraint>

<security-constraint> <web-resource-collection> <web-resource-name>Logout</web-resource-name> <url-pattern>/LogoutServlet</url-pattern> </web-resource-collection> </security-constraint>

(For JavaScript only) Log out Involving JavaScript Resources

If you are using JavaScript for the logout, besides the logout servlet or JSP, you need to handle two more things on triggering logout:

● Invalidate the entire JavaScript session● Reload the entire window by calling window.location=<logout_servlet>

Skipping some of the above steps may lead to partial logout only.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 511

Page 512: Hana Cloud

NoteYou also have to make sure the logout servlet is unprotected, as described in the previous step.

Avoid Mapping Servlet Resources to /* in the web.xml

Avoid mapping a servlet to resources using wildcard (<url-pattern>/*</url-pattern> in the web.xml). This may lead to an infinite loop. Instead, map the servlet to particular resources, as in the following example:

<servlet-mapping> <servlet-name>Logout Servlet</servlet-name> <url-pattern>/LogoutServlet</url-pattern> <servlet-class>test.LogoutServlet</servlet-class> </servlet-mapping>

Working with User Profile Attributes

The user management API provides access to users via the user interface. It can be used to get and create users or to read and update their information.

To access user information, you need to get to com.sap.security.um.user.UserProvider.

To get UserProvider, first, declare a resource reference in the web.xml. For example:

<resource-ref> <res-ref-name>user/Provider</res-ref-name> <res-type>com.sap.security.um.user.UserProvider</res-type></resource-ref>

Then look up UserProvider via JNDI in the source code of your application. For example:

InitialContext ctx = new InitialContext();UserProvider userProvider = (UserProvider) ctx.lookup("java:comp/env/user/Provider");User user = null;if (request.getUserPrincipal() != null) { user = userProvider.getUser(request.getUserPrincipal().getName());}

NoteIf you are using the SDK for Java EE 6 Web Profile, you can look up UserProvider via annotation (instead of embedding JNDI lookup in the code). For example:

@Resourceprivate UserProvider userProvider;

try { // Read the currently logged in user from the user storage return userProvider.getUser(request.getRemoteUser());} catch (PersistenceException e) { throw new ServletException(e);}

512P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 513: Hana Cloud

Alternatively, you can access UserProvider using com.sap.security.um.user.UserManagementAccessor. For example:

import com.sap.security.um.user.User;import com.sap.security.um.user.UserProvider;import com.sap.security.um.service.UserManagementAccessor;

...

// Check for a logged in userif (request.getUserPrincipal() != null) { try { // UserProvider provides access to the user storage UserProvider users = UserManagementAccessor.getUserProvider();

// Read the currently logged in user from the user storage User user = users.getUser(request.getUserPrincipal().getName());

// Print the user name and email response.getWriter().println("User name: " + user.getAttribute("firstname") + " " + user.getAttribute("lastname")); response.getWriter().println("Email: " + user.getAttribute("email")); } catch (Exception e) { // Handle errors }}

Testing User Authentication on the Local Server

When you add user authentication to your application, you can test it first on the local server before uploading it to the SAP HANA Cloud.

NoteOn the local server, authentication is handled locally, and not by the SAP ID service. When you try to access a protected resource on the local server, you will see a local login page (not SAP ID service's or another identity provider's login page). User access is then either granted or denied based on a local JSON (JavaScript Object Notation) file (<local_server_dir>/config_master/com.sap.security.um.provider.neo.local/neousers.json), which defines the local set of user accounts, along with their roles and attributes. This is just for testing purposes. When you deploy to the SAP HANA Cloud, user authentication is still handled by the SAP ID service.

Using the SAP HANA Cloud Tools for Java, you can manage local users easily. You can use the visual editor for configuring the users, or edit the JSON file directly.

To open the local user management UI, proceed as follows:

1. In the Eclipse IDE, open the Servers view.2. Select the Local Server node and double-click it.

The local server editor opens.3. Enter the Users tab page.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 513

Page 514: Hana Cloud

Creating and Managing Users

To create a user:

1. In the All Users pane, choose button to add a new user.2. Specify the user ID and password, and, optionally, email, first name and last name.3. Choose OK.4. Save the changes in the editor.

Managing User Attributes

User attributes provide additional information about a user account. Applications can use attributes to distinguish between users or customization according to users.

To add a new attribute, proceed as follows:

1. In the Attributes pane, choose button to add a new attribute.2. Specify the name and value pair, and choose OK.3. Save the changes in the editor.

Managing User Roles

Roles are used by applications to define access rights. By default, each user is assigned the User.Everyone role. It is read-only, which means you cannot remove it.

To add a new role, proceed as follows:

1. In the Roles pane, choose button to add a new role.2. Specify the role name and choose OK.3. Save the changes in the editor.

Local Testing with the Command Line Tool

514P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 515: Hana Cloud

If you prefer using the command line tool instead of the Eclipse IDE, you will have to find and edit manually the JSON file configuring local test users. It is located at <local_server_dir>/config_master/com.sap.security.um.provider.neo.local/neousers.json.

The following example shows a sample configuration of the JSON file with a number of users, along with their attributes and roles:

{ "Users": [ { "UID": "I000001", "Password": "{SSHA}OA5IKcTJplwLLaXCjmbcV+d3LQVKey+bEXU\u003d", "Roles": [ "Employee", "Manager" ], "Attributes": [ { "attributeName": "firstname", "attributeValue": "John" }, { "attributeName": "lastname", "attributeValue": "Doe" }, { "attributeName": "email", "attributeValue": "[email protected]" } ] }, { "UID": "I000002", "Password": "{SSHA}OA5IKcTJplwLLaXCjmbcV+d3LQVKey+bEXU\u003d", "Roles": [ "SomeRole" ], "Attributes": [ { "attributeName": "firstname", "attributeValue": "Boris" }, { "attributeName": "lastname", "attributeValue": "Boykov" }, { "attributeName": "email", "attributeValue": "[email protected]" } ] } ]}

Troubleshooting

When stopping your local server, you might see the following error logs:

#ERROR#org.apache.catalina.core.ContainerBase##anonymous#System Bundle Shutdown###ContainerBase.removeChild: stop: org.apache.catalina.LifecycleException: Failed to stop component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/idelogin]]

This error causes no harm, and you need not take any measures.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 515

Page 516: Hana Cloud

Reference

SAP HANA Cloud provides the following APIs for user management and authentication:

Package Description

User Management API

com.sap.security.um.user.* The user management API can be used to create and delete users or update user information.

Authentication API

com.sap.engine.lib.security com.sap.engine.lib.security.http

com.sap.security.auth.login

The authentication API provides basic login modules and callback handlers implementations and a custom LoginContext implemenatation. It relies on the user management API to provide user information required during the authentication process.

1.3.8.5 Cryptography

The Keystore Service provides a repository for cryptographic keys and certificates to the applications hosted on SAP HANA Cloud platform.

Keys and Certificates [page 516]

If you want to use cryptography with unlimited strength in an SAP HANA Cloud application, you need to enable it via installing the necessary Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files on SAP JVM.

Using Strong Encryption in Applications [page 526]

1.3.8.5.1 Keys and Certificates

Overview

The Keystore Service provides a repository for cryptographic keys and certificates to the applications hosted on SAP HANA Cloud platform. By using the Keystore Service, the applications could easily retrieve keystores and use them in various cryptographic operations such as signing and verifying of digital signatures, encrypting and decrypting messages, and performing SSL communication.

Features

The SAP HANA Keystore Service stores and provides keystores encoded in the following formats:

516P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 517: Hana Cloud

● Java Keystore (JKS)It supports password-based integrity validation for its content. Key entries are protected with password-based encryption. Password has to be specified in order to retrieve a key entry.

● Extended Java Keystore (JCEKS)It provides the same functionality as the JKS format with stronger protection for private keys.

● PKCS #12 file (P12)This format supports password-based integrity validation for its content. Key entries are protected with password-based symmetric encryption. A password has to be specified in order to retrieve a key entry.

● Privacy Enhanced Mail Certificate (PEM)It does not support integrity validation. Key entries are not protected with password.

Configuring Keystores

● Local Server ConfigurationYou can manage the keystores directly on the file system of the local server. Place the keystore files with .jks, .pem, .jceks, or .p12 extension in the following folder: <local server>/config_master/com.sap.cloud.crypto.keystore.

● Cloud ConfigurationYou can manage the keystores via the SAP HANA Cloud console client. For more information, see Keystore Console Commands.

Consuming the Keystore Service

To consume the Keystore Service, you need to add the following reference to your web.xml file:

<resource-ref> <res-ref-name>KeyStoreService</res-ref-name> <res-type>com.sap.cloud.crypto.keystore.api.KeyStoreService</res-type></resource-ref>

Then, in the code you can look up Keystore Service API via JNDI:

import com.sap.cloud.crypto.keystore.api.KeyStoreService;...KeyStoreService keystoreService = (KeyStoreService) new InitialContext().lookup("java:comp/env/KeyStoreService");

A keystore can be obtained by using the getKeyStore() method.

KeyStore keyStore = keystoreService.getKeystore(keystoreName, keystorePassword);

For more information, see Tutorial: Using the Keystore Service for Client Side HTTPS Connections.

Related LinksKeystore Console Commands [page 518]Tutorial: Using the Keystore Service for Client Side HTTPS Connections [page 520]

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 517

Page 518: Hana Cloud

Keystore Console Commands

The keystore console commands are called from the SAP HANA Cloud Console Client and allow users to list, upload, download, and delete keystores. To be able to use them, the user must have administrative rights for that account. The console supports the following keystore commands: list-keystores, upload-keystores, download-keystores, and delete-keystores.

To specify cross account subscription, you must specify both parameters --provider-account and --provider-application.

● Command list-keystoresIt is used to list available keystores.

Table 4: Parameters of list-keystoresParameter Description

-a, --account Account name

-b, --application Optional. Application name

-h, -host SAP HANA Cloud host

-u, -user User supposed to perform the command

--provider-account Optional. Refers to the account providing an application specified with the --provider-application parameter. Required if configuring a provider application.

--provider-application Optional. Refers to an application provided by the account specified with the --provider-account parameter. Required if provider account is specified.

Example

neo list-keystores --account <account name> --user <user ID>

● Command upload-keystoreIt is used to upload a keystore file.

Table 5: Parameters of upload-keystoresParameter Description

-a, --account Account name

-b, --application Optional. Application name

-h, -host SAP HANA Cloud host

-u, -user User supposed to perform the command

--location Path to a JKS or PEM file to be uploaded from a local file system.

-w, --overwrite Optional. Overwrite the keystore if it already exists

518P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 519: Hana Cloud

Parameter Description

--provider-account Optional. Refers to the account providing an application specified with the --provider-application parameter. Required if configuring a provider application.

--provider-application Optional. Refers to an application provided by the account specified with the --provider-account parameter. Required if provider account is specified.

Example

neo upload-keystore --account <account name> --user <user ID> --location C:\Keystores\KeyStore1.jks

● Command download-keystoreIt is used to download a keystore file.

Table 6: Parameters of download-keystoresParameter Description

-a, --account Account name

-b, --application Optional. Application name

-h, -host SAP HANA Cloud host

-u, -user User supposed to perform the command

--location Optional. Local directory where the keystore will be saved. If it is not specified, the current directory is used.

--name Name of the keystore to be downloaded

-w, --overwrite Optional. Overwrite the keystore if it already exists

--provider-account Optional. Refers to the account providing an application specified with the --provider-application parameter. Required if configuring a provider application.

--provider-application Optional. Refers to an application provided by the account specified with the --provider-account parameter. Required if provider account is specified.

Example

neo download-keystore --account <account name> --user <user ID> --location c:\temp --name KeyStore1

● Command delete-keystoreIt is used to delete a keystore file.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 519

Page 520: Hana Cloud

Table 7: Parameters of delete-keystoresParameter Description

-a, --account Account name

-b, --application Optional. Application name

-h, -host SAP HANA Cloud host

-u, -user User supposed to perform the command

--name Name of the keystore to be deleted

--provider-account Optional. Refers to the account providing an application specified with the --provider-application parameter. Required if configuring a provider application.

--provider-application Optional. Refers to an application provided by the account specified with the --provider-account parameter. Required if provider account is specified.

Example

neo delete-keystore --account <account name> --user <user ID> --name KeyStore1

Tutorial: Using the Keystore Service for Client Side HTTPS Connections

Prerequisites

● You have downloaded and configured the SAP Eclipse platform. For more information, see Setting Up the Tools and SDK [page 27].

● You have created a HelloWorld Web application as described in the Creating a HelloWorld Application tutorial. For more information, see Creating a HelloWorld Application [page 36].

● You have an HTTPS server hosting a resource which you would like to access in your application.● You have prepared the required key material as .jks files in the local file system.

NoteFile client.jks contains a client identity key pair trusted by the HTTPS server, and cacerts.jks contains all issuer certificates for the HTTPS server. The files are created with the keytool from the standard JDK distribution. For more information, see Key and Certificate Management Tool.

520P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 521: Hana Cloud

Context

This tutorial describes how to extend the HelloWorld Web application to use SAP HANA Cloud Keystore Service. It tells you how to make an SSL connection to an external HTTPS server by using the JDK and Apache HTTP Client. For more information about the HelloWorld Web application, see Creating a HelloWorld Application.

You test and run the application on your local server and on SAP HANA Cloud.

Procedure

1. Declare a Keystore Service Resource Reference

To enable the look-up of the Keystore Service through JNDI, you need to add a resource reference entry to the web.xml descriptor.

a) In the Project Explorer view, select the HelloWorld/WebContent/WEB-INF node.b) Open the web.xml file in the text editor and insert the following content:

<resource-ref> <res-ref-name>KeyStoreService</res-ref-name> <res-type>com.sap.cloud.crypto.keystore.api.KeyStoreService</res-type></resource-ref>

c) Save the file.2. Create a new Servlet

a) To add a servlet to the HelloWorld project, select the HelloWorld node in the Project Explorer view.

b) From the Eclipse main menu, choose File New Servlet .c) Enter the Java package com.sap.cloud.sample.keystoreservice and the class name SSLExampleServlet.d) Choose the Finish button to generate the servlet.e) Replace the entire servlet class with the code below.

package com.sap.cloud.sample.keystoreservice;

import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.PrintWriter;import java.security.KeyStore;

import javax.naming.Context;import javax.naming.InitialContext;import javax.naming.NamingException;import javax.net.ssl.KeyManager;import javax.net.ssl.KeyManagerFactory;import javax.net.ssl.SSLContext;import javax.net.ssl.SSLSocket;import javax.net.ssl.SSLSocketFactory;import javax.net.ssl.TrustManager;import javax.net.ssl.TrustManagerFactory;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 521

Page 522: Hana Cloud

import com.sap.cloud.crypto.keystore.api.KeyStoreService;

public class SSLExampleServlet extends HttpServlet { private static final long serialVersionUID = 1L;

/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// get Keystore Service KeyStoreService keystoreService; try { Context context = new InitialContext(); keystoreService = (KeyStoreService) context.lookup("java:comp/env/KeyStoreService"); } catch (NamingException e) { response.getWriter().println("Error:<br><pre>"); e.printStackTrace(response.getWriter()); response.getWriter().println("</pre>"); throw new ServletException(e); }

String host = request.getParameter("host"); if (host == null || (host = host.trim()).isEmpty()) { response.getWriter().println("Host is not specified"); return; } String port = request.getParameter("port"); if (port == null || (port = port.trim()).isEmpty()) { port = "443"; } String path = request.getParameter("path"); if (path == null || (path = path.trim()).isEmpty()) { path = "/"; } String clientKeystoreName = "client"; String clientKeystorePassword = request.getParameter("client.keystore.password"); if (clientKeystorePassword == null || (clientKeystorePassword = clientKeystorePassword.trim()).isEmpty()) { response.getWriter().println("Password for client keystore is not specified"); return; } String trustedCAKeystoreName = "cacerts";

// get a named keystores with password for integrity check KeyStore clientKeystore; try { clientKeystore = keystoreService.getKeyStore(clientKeystoreName, clientKeystorePassword.toCharArray()); } catch (Exception e) { response.getWriter().println("Client keystore is not available: " + e); return; }

// get a named keystore without integrity check KeyStore trustedCAKeystore; try { trustedCAKeystore = keystoreService.getKeyStore(trustedCAKeystoreName, null); } catch (Exception e) { response.getWriter().println("Trusted CAs keystore is not available" +

522P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 523: Hana Cloud

e); return; } callHTTPSServer(response, host, port, path, clientKeystorePassword, clientKeystore, trustedCAKeystore);}

private void callHTTPSServer(HttpServletResponse response, String host, String port, String path, String clientKeystorePassword, KeyStore clientKeystore, KeyStore trustedCAKeystore) throws IOException { try { KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(clientKeystore, clientKeystorePassword.toCharArray());

KeyManager[] keyManagers = kmf.getKeyManagers(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(trustedCAKeystore);

TrustManager[] trustManagers = tmf.getTrustManagers(); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, trustManagers, null);

SSLSocketFactory factory = sslContext.getSocketFactory();

SSLSocket socket = (SSLSocket)factory.createSocket(host, Integer.parseInt(port)); socket.startHandshake();

PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))); out.println("GET " + path + " HTTP/1.0"); out.println(); out.flush();

if (out.checkError()) { response.getWriter().println("Error durring request sending"); }

BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { response.getWriter().println(inputLine); }

in.close(); out.close(); socket.close(); } catch (Exception e) { response.getWriter().println("Error:<br><pre>"); e.printStackTrace(response.getWriter()); response.getWriter().println("</pre>"); } finally { response.getWriter(); } } }

f) Save the Java editor and make sure that the project compiles without errors.3. Deploy and Test the Web Application

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 523

Page 524: Hana Cloud

○ Local Server Configuration of the Keystore○ Cloud Configuration of the Keystore

4. Switch to Apache HTTP Client Implementationa) Add the required .jar files of the Apache HTTP Client (version 4.2 or higher) to the build path of your

project.b) Add the following imports:

import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.conn.scheme.Scheme;import org.apache.http.conn.scheme.SchemeSocketFactory;import org.apache.http.conn.ssl.SSLSocketFactory;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.util.EntityUtils;

c) Replace callHTTPSServer() method with the one using Apache HTTP client.

private void callHTTPSServer(HttpServletResponse response, String host, String port, String path, String clientKeystorePassword, KeyStore clientKeystore, KeyStore trustedCAKeystore) throws IOException, ServletException { try { SchemeSocketFactory socketFactory = new SSLSocketFactory(clientKeystore, clientKeystorePassword, trustedCAKeystore); Scheme sch = new Scheme("https", Integer.parseInt(port), socketFactory); DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.getConnectionManager().getSchemeRegistry().register(sch);

HttpGet httpget = new HttpGet("https://" + host + path);

HttpResponse resp = httpclient.execute(httpget); HttpEntity entity = resp.getEntity();

BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent())); String inputLine; while ((inputLine = in.readLine()) != null) { response.getWriter().println(inputLine); } EntityUtils.consume(entity); } catch (Exception e) { response.getWriter().println("error: " + e); throw new ServletException(e); } finally { response.getWriter().flush(); }}

Related LinksCreating a HelloWorld Application [page 36]Local Server Configuration of the Keystore [page 524]Cloud Configuration of the Keystore [page 525]

Local Server Configuration of the Keystore

524P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 525: Hana Cloud

Procedure

1. To deploy your Web application on the local server, follow the steps for deploying a Web application locally as described in Deploying Locally from Eclipse IDE.

2. To upload the required keystores, copy the prepared client.jks and cacerts.jks files into <local server root>\config_master\com.sap.cloud.crypto.keystore subfolder.

3. To test the functionality, open the following URL in your Web browser: http://localhost:<local server HTTP port>/HelloWorld/SSLExampleServlet?host=<remote HTTPS server host name>&port=<remote HTTPS server port number>&path=<remote HTTPS server resource>&client.keystore.password=<client identity keystore password>.

Related LinksDeploying Locally from Eclipse IDE [page 533]Follow the steps below to deploy an application on SAP HANA Cloud local runtime.

Cloud Configuration of the Keystore

Procedure

1. To deploy your Web application on the cloud, follow the steps for deploying a Web application to SAP HANA Cloud as described in Deploying on the Cloud with the Console Client.

2. To upload the required keystores, execute upload-keystore console command with the prepared .jks files. For more information, see the Cloud Configuration section in Keys and Certificates.

ExampleAssuming you have myAccount account, myApplication application, myUser user, and the keystore files in folder C:\Keystores, you need to execute the following commands in your local <SDK root>\tools folder:

neo upload-keystore --account myAccount --user myUser --location C:\Keystores\client.jksneo upload-keystore --account myAccount --user myUser --location C:\Keystores\cacerts.jks

For more information about the keystore console commands, see Keystore Console Commands.

3. To test the functionality, open the application URL shown by SAP HANA Cloud cockpit with the following options:<SAP HANA Cloud Application URL>/SSLExampleServlet?host=<remote HTTPS server host name>&port=<remote HTTPS server port number>&path=<remote HTTPS server resource>& client.keystore.password=<client identity keystore password>.

For more information, see Applications.

Related LinksDeploying on the Cloud with the Console Client [page 537]Deploying an application publishes it to SAP HANA Cloud. During deploy, you can define various specifics of the deployed application using the deploy command optional parameters.

Keys and Certificates [page 516]

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 525

Page 526: Hana Cloud

Keystore Console Commands [page 518]Applications [page 52]

1.3.8.5.2 Using Strong Encryption in Applications

By default, SAP JVM provides Java Cryptography Extension (JCE) with limited cryptography strength. If you want to use cryptography with unlimited strength in an SAP HANA Cloud application, you need to enable it via installing the necessary Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files on SAP JVM. To do that, follow the procedure below.

Prerequisites

You have the appropriate Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files enabling cryptography with unlimited strength.

Procedure

1. Pack the encryption policy files (JCE Unlimited Strength Jurisdiction Policy Files) in the following folder of the Web application:

META-INF/ext_security/jre6 - for applications, running on JDK 1.6

META-INF/ext_security/jre7 - for applications, running on JDK 1.7

2. If the application consists of multiple WAR files, pack the encryption policy files in one of them.3. Deploy the application on SAP HANA Cloud.

Results

The encryption policy files (Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files) will be installed on the JVM of the application prior to start. As a result, the application can use unlimited strength encryption.

ExampleThe WAR file of the application must have the following file entries:

META-INF/ext_security/jre6/local_policy.jar

META-INF/ext_security/jre6/US_export_policy.jar

META-INF/ext_security/jre7/local_policy.jar

META-INF/ext_security/jre7/US_export_policy.jar

526P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 527: Hana Cloud

Related LinksDeploying Applications [page 532]

1.3.8.6 Protecting from Cross-Site Scripting (XSS)

What is Cross-Site Scripting (XSS)

Cross-site Scripting (XSS) is the name of a class of security vulnerabilities that can occur in Web applications. It summarizes all vulnerabilities that allow an attacker to inject HTML Markup and/or JavaScript into the affected Web application's front-end.

XSS can occur whenever the application dynamically creates its HTML/JavaScript/CSS content, which is passed to the user's Web browser, and attacker-controlled values are used in this process. In case these values are included into the generated HTML/JavaScript/CSS without proper validation and encoding, the attacker is able to include arbitrary HTML/JavaScript/CSS into the application's frontend, which in turn is rendered by the victim's Web browser and, thus, interpreted in the victim's current authentication context.

This guide describes the solutions provided by SAP HANA Cloud that help applications to protect against this class of vulnerabilities.

Protecting Applications Using SAP UI5

For SAPUI5 applications, XSS vulnerabilities can exist at different levels:

● Within the HTML page or custom data transports sent to the browser by the server● Within the JavaScript Code of the application processing server responses● Within the HTML renderers of SAPUI5 controls

For more information about the security measures implemented by SAPUI5, see SAP UI5 Documentation.

Protecting Applications via the XSS Output Encoding Library

For all cases not covered automatically by SAP UI5, SAP HANA Cloud provides an output encoding library that helps protecting from XSS vulnerabilities. It is a central library that implements several encoding methods for the different contexts.

In the application node, first retrieve the com.sap.security.core.server.csi.IXSSEncoder interface using com.sap.security.core.server.csi.XSSEncoder.getInstance().

The interface provides methods for retrieving parameters or attributes, and for encoding and decoding data.

It also has various methods for different data types that should be encoded:

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 527

Page 528: Hana Cloud

Data Type Code Sample for Encoding

HTML / XML: out = XSSEncoder.encodeHTML( in ); / XSSEncoder.encodeXML( val );

JavaScript: out = XSSEncoder.encodeJavaScript( val );

URL: out = XSSEncoder.encodeURL( val );

CSS: out = XSSEncoder.encodeCSS( val );

Installing the XSS Output Encoding Library

Тo use XSS output encoding API, you need to add it as library to the Dynamic Web Project. This is done with the following steps:

1. In the Project Explorer view, select the persistence-with-jpa/WebContent/WEB-INF/lib node.

2. From the context menu, choose Import General File System and choose Next.3. Browse to your local directory where you downloaded and unpacked the SAP HANA Cloud SDK, select the

repository/plugins directory, and choose OK.4. Select the archive com.sap.security.core.server.csi_1.x.y.jar and choose Finish.

Using the XSS Output Encoding Library

In the following example, we demonstrate the use of the XSS Output Encoding API. The example has one HTML form that retrieves user input, which can contain malicious code:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html> <head><title>Login Page</title><link rel="stylesheet" href="resources/login.css" /><meta http-equiv="cache-control" content="no-cache"/> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> </head> <body> <div class="fields"><form method="post" action="checkedInput.jsp"> <span class="header">Enter your names:</span><br/> <table border="0"> <tr> <td>First name: </td> <td><input name="firstname"/></td> </tr><tr> <td>Last name: </td> <td><input name="lastname"/></td></tr><tr><td></td><td><input type="submit" value="Submit"/></td>

528P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 529: Hana Cloud

</tr> </table> </form> </div></body></html>

Тhis form sends parameters to a second JSP:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ page import="com.sap.security.core.server.csi.IXSSEncoder" %><%@ page import="com.sap.security.core.server.csi.XSSEncoder" %><%@ page import="java.io.UnsupportedEncodingException" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><title>Welcome</title><link rel="stylesheet" href="resources/login.css" /><meta http-equiv="cache-control" content="no-cache"/> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> </head><body><div class="fields"> <form><%String encodedName = validateInput(request.getParameter("firstname"));out.println("<br>Hello, " + encodedName); String lastName = request.getParameter("lastname");out.println("<br> Hacked: " + lastName);%> </form> </div> <%! private String validateInput(String firstName) {String encodedInput = null; IXSSEncoder xssEncoder = XSSEncoder.getInstance();try {encodedInput = xssEncoder.encodeHTML(firstName).toString(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return encodedInput; } %> </body></html>

Even though the attacker might attempt to inject malicious code in both parameters - firstname and lastname, the firstname is protected, since it uses the output encoding library to neutralize all special symbols. However, the attack attempt will be successful for the lastname parameter since it is printed directly to the output. This is unsafe behavior and should be avoided.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 529

Page 530: Hana Cloud

1.3.8.7 Protecting from Cross-Site Request Forgery (CSRF)

Cross-site request forgery is also known as one-click attack or session riding and abbreviated as CSRF or XSRF. The main step in the attack is that a malicious user tricks the victim into invoking a URL that performs a security sensitive action. If the victim has already logged in in the attacked site, the browser has already received session cookies for it. Those cookies are sent automatically with the request. The server checks the cookies and confirms that the action has been initiated by the user. The predictability of the URL is a prerequisite for the attacker to guess it, so that he/she is able to trick the victim into executing it. Therefore the most common prevention to this attack is to add a token to the URL that is unique for each session or request depending on the implementation. This makes the URL different each time, therefore it is impossible for the attacker to guess the URL and to perform the attack.

SAP HANA Cloud provides protection based on Tomcat's CSRF Prevention Filter. The prevention mechanism is based on a token (a nonce value) generated on each request and stored in the session. The token is used to encode all URLs on the current site. Upon request to a protected URL the existence and value of the token is checked. The request is allowed to proceed only if the nonce from the token equals the one stored in the session. The prevention mechanism is applied for all URLs mapped to the filter except for specially defined entry points.

Prerequisites

You have created a working Web application and have enforced authentication for it, as described in User Authentication.

For the purposes of this tutorial, an example application consisting of the following URLs will be used:

● /home - displays home page, and has links to /doActionA and /doActionB● /doActionA - executes a security sensitive action A, and also has a link to /doActionB● /doActionB - executes a security sensitive action B

Adding CSRF Prevention to a Web Application

1. Choose entry point URLs

Entry points are URLs used as a starting point for the navigation across the application. They are not protected against CSRF as requests to them will not be tested for the presence of a valid nonce. Entry points should meet the following criteria:

● Entry points are protected resources .

○ Entry points should not trigger any security sensitive actions.○ Using the full set of entry points as navigation starting points, it should be possible to reach any link in the

application that is being protected against CSRF.

Considering the example application, /doActionA and /doActionB are not plausible for entry points since they are state changing URLs. They should be protected against CSRF. Following the rules above, you could easily conclude that /home is best suited to be the entry point.

2. Define the filter in the application's web.xml

530P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 531: Hana Cloud

The CSRF Prevention Filter should be defined in the web.xml configuration file. Important init parameters are entryPoints and nonceCacheSize. The first parameter's value is a comma separated list of the entry points, identified in the previous step. In this case /home.

The second parameter, nonceCacheSize, should be used in case of parallel requests that might cause a new nonce to be generated, before the validation of an encoded URL. The nonceCacheSize parameters defines the number of previous values stored. The default number is 5.

The definition below will protect all URLs except for the entry point /home.

<filter> <filter-name>CsrfFilter</filter-name> <filter-class>org.apache.catalina.filters.CsrfPreventionFilter</filter-class> <init-param> <param-name>entryPoints</param-name> <param-value>/home</param-value> </init-param> </filter>

3. Define the filter mapping in the web.xml

The general recommendation is to enable the filter for all URLs using the pattern /*:

<filter-mapping> <filter-name>CsrfFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

4. Encode all URL links

In the example application the URLs that should be encoded are /protected/doActionA and /protected/doActionB in /protected/home, and the /protected/doActionB URL in /protected/doActionA. To encode the URLs use HttpServletResponse#encodeRedirectURL(String) or HttpServletResponse#encodeURL(String).

Here is the source for the home.jsp, mapped to /protected/home.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Home</title></head><body> This is a home page and I am an entry point. <br/>

<% String urlActionA = "doActionA"; String urlActionAEncoded = response.encodeURL(urlActionA); %> <form action="<%=urlActionAEncoded %>" method="POST"> <input type="text" name="arg" value="A"/> <input type="submit" value="Do Action A"/> </form> <br/>

<% // Encode URL for action B

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 531

Page 532: Hana Cloud

String urlActionB = "doActionB"; String urlActionBEncoded = response.encodeURL(urlActionB); %> <form action="<%=urlActionBEncoded %>" method="POST"> <input type="text" name="arg" value="B"/> <input type="submit" value="Do Action B"/> </form> <br/></body></html>

5. Adding new URLs to a CSRF protected application

In case a new URL needs to be added to the application later, for example, /newlink, then you should evaluate its need of CSRF protection. For example, if it executes a state changing action, it certainly should be protected. Depending on the case there are two possibilities:

● No CSRF protection is neededThe URL should be defined as entry point. This is done by editing the web.xml and adding the new URL to the value of the init parameter entryPoints of the CsrfPreventionFilter from step 2. The new value should be separated with a comma.

● CSRF protection is needed.The /newlink URL should be encoded in all pages that use it as described in step 4.

All CSRF protected links that are used in the new page should be encoded, as described in step 4.

1.3.9 Deploying Applications

After you have created your application, you need to deploy and run it on SAP HANA Cloud. We recommend that you first deploy and test your application on the local runtime before deploying it on the cloud.

Eclipse IDE

If you have developed your application using the Eclipse IDE and SAP HANA Cloud Tools, you can deploy the application from inside the Eclipse IDE.

Deploying Locally from Eclipse IDE [page 533]

Deploying on the Cloud from Eclipse IDE [page 535]

SAP HANA Cloud console client

If you want to deploy existing or developed with another development environment applications, use SAP HANA Cloud console client. With this tool, you can deploy applications in the form of WAR files.

Deploying Locally with the Console Client [page 536]

Deploying on the Cloud with the Console Client [page 537]

532P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 533: Hana Cloud

1.3.9.1 Deploying Locally from Eclipse IDE

Follow the steps below to deploy an application on SAP HANA Cloud local runtime.

Procedure

1. Open the servlet in the Java Editor and from the context menu, choose Run As Run on Server .2. Window Run On Server opens. Make sure that the Manually define a new server option is selected.

3. As server type, select SAP SAP HANA Cloud Local Runtime and then choose Finish.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 533

Page 534: Hana Cloud

4. The local runtime starts up in the background and your application is installed, started and ready to serve requests.Also, if this is the first server you run in your IDE workspace, a folder Servers is created and appears in the navigation tree of the Eclipse IDE. It contains configurable folders and files you can use, for example, to change your HTTP or JMX port.

5. The Internal Web Browser opens in the editor area and shows the application.

534P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 535: Hana Cloud

1.3.9.2 Deploying on the Cloud from Eclipse IDE

Follow the steps below to deploy an application on SAP HANA Cloud.

Procedure

1. Open the servlet in the Java editor and from the context menu, choose Run As Run on Server .2. The Run On Server dialog box appears. Make sure that the Manually define a new server option is selected.

3. As server type, select SAP SAP HANA Cloud .4. For Server's host name, use the landscape host depending on your account type: for customer and partner

accounts, use hana.ondemand.com; for developer accounts, use hanatrial.ondemand.com.5. Choose Next.6. On the New Server wizard page, specify your application name (only lowercase Latin letters and digits are

allowed).The application name should be unique enough so that your deployed application can be easily identified.

7. Enter your account name, e-mail or user name, and password.

Note○ When deploying, use the respective landscape host for your account type. For more information, see

Account types .○ Applications using features or services in beta state cannot be deployed in customer SAP HANA Cloud

accounts. Beta features and services can be tested with the free developer account, which you can request on http://hanatrial.ondemand.com.

○ Developer accounts are intended for personal exploration, and not for use in a production environment or for team development. You cannot assign members to the account (you will not see the <Members> list normally available).

○ A developer account has only one virtual machine (VM) at its disposal. You can deploy multiple applications, but you can start only one application at a time.

8. Choose Finish.This triggers the publishing of the application on SAP HANA Cloud.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 535

Page 536: Hana Cloud

NoteYou cannot deploy multiple applications to the same SAP HANA Cloud application process (node). Deployment of a second application on the same application process overwrites any previous deployments. If you want to deploy several applications, deploy each of them on a separate application process.

1.3.9.3 Deploying Locally with the Console Client

The console client allows you to install a server runtime into a local folder and use it to deploy your application.

536P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 537: Hana Cloud

Procedure

1. Open the folder <SDK installation folder>/tools.

2. Open the command prompt, enter the following command, and press ENTER:

neo install-local

This installs a server runtime into the default local server directory <SDK installation folder>/server. To use an alternative directory, enter the command together with the following optional command argument:

--location <local server directory>

3. To start the local server, enter the following command and press ENTER:

neo start-local

This starts a local server instance in the default local server directory <SDK installation folder>/server. Again, use the following optional command argument to specify another directory:

--location <local server directory>

4. To deploy your application, copy the WAR file to the directory <SDK installation folder>/server/pickup, or to the pickup folder of the alternative local server directory you specified above.

5. To check your application is running, open a browser and enter the URL, for example:

http://localhost:8080/HelloWorld

NoteThe HTTP port is normally 8080. However, the exact port configurations used for your local server, including the HTTP port, are displayed on the console screen when you install and start the local server.

6. To stop the local server instance, enter the following command from the <SDK installation folder>/tools folder and press ENTER:

neo stop-local

1.3.9.4 Deploying on the Cloud with the Console Client

Deploying an application publishes it to SAP HANA Cloud. During deploy, you can define various specifics of the deployed application using the deploy command optional parameters.

Prerequisites

Applications using features or services in beta state cannot be deployed in customer SAP HANA Cloud accounts. Beta features and services can be tested with the free developer account, which you can request on http://hanatrial.ondemand.com.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 537

Page 538: Hana Cloud

Procedure

1. In the opened command line console, execute neo deploy command with the appropriate parameters.

2. Enter your password if requested.3. Press ENTER and deployment of your application will start. If deployment fails, check if you have defined the

parameters correctly.

Example

neo deploy --account <your account> --application <application name> --source samples/deploy_war/example.war --user <email or user name>

You can define the parameters of commands directly in the command line as in the example above, or in the properties file. For more information, see SAP HANA Cloud Console Client.

Next Steps

To make your deployed application available for requests, you need to start it by executing the ‘neo start’ command.

Then, you can manage the application lifecycle (check the status; stop; restart; undeploy) using dedicated console client commands.

Related LinksReference of related console client commands with a complete list of their parameters:Deploy [page 539]Deploying an application publishes it to SAP HANA Cloud. Use the optional parameters to make some specific configurations of the deployed application.

Start [page 541]After you have deployed your application to SAP HANA Cloud, you need to start it in order to make it available for customers.

Status [page 542]You can check the current status of a deployed application on SAP HANA Cloud. For example, you can check if an application has been started or stopped successfully.

Restart [page 544]Use this command to restart your application. The effect of the restart command is the same as executing the stop command first and when the application is stopped, starting it with the start command.

Stop [page 543]Use this command to stop your deployed and started application on SAP HANA Cloud.

Undeploy [page 545]Undeploying an application removes it from SAP HANA Cloud. To undeploy an application, you have to stop it first.

538P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 539: Hana Cloud

1.3.9.4.1 Deploy

Deploying an application publishes it to SAP HANA Cloud. Use the optional parameters to make some specific configurations of the deployed application.

Example

neo deploy --account <your account> --application <application name> --source <file location> --user <e-mail or user name>

To list all parameters available for the deploy command, execute neo help deploy.

Parameter Value Note

Mandatory

--account account name

--application application name

--user your e-mail or user for login to hana.ondemand.com

--source a comma-separated list of file locations, pointing to WAR files, or folders containing them

If you want to deploy more than one application on one and the same application process, put all WAR files in the same folder and execute the deployment with this source, or specify them as a comma-separated list.

Optional

--host SAP HANA Cloud host Defaults to https://hana.ondemand.com. Use the respective landscape host for your account type: for customer accounts, use hana.ondemand.com; for developer accounts, use hanatrial.ondemand.com.

--password password for your user You will be asked to provide a password if this argument is not specified.

NoteTo protect your password, enter it only when prompted by the console client and not explicitly as a parameter in the properties file or the command line.

--minimum-processes

minimum number of application processes (nodes), on which the application can be started

Defaults to 1

--maximum-processes

maximum number of application processes (nodes),

Defaults to 1

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 539

Page 540: Hana Cloud

Parameter Value Note

on which the application can be started

--vm-arguments

JVM system properties (-D<name>=<value>) separated with space that will be used when starting the application process.

You can also use -vm arguments to define custom memory settings of your compute units. You can set the following memory parameters: -Xms, -Xmx, -XX:PermSize, -XX:MaxPermSize.

For example,

neo deploy <other parameters> --vm-arguments "-Dexample=value '-Dlocation=~/file location'"

or in the properties file: vm-arguments=-Dexample=value '-Dlocation=~/file location'

We recommend that you use the default memory settings. Change them only if necessary and note that this may impact the application performance or its ability to start.

--size Compute Unit size:

lite, pro, prem, prem-plus

If not specified, the size is inherited from the account settings.

--runtime-version

version of SAP HANA Cloud application runtime.

For example, --runtime-version 1.22

Specifies the runtime version on which the application will be started and will run on the same version after a restart. Otherwise, by default, the application is started on the latest minor version (of the same major version) which is backward compatible and includes the latest corrections (including security patches), enhancements, and updates. Note that choosing this option does not affect already started application processes.

You can view the recommended versions by executing the list-runtime-versions command.

NoteIf you choose your runtime version, consider its expiration date and plan updating to a new version regularly.

--java-version JVM version Only the major version number of the JVM can be specified (6 or 7).

Examples

Here are examples of some additional configurations. If your application is already started, stop it and start it again for the changes to take effect

Define JVM Version

540P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 541: Hana Cloud

If you want to specify the JVM version, use the --java-version parameter. Note that only the major version number of the JVM can be specified (6 or 7).

For example, to use Java SE 7 Hotspot compatible JVM, execute the following command:

neo deploy --java-version 7 samples/deploy_war/example_war.properties

Choose Compute Unit Size

If you want to specify the compute unit size on which you want the application to run, use the --size parameter with one of the following values:

● lite - Lite Edition● pro - Professional edition● prem - Premium edition● prem-plus - Premium Plus edition

Available sizes depend on your account type and what options you have purchased. For developer accounts, only the Lite edition is available.

For more information, see Compute Units.

For example, if you have a productive account and have purchased a package with Premium edition Compute Units, then you can run your application on a Premium compute unit size, by executing the following command:

neo deploy --size prem samples/deploy_war/example_war.properties

Set the context root of an application

When deploying an application, name the WAR file with the desired context root.

For example, if you want to deploy your WAR in context root "/hello" then rename your WAR to hello.war.

If you want to deploy it in the "/" context root then rename your WAR to ROOT.war.

Related LinksSAP HANA Cloud Console Client [page 61]

1.3.9.4.2 Start

After you have deployed your application to SAP HANA Cloud, you need to start it in order to make it available for customers.

Example

neo start --account <your account> --application <your application> --user <email or user name>

To list all parameters available for the start command, execute neo help start.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 541

Page 542: Hana Cloud

Parameter Value Note

Mandatory

--account account name

--application application name

--user your e-mail or user for login to hana.ondemand.com

Optional

--host SAP HANA Cloud host Defaults to https://hana.ondemand.com

--password password for your user You will be asked to provide a password if this argument is not specified.

NoteTo protect your password, enter it only when prompted by the console client and not explicitly as a parameter in the properties file or the command line.

--synchronous none The following command triggers the starting process and waits until the application is started.

neo start --account <your account> --application <your application> --user <user name or email> --synchronous

The same command without the --synchronous parameter will trigger the starting process and exit immediately without waiting for the application to start.

Related LinksSAP HANA Cloud Console Client [page 61]

1.3.9.4.3 Status

You can check the current status of a deployed application on SAP HANA Cloud. For example, you can check if an application has been started or stopped successfully.

Example

neo status --account <your account> --application <your application> --user <email or user name>

To list all parameters available for the status command, execute neo help status.

542P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 543: Hana Cloud

Parameter Value Note

Mandatory

--account account name

--application application name

--user your e-mail or user for login to hana.ondemand.com

Optional

--host SAP HANA Cloud host Defaults to https://hana.ondemand.com

--password password for your SCN user You will be asked to provide a password if this argument is not specified.

NoteTo protect your password, enter it only when prompted by the console client and not explicitly as a parameter in the properties file or the command line.

Related LinksSAP HANA Cloud Console Client [page 61]

1.3.9.4.4 Stop

Use this command to stop your deployed and started application on SAP HANA Cloud.

Example

neo stop --account <your account> --application <your application> --user <user name or email>

To list all parameters available for the stop command, execute neo help stop.

Parameter Value Note

Mandatory

--account account name

--application application name

--user SCN user for login to hana.ondemand.com

You can also use your e-mail.

Optional

--host SAP HANA Cloud host Defaults to https://hana.ondemand.com

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 543

Page 544: Hana Cloud

Parameter Value Note

--password password for your user You will be asked to provide a password if this argument is not specified.

NoteTo protect your password, enter it only when prompted by the console client and not explicitly as a parameter in the properties file or the command line

--synchronous none The following command triggers the stopping process and waits until the application is stopped.

neo stop --account <your account> --application <your application> --user <user name or email> --synchronous

The same command without the --synchronous parameter will trigger the stopping process and exit immediately without waiting for the application to stop.

Related LinksSAP HANA Cloud Console Client [page 61]

1.3.9.4.5 Restart

Use this command to restart your application. The effect of the restart command is the same as executing the stop command first and when the application is stopped, starting it with the start command.

Example

neo restart --account <your account> --application <your application> --user <e-mail or user name>

To list all parameters available for the restart command, execute neo help restart.

Parameter Value Note

Mandatory

--account account name

--application application name

--user your e-mail or user for login to hana.ondemand.com

Optional

--host SAP HANA Cloud host Defaults to https://hana.ondemand.com

544P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 545: Hana Cloud

Parameter Value Note

--password password for your user You will be asked to provide a password if this argument is not specified.

NoteTo protect your password, enter it only when prompted by the console client and not explicitly as a parameter in the properties file or the command line.

--synchronous none The following command triggers the restart and waits until the application is started.

neo restart --account <your account> --application <your application> --user <e-mail or user name> --synchronous

The same command without the --synchronous parameter will trigger the restart and exit immediately without waiting for the application to start.

1.3.9.4.6 Undeploy

Undeploying an application removes it from SAP HANA Cloud. To undeploy an application, you have to stop it first.

Example

neo stop --account <your account> --application <your application> --user <user name or email> neo undeploy --account <your account> --application <your application> --user <email or user name>

To list all parameters available for the undeploy command, execute neo help undeploy.

Parameter Value Note

Mandatory

--account account name

--application application name

--user your e-mail or user for login to hana.ondemand.com

Optional

--host SAP HANA Cloud host Defaults to https://hana.ondemand.com

--password password for your user You will be asked to provide a password if this argument is not specified.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 545

Page 546: Hana Cloud

Parameter Value Note

NoteTo protect your password, enter it only when prompted by the console client and not explicitly as a parameter in the properties file or the command line.

Related LinksSAP HANA Cloud Console Client [page 61]

1.3.10 Profiling Applications

Overview

After you have created a non-trivial Web application and verified that it is functionally correct, you may want to inspect its runtime behavior by profiling the application.

NoteCurrently, it is only possible to profile a locally running Web application.

Prerequisites

● You have developed a cloud application using the Eclipse IDE.● You have installed SAP JVM as the runtime for the local server.● You have installed SAP JVM Profiler into your Eclipse IDE.

Procedure

1. Deploy and run the Web application on the local server.For more information, see Deploying Applications [page 532].

2. When the local server is running, that is it is in started state, choose Window Open Perspective Other... to open the perspective dialog.

3. Choose SAP JVM Profiler to switch to the Profiling perspective.

546P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 547: Hana Cloud

The Profiling perspective opens and displays the Profiling Intro.4. Select Profile Local Application from the Profiling Intro editor page.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 547

Page 548: Hana Cloud

5. Select the org.eclipse.equinox.launcher.Main entry and choose Next.6. Choose the type of analysis to perform. You can check the documentation of the SAP JVM Profiler (available

in the Eclipse IDE via Help Help Contents SAP JVM Profiler ) for more details.

548P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 549: Hana Cloud

7. Choose Finish to connect the profiler and start the analysis.

Result

You have successfully started a profiling run of a locally deployed Web application. You can now trigger your work load, create snapshots of the profiling data and analyze the profiling results.

Next Steps

You can have a look at SAP JVM Profiler documentation for details about the available analysis options. The documentation is available as part of the SAP JVM Profiler plugin in the Eclipse IDE and can be found via HelpHelp Contents SAP JVM Profiler . In addition to that, a link to Getting Started Tutorials of the SAP JVM Profiler is also located at the bottom of the Profiling Intro editor page.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 549

Page 550: Hana Cloud

1.3.11 Logging in Applications

Overview

If you want to have logs produced at runtime, which you can use for analysis and troubleshooting, you have to use a logging API in your SAP HANA Cloud application.

For SAP HANA Cloud applications, we recommend that you use the Simple Logging Facade for Java (SLF4J). The API is built upon using Logger class. All logs are put in the default trace file of the server and are visualized at runtime in the Cockpit.

Prerequisites

You have created an application for SAP HANA Cloud.

For more information, see Creating a HelloWorld Application.

Implementing the SLF4J API in your application

Follow the guidelines in the SLF4J User Manual.

SAP HANA Cloud applications can access SLF4J API directly without adding any references or packaging the library in the application archive.

Example

You can add an error log in your application with the following code:

import org.slf4j.Logger;import org.slf4j.LoggerFactory;

public class YourClass { public static void main(String[] args){ Logger logger = LoggerFactory.getLogger(YourClass.class); logger.error("message"); }}

To construct a parameterized message, you can use one of the following ways:

● Passing the parameter inside the message String

550P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 551: Hana Cloud

You also need to add a log level check here - this will help you avoid creating too many String objects which could lead to performance issues of your application.

if (logger.isInfoEnabled()) { logger.info("Message logged for name " + name + " with level info");}

● Passing the parameter as an argument to the respective methods (info, error, and so on):

logger.info("Message logged for name {} with level info", name);

For more tips and tricks, check the SLF4J FAQ.

Log severity mapping

SLF4J uses the following log severity levels:

SLF4J Description

DEBUG This level designates fine-grained informational events that are most useful to debug an application.

INFO This level designates informational messages that highlight the progress of the application at coarse-grained level.

WARN This level designates potentially harmful situations.

ERROR This level designates error events that might still allow the application to continue running.

Related Links

SLF4J API

Next Steps

After the application is deployed and running on SAP HANA Cloud, you can see its logs in the Cockpit.

For more information, see Applications [page 52].

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 551

Page 552: Hana Cloud

1.3.11.1 Managing Application Logs from the Eclipse IDE

Overview

You can view the logs of your deployed applications and change the effective level of loggers on both SAP HANA Cloud and SAP HANA Cloud local runtime. This section describes how you do this from the Eclipse IDE.

If you want to set or change the log level from the console client, see Managing Application Logs Using the Console Client [page 554] → subsection "Setting Log Levels".

Prerequisites

● You have downloaded and set up your Eclipse IDE, SAP HANA Cloud Tools for Java and SAP HANA SDK.For more information, see Setting Up the Tools and SDK [page 27] or Updating the Tools and SDK [page 34].

● You have created and deployed a Web application that uses logging functionality on SAP HANA Cloud.For more information, see Logging in Applications [page 550].

Setting Log Levels for Loggers

1. After deploying an application in the Eclipse IDE on SAP HANA Cloud or SAP HANA Cloud local runtime, open the Servers view and double-click the server.

2. Choose the Loggers tab.3. When the server is in [Started] state, all the available loggers are listed in the Loggers table. If the server is in

[Starting], [Stopping], or [Stopped] state, the table is empty.

○ You can use the filter field to find particular loggers you need. You can filter by both the Name and the Level columns.

○ You can also sort the loggers table by both the Name and the Level column. The Level column sorts the fields by effective level, not alphabetically.

552P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 553: Hana Cloud

4. To change a logger level, go to the relevant row in the table and select the new log level from the Level column.You can configure as many loggers as you need.

5. If you need to simultaneously set a log level for all the currently displayed loggers, go to Set the shown loggers to level and select the desired one.Besides for all available server loggers in the table, this feature is also applicable for a list of loggers displayed after filtering.

6. Save your changes using the Save button from the main menu or by pressing Ctrl+S.

7. To refresh the loggers table, choose the button.

NoteIf you try to refresh your loggers before saving your changes, a dialog appears warning you that your changes will be lost.

Note that log levels are reset to their initial value when the server is restarted.

Viewing Log Files

1. In the Servers view, go to the context menu of your server and choose Show In Server Logs .

Note

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 553

Page 554: Hana Cloud

If the server has never been started, no logs are available and the Server Logs view is empty.

2. When the server is started, the Server Logs view displays all available Default Trace and HTTP Access logs of the applications that you are running on this server.

NoteYou can also reach the Server Logs view if you expand the server and double-click on the Server Logs node.

3. If you have more than one running servers, from the Server dropdown box, select the one you need to view its logs.

4. You can sort your log files by all columns.

5. To refresh the log files table, choose the button.6. Double-click on a log to see its details in the Console. You can then:

○ Open the log in an editor, choosing the button.

○ Clear the log console, choosing the button.

○ Close the log console, choosing the button.

Related LinksManaging Application Logs Using the Console Client [page 554]

1.3.11.2 Managing Application Logs Using the Console Client

Overview

After you have deployed and started an application on SAP HANA Cloud, you can manage some of its logging configurations using SAP HANA Cloud console client. For easier troubleshooting, you can use the commands from the logging group to:

● list available log files;● download a log file;● list available loggers;● change the log level of a particular logger.

554P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 555: Hana Cloud

Prerequisites

● You have created and deployed a Web application which uses logging functionality on SAP HANA Cloud.For more information, see Logging in Applications [page 550].

● You have downloaded and set up the SAP HANA Cloud console client.For more information, see Setting Up SAP HANA Cloud Console Client [page 32]

Procedure

1. Open the Command Prompt.2. Navigate to the bin folder of the SDK location.3. Enter neo help to display all the commands of the console client or neo help <command_name> to display

the help information for a command.

For more information about argument values usage, see SAP HANA Cloud Console Client [page 61].

Listing Available Log Files

You can list all log files of your application sorted by date in a table format, starting with the latest modified.

To do that, execute the following command:

neo list-logs --account <account_name> --application <application_name> --user <user_name> --host <SAP_HANA_Cloud_host>

Downloading Log Files

To download a particular log file, execute the following command:

neo get-log --account <account_name> --application <application_name> --user <user_name> --host <SAP_HANA_Cloud_host> --directory <local_folder_location_of_the_file> --file <file_name>

You can also use the --overwrite command argument so that in case a file with the same name already exists, it will be overwritten. If a file with the same name already exists and you do not explicitly include --overwrite, you will be notified and asked if you want to overwrite it.

If the directory you have specified in the command line does not exist, it will be created.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 555

Page 556: Hana Cloud

Listing Loggers

To list available loggers and their log levels, execute the following command:

neo list-loggers --account <account_name> --application <application_name> --user <user_name> --host <SAP_HANA_Cloud_host>

Setting Log Levels

To set a log level for a logger, execute the following command:

neo set-log-level --account <account_name> --application <application_name> --user <user_name>--host <SAP_HANA_Cloud_host> --logger <logger_name> --level <log_level>

NoteLog levels are reset to their initial value when the server is restarted.

Example

1. You can deploy the example_war.properties file on SAP HANA Cloud and then change its log level to INFO.2. After deploying the application, execute the following command:

neo set-log-level --account <account_name> --application <application_name> --user <user_name> --host <SAP_HANA_Cloud_host> --logger com.mycompany.superapp.ui.Utils --level INFO

3. Request the example application in the browser and then download and open the ljs_trace.log file.

As a result, a new info message is logged indicating that the logger level has been changed successfully.

1.3.11.3 Using Logs in the Cockpit

You can view the logs and change the log settings of any applications deployed in your account.

Viewing Logs

Two types of logs are available on the SAP HANA Cloud platform: default trace logs and HTTP access logs.

556P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 557: Hana Cloud

Procedure

1. Log into the cockpit from the SAP HANA Cloud landing page:

○ Customer and partner accounts: https://account.hana.ondemand.com○ Developer accounts: https://account.hanatrial.ondemand.com

2. Choose Applications in the navigation area and click the relevant application to go to the dashboard.

TipThe newest logs are listed in the Most Recent Logging screen area.

3. In the navigation area, choose Logging.All log files written for the selected application are listed with the following information: log file type; log file size; date and time of the last modification, with the applicable time zone.

4. Click the log file name to display the contents of a particular log file.

Changing Log Settings

To obtain the required level of detail in the logs, you can change the log levels set for the loggers used by your application. These include platform loggers and, if configured, the application logger, named as follows: <package name>.<class name>, for example, com.sap.cloud.sample.persistence.PersistenceWithJDBCServlet.

Context

When setting log levels, you should bear in mind that an inheritance mechanism applies within the logger class hierarchy, which is not immediately visible.

Example:

Class Level Logger Log Level

Parent com.sap.core.js.admin.operations Information

Child com.sap.core.js.admin.operations.AdminOperations Information

Child com.sap.core.js.admin.operations.internal.ErrorQueueHandler Information

If you set a new log level for the parent logger, the child loggers automatically inherit the same log level. However, if you change the log level for a child logger class, this breaks the inheritance relationship between the child and its parent class and any changes made subsequently to the log level of the parent class, whether explicitly or through inheritance, will not be passed down to this child.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 557

Page 558: Hana Cloud

Procedure

1. To change the log levels for a particular application, select the application and choose Logging in the navigation area.

2. In the Log Settings section in the content area, a list of all loggers used by the application is shown with the log levels that are currently applicable.

3. Optionally filter the list by logger name to select only the loggers in which you are interested.4. To set the log level for a logger, locate the relevant logger and in that row select the new log level from the

dropdown list.5. To change the log level for all loggers contained in the list, enter the new log level in the Set loggers to level

field and choose Set. Note that there might be a slight delay depending on the number of loggers you have selected.

Note○ The settings take effect immediately.○ The log levels are reset to their initial value when the application is restarted.

Related LinksSAP HANA Cloud Cockpit [page 50]

1.3.12 Monitoring Applications

To monitor whether your deployed application is up and running, you can register an availability check and JMX checks for it and configure email recipients who will receive notification if the application goes down. To do that, you use the SAP HANA Cloud console client.

Related LinksFor more information about the specifics of the different types of checks, see:Availability Checks [page 559]

JMX Checks [page 561]Registering JMX checks allows alerting on any metric that is based on JMX MBean attribute.

To learn how you can configure an availability check, see:Tutorial: Configuring an Availability Check to Monitor Your Application [page 561]This step-by-step tutorial shows how you can configure an availability check for your application and configure e-mail recipients to receive alert e-mail notifications when your application is down. You will configure the availability check for your application "demo", deployed in your account "myaccount" with your user "s1234567" and set the e-mail "[email protected]" as a recipient of alert e-mails.

For more information about available monitoring commands and their parameters, see:Availability Checks Commands [page 562]JMX Checks Commands [page 565]Alert Recipients Commands [page 568]

558P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 559: Hana Cloud

1.3.12.1 Availability Checks

The availability check is one per application and is executed every minute. If your application is not available or its response time is too high, you will receive an e-mail notification. If you stop the application by yourself, you will not receive a notification as in this case alerting is suppressed and enabled once again when you start the application. E-mail alert is triggered if the application is not in state OK for 2 consecutive checks. There are 5 types of notifications:

Notification Description

CRITICAL Your application is not available or the response time is above the CRITICAL threshold.

WARNING The response time of your application is above the WARNING threshold.

OK Your application has recovered from CRITICAL/WARNING state.

UNSTABLE Your application does not behave consistently. For example, the response time is OK upon check n, then is CRITICAL upon check n+1, then is again OK on check n+2, and so on.

STABLE Your application behaves consistently again.

You may also set your availability check on account level using relative URL. This means that each application started in your account will immediately receive an availability check requesting application_url/configured_relative_url. This option is useful in case you start multiple productive instances of one and the same application in your account and allows you to configure this check only once for all of them. If there is a check configured on account level and a check configured on application level, the one on the application level has higher priority. For example, if you have in your account 10 instance of application A and one instance of application B, you can configure availability check for all of them using one configuration on account level and one configuration for application B.

Limitations

Availability monitoring in SAP HANA Cloud is done by running http/https pings. The http/https ping is not parsing the response body, but it is relying only on the http response codes.

Currently there are two limitations that need to be considered when designing your availability URL:

● The monitoring infrastructure does not support authorization for the checks. This means that you cannot pass user and password when configuring the availability check. Therefore, it is better to design the availability URL without authentication or authorization. This will make sure that your application can be accessed in any case, the correct response code is returned (for example 404, 500) and the response time is only from your application.

○ If your application has authentication based on SCN and it is SAML2, if you do not have additional authorization afterwards, it will behave in the same way as without authentication/authorization except for the response time. Identity provider response time will be added to your application response time.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 559

Page 560: Hana Cloud

○ If you have non-SAML2 or non-SCN based authentication, the check will return 'ok' if your application is started successfully and it will stop the requests at the IDP (response code will be 401).

○ If you have SAML2 and SCN-based authentication but have additional authorization afterwards, the check will return 'ok' if your application is running to the point of the additional authorization (the response code should be 403).

○ Currently the error codes accepted by the 'http/https ping' are 200, 302, 403 and 401. This is done to cover all the different types of URLs that can be monitored. If you have provided a non-protected URL for monitoring, you need to make sure that if something does not work as expected, you are not returning some of the above 4 codes as you will not get an alert.

● The monitoring infrastructure supports only one availability check per application. This means that if you have multiple web applications deployed together as one application in your account, you need to design one common availability URL to be able to monitor them all together. If one of the applications fails, you will get an alert and then you will have to check which one exactly is failing by opening the availability URL. We recommend that the response is a simple, plain HTML, just stating which web application is ok and which is not. It depends on the implementation of the availability URL whether it will just inform that a web application is available or it will also check whether it is working as expected. If you plan to develop and operate multiple applications in your account, it is a good idea to have identical availability URLs for the different applications (for example /availability). This will allow you to configure the availability check only once on account level.

Sample output of application which is OK:

HTTP RETURN CODE 200 OKPurchasing - OK

Sales - OK

Registration - OK

IDP - OK

Sample output of application that has problems:

HTTP RETURN CODE 500 INTERNAL SERVER ERRORPurchasing - OK

Sales - no connectivity to backend

Registration - OK

IDP - OK

Related LinksTutorial: Configuring an Availability Check to Monitor Your Application [page 561]This step-by-step tutorial shows how you can configure an availability check for your application and configure e-mail recipients to receive alert e-mail notifications when your application is down. You will configure the availability check for your application "demo", deployed in your account "myaccount" with your user "s1234567" and set the e-mail "[email protected]" as a recipient of alert e-mails.

Availability Checks Commands [page 562]

560P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 561: Hana Cloud

1.3.12.2 JMX Checks

Registering JMX checks allows alerting on any metric that is based on JMX MBean attribute.

The checks support attributes that are java.lang.String or java.lang.Number or CompositeDataSupport. In case it is CompositeDataSupport, the objects that are mapped to the keys again should be java.lang.String or java.lang.Number, otherwise error will be thrown. For more information, see CompositeDataSupport.

The MBean can be registered either by the application runtime (for example, standard JVM MBeans like java.lang:type=Memory) or by the application itself (application specific). The MBeans registered by the application runtime can be checked using jconsole and connecting to the local server from the SDK.

You can set multiple JMX checks per application. They will be executed each minute. In case the JMX check fails due to an error in the MBean execution like, for example, wrong ObjectName, Attribute, MBean not registered, and so on, or due to exceeded threshold, you will receive e-mail notification if you have configured an email recipient. There are 5 types of notifications:

Notification Description

CRITICAL The JMX check fails due to an error in the MBean execution or the attribute value is not within the defined CRITICAL threshold.

WARNING Attribute value is not within the defined WARNING threshold.

OK The attribute has recovered from CRITICAL/WARNING state.

UNSTABLE Your application does not behave consistently. For example, the attribute is OK upon check n, then is CRITICAL upon check n+1, then is again OK on check n+2, and so on.

STABLE Your application behaves consistently again.

You may also set JMX checks on account level. This means that each application started in your account will immediately receive all the JMX checks configured on account level in addition to the checks configured on the application level. If there is a check configured on account level and a check configured on application level with one and the same name, the one on the application level has higher priority and only it will be assigned to the started application.

Related LinksJMX Checks Commands [page 565]

1.3.12.3 Tutorial: Configuring an Availability Check to Monitor Your Application

This step-by-step tutorial shows how you can configure an availability check for your application and configure e-mail recipients to receive alert e-mail notifications when your application is down. You will configure the availability check for your application "demo", deployed in your account "myaccount" with your user "s1234567" and set the e-mail "[email protected]" as a recipient of alert e-mails.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 561

Page 562: Hana Cloud

Prerequisites

You have set up the console client.

For more information, see Setting Up SAP HANA Cloud Console Client [page 32].

Procedure

1. Open the command prompt and navigate to the folder containing neo.bat/sh (<SDK installation folder>/tools).

2. Execute neo create-availability-check -a myaccount -b demo -u s1234567 -U /heartbeat -C 4 -W 6 --host hana.ondemand.com.

You have configured an availability check for your application "demo", which will request the URL hana.ondemand.com/heartbeat and will trigger warning e-mail notification in case the response time is above 4 seconds and critical e-mail notification if the response time is above 6 seconds. You will also receive a critical notification if your application is not available.

3. To configure the e-mail "[email protected]" to receive the notifications, execute neo set-alert-recipients -a myaccount -b demo -u s1234567 -e [email protected] --host hana.ondemand.com.

CautionIf you stop the application by yourself, you will not receive a notification, as in this case alerting is suppressed and enabled once again when you start the application.

Related LinksAvailability Checks [page 559]

Availability Checks Commands [page 562]Alert Recipients Commands [page 568]

1.3.12.4 Availability Checks Commands

This document contains the SAP HANA Cloud console client commands related to availability checks and their parameters.

Listing Configured Availability Checks

list-availability-check

562P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 563: Hana Cloud

Parameter Value Note

Mandatory

--account (-a) account name

--user (-u) SCN user for login to hana.ondemand.com

--host (-h) SAP HANA Cloud host

Optional

--application (-b)

application name

--recursively (-R)

Lists availability checks recursively starting from the specified level. For example, if only 'account' is passed as an argument, it starts from the account level and then lists all checks configured on application level.

Example:

neo list-availability-check -a myaccount -b demo -u s1234567 --host hana.ondemand.com -R

Sample output:

_____ _ _____ _ _ _ / ____| SAP HANA Cloud | | / ____| (_) | || | ___ _ __ ___ ___ | | ___ | | | |_ ___ _ __ | |_| | / _ \| '_ \/ __|/ _ \| |/ _ \ | | | | |/ _ \ '_ \| __|| |____| (_) | | | \__ \ (_) | | __/ | |____| | | __/ | | | |_ \_____|\___/|_| |_|___/\___/|_|\___| \_____|_|_|\___|_| |_|\__|

Password for your user:

Running list-availability-checks with the following parameters:

account : myaccount host : https://hana.ondemand.com recursively: true SDK version: 1.2.3 user : s1234567

Account-level availability check

account : test url : /example warning : 50 critical : 60

Application availability checks

application : demo url : /example warning : 6 critical : 4

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 563

Page 564: Hana Cloud

Creating an Availability Check

create-availability-check

Parameter Value Note

Mandatory

--account (-a) account name

--user (-u) SCN user for login to hana.ondemand.com

--host (-h) SAP HANA Cloud host

--url (-U) relative application URL

Optional

--application (-b)

application name

--warning (-W) threshold value or range of the response time in seconds, default value is 50

--critical (-C) threshold value or range of the response time in seconds, default value is 60

--overwrite, (-w)

Should be used only if there is an existing alert that needs to be updated

Example

neo create-availability-check -a myaccount -b demo -u s1234567 -U /heartbeat -C 4 -W 6 --host hana.ondemand.com

Deleting an Availability Check

delete-availability-check

Parameter Value Note

Mandatory

--account (-a) account name

564P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 565: Hana Cloud

Parameter Value Note

--user (-u) SCN user for login to hana.ondemand.com

--host (-h) SAP HANA Cloud host

Optional

--application (-b)

application name

Example

neo delete-availability-check -a myaccount -b demo s1234567 --host hana.ondemand.com

1.3.12.5 JMX Checks Commands

This document contains the SAP HANA Cloud console client commands related to JMX checks and their parameters

Creating a JMX Check

create-jmx-check

Parameter Value Note

Mandatory

--account (-a) account name

--user (-u) SCN user for login to hana.ondemand.com

--host (-h) SAP HANA Cloud host

--name (-n) name of the JMX check

--object-name (-O)

object name of the MBean that you want to call

If it contains quotation marks, they should be escaped with ‘\’.

--attribute (-A) name of the attribute

Optional

--application (-b)

application name

--key (-K) attribute key It is needed only if the attribute is a composite data structure.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 565

Page 566: Hana Cloud

Parameter Value Note

--operation (-o)

operation that has to be called on the MBean after checking the attribute value

Useful for resetting statistical counters.

--unit (-U) unit of measurement

--overwrite (-w)

overwrites an existing check

--warning (-W) warning threshold The threshold can be a regular expression in case of string values or compliant with the official nagios threshold/ranges format. For more information about the format in case it is a number, see the official nagios documentation.

--critical (-C) critical threshold The threshold can be a regular expression in case of string values or compliant with the official nagios threshold/ranges format.

Example

neo create-jmx-check -a myaccount -b demo -u s1234567 -n "JVM Heap Memory Used" -O java.lang:type=Memory -A HeapMemoryUsage -K used -U B --host hana.ondemand.com

Deleting a JMX Check

delete-jmx-check

It deletes the specified JMX check or all JMX checks.

Parameter Value Note

Mandatory

--account (-a) account name

--user (-u) SCN user for login to hana.ondemand.com

--host (-h) SAP HANA Cloud host

--name (-n) or all (-A)

name of the JMX check to be deleted or all JMX checks configured for the given account and application are deleted

Optional

--application (-b)

application name

566P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 567: Hana Cloud

Parameter Value Note

--component (-c)

Example

neo delete-jmx-check -a myaccount -b demo s1234567 -n "JVM Heap Memory Used" --host hana.ondemand.com

Listing JMX Checks

list-jmx-checks

Parameter Value Note

Mandatory

--account (-a) account name

--user (-u) SCN user for login to hana.ondemand.com

--host (-h) SAP HANA Cloud host

Optional

--application (-b)

application name

--component (-c)

--recursively (-R)

Lists JMX checks recursively, starting from the specified level. For example, if only 'account' is passed as an argument, it starts from the account level and then lists all checks configured on application level.

Example:

neo list-jmx-checks -a myaccount -b demo -u s1234567 -R --host hana.ondemand.com

Sample output:

_____ _ _____ _ _ _ / ____| SAP HANA Cloud | | / ____| (_) | || | ___ _ __ ___ ___ | | ___ | | | |_ ___ _ __ | |_| | / _ \| '_ \/ __|/ _ \| |/ _ \ | | | | |/ _ \ '_ \| __|| |____| (_) | | | \__ \ (_) | | __/ | |____| | | __/ | | | |_ \_____|\___/|_| |_|___/\___/|_|\___| \_____|_|_|\___|_| |_|\__|

Password for your user:

Running list-jmx-check with the following parameters:

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 567

Page 568: Hana Cloud

account : myaccount host : https://hana.ondemand.com recursively: true user : s1234567

Account-level JMX checks

account : myaccount check-name : JVM Heap Memory Used object-name : java.lang:type=Memory critical : 60 attribute : HeapMemoryUsage attribute key : used warning : 700000000 critical : 900000000 unit : B

Application JMX checks application : demo check-name : JVM Heap Memory Used object-name : java.lang:type=Memory attribute : HeapMemoryUsage attribute key : used warning : 600000000 critical : 850000000 unit : B

1.3.12.6 Alert Recipients Commands

This document contains the SAP HANA Cloud console client commands and parameters related to configuring alert recipients. Setting an alert recipient for an application will trigger sending all alerts for this application to the configured email(s). Setting an alert recipient on account level will send all alerts for all applications in this account to the configured email(s).

Listing Configured Alert Recipients

list-alert-recipients

Parameter Value Note

Mandatory

--account (-a) account name

--user (-u) SCN user for login to hana.ondemand.com

--host (-h) SAP HANA Cloud host

Optional

568P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 569: Hana Cloud

Parameter Value Note

--application (-b)

application name

--recursively (-R)

Lists alerts recipients recursively starting from the specified level. For example, if only 'account' is passed as an argument, it starts from the account level and then lists all recipients configured on application level.

Example:

neo list-alert-recipients -a myaccount -b demo -u s1234567 -R --host hana.ondemand.com

Sample output:

_____ _ _____ _ _ _ / ____| SAP HANA Cloud | | / ____| (_) | || | ___ _ __ ___ ___ | | ___ | | | |_ ___ _ __ | |_| | / _ \| '_ \/ __|/ _ \| |/ _ \ | | | | |/ _ \ '_ \| __|| |____| (_) | | | \__ \ (_) | | __/ | |____| | | __/ | | | |_ \_____|\___/|_| |_|___/\___/|_|\___| \_____|_|_|\___|_| |_|\__|

Password for your user:

Running list-alert-recipients with the following parameters:

account : myaccount host : https://hana.ondemand.com recursively : true user : s1234567

Account-level alert recipientsRecipients not set on account level for account myaccount

application : demo1 [email protected] application : demo2 [email protected], [email protected]

Clearing Configured Alert Recipients

clear-alert-recipients

It clears all if e-mails are not specified.

Parameter Value Note

Mandatory

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 569

Page 570: Hana Cloud

Parameter Value Note

--account (-a) account name

--user (-u) SCN user for login to hana.ondemand.com

--host (-h) SAP HANA Cloud host

Optional

--application (-b)

application name

--email (-e) comma separated list of recipient e-mails

Example

neo clear-alert-recipients -a myaccount -b demo -u s1234567 --host hana.ondemand.com

Setting Alert Recipients

set-alert-recipients

Parameter Value Note

Mandatory

--account (-a) account name

--user (-u) SCN user for login to hana.ondemand.com

--host (-h) SAP HANA Cloud host

--email (-e) comma separated list of recipient e-mails

Optional

--application (-b)

application name

--overwrite (-w)

overwrites existing recipients

Example

neo set-alert-recipients -a myaccount -b demo -u s1234567 -e [email protected] --host hana.ondemand.com

570P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 571: Hana Cloud

1.4 Glossary

SAP HANA Cloud Terminology

Term Abbreviation Description

Account A hosted environment provided to a customer organization for the use of one or multiple SAP HANA Cloud based solutions with guaranteed exclusive access and services for managing and operating the solutions.

Application An application running on SAP HANA Cloud, which has a deploy/start/stop/undeploy lifecycle.

Application Runtime Container

Applications developed on SAP HANA Cloud run on a modular and lightweight runtime container which allows them to consume standard Java EE APIs and platform services.

Compute Unit The virtualized hardware resources used by an SAP HANA Cloud application.

Customer account Allows customers to build applications and host them in a production environment for their own purposes. A customer account can be purchased as part of a predefined or tailored package.

Database type A specific database product, such as the SAP HANA database.

Developer account Offers access to the SAP HANA Cloud trial landscape for evaluation purposes. A developer account is free of charge and valid for an unlimited period. It allows restricted use of the platform resources.

Infrastructure as a Service

IaaS A provisioning model in which an organization outsources the equipment used to support operations, including storage, hardware, servers and networking components.

Member Indicates a user’s assignment to an account. As an account member, a user automatically has the permissions required to use the SAP HANA Cloud functionality within the scope of the respective account. A user can be assigned to more than one account.

Partner account Allows partners to build applications and sell them to their customers. A partner account is available through a partner program, which provides a package of predefined resources and the opportunity to certify, advertise, and ultimately sell products.

Platform as a Service PaaS An environment to develop, deploy, run and manage your business applications in the cloud. The underlying software and hardware infrastructure is provided on demand (as a service).

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 571

Page 572: Hana Cloud

Term Abbreviation Description

Quota An account’s entitlement to an allocated resource, such as CPU, memory, database storage, and bandwidth. The resources purchased for an account are available to all applications deployed within that account, within the specified limits.

SAP HANA Cloud Runtime for Java

The components which create the environment for deploying and running applications on SAP HANA Cloud - Java Virtual Machine, Application Runtime Container and Compute Units.

SAP Cloud Connector SAP Cloud Connector serves as the link between on-demand applications in SAP HANA Cloud and existing on-premise systems. It combines an easy setup with a clear configuration of the systems that are exposed to SAP HANA Cloud.

SAP Community Network SCN SAP's professional social network for SAP customers, partners, employees and experts, which offers insight and content about SAP solutions and services in a collaborative environment: http://scn.sap.com. To use SAP HANA Cloud, you have to be registered on SCN.

SAP HANA Cloud SAP HANA Cloud is the Platform-as-a-Service (PaaS) offering from SAP, which enables SAP partners and customers to deploy and use Java applications in a cloud environment.

SAP HANA Cloud cockpit cockpit A central point of entry to key information about your accounts and applications, and for managing all activities associated with your account.

SAP HANA Cloud connectivity service

Provides a secure, reliable and easy-to-consume access to business systems, running either on-premise or in a cloud.

SAP HANA Cloud console client

The SAP HANA Cloud console client enables development, deployment and configuration of a Web application outside the Eclipse IDE as well as continuous integration and automation tasks. The tool is part of the SAP HANA Cloud SDK.

SAP HANA Cloud Developer Center

Developer Center

SAP HANA Cloud Developer Center is the place on the SAP Community Network where you can find information, news, discussions, blogs, and more about SAP HANA Cloud.

SAP HANA Cloud document service

Provides an on-demand repository for applications to manage unstructured content for an application-specific context using the CMIS protocol.

SAP HANA Cloud identity service

SAP ID service The service is responsible for identity management and authorization on SAP HANA Cloud, which you can use in your on-demand applications to ensure proper identity management mechanism.

SAP HANA Cloud persistence service

Provides persistence in a relational database for applications that are hosted on the platform.

572P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved.

SAP HANA Cloud PlatformSAP HANA Cloud

Page 573: Hana Cloud

Term Abbreviation Description

SAP HANA Cloud Software Development Kit

SAP HANA Cloud SDK

The toolset you need to build and run SAP HANA Cloud applications. It contains console clients for deployment and configuration editing; binaries for local testing runtime; javadoc.

SAP UI Development Toolkit for HTML5

SAPUI5 A framework providing UI controls for developing Web applications.

Security Assertion Markup Language

SAML A markup language which provides a wide-spread protocol for secure authentication and SSO. SAML is implemented by SAP ID service.

Single Sign-On SSO A property of access control of multiple related, but independent software systems, which enables a user to log in once and have access to all systems.

Software as a Service SaaS A software distribution model in which applications are hosted by a vendor or service provider and made available to customers over the Internet.

SAP Java Virtual Machine SAP JVM SAP's own implementation of a Java Virtual Machine on which the SAP HANA Cloud infrastructure runs.

Tenant ID tenantId Identifier of the consumer account for the current application context. The tenant ID can be used to distinguish data of different application consumer accounts.

WTP Server Adapter A tool for deploying and testing Java EE assets on SAP HANA Cloud or for local testing.

SAP HANA Cloud PlatformSAP HANA Cloud

P U B L I C© 2013 SAP AG or an SAP affiliate company. All rights reserved. 573

Page 574: Hana Cloud

www.sap.com/contactsap

Material Number: No external material number© 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.