You are on page 1of 78

Web Programming using

SAP UI5
Bogdan MIHAI
Research Scientist, Performance and Insight Optimization
September 30th, October 2nd, 4th, 9th and 11th 2013 Internal
Web Programming using SAP UI5
From zero to hero in just 5 days
Bogdan MIHAI (bogdan-eugen.mihai@sap.com)
Performance and Insight Optimization
September 30th, October 2nd, 4th, 9th and 11th 2013
Agenda – part 1

Day 1 – September 30th


 Introduction
 HTML
 HTTP
 JavaScript

Day 2 – October 2nd


 Quiz
 Introduction
 Internet Architecture
 Internet Communication
 SAP UI5 Overview
 SAP UI5 Programming
 SAP UI5 Controls API

© 2013 SAP AG. All rights reserved. Internal 3


Agenda – part 2

Day 3 – October 4th


 Introduction
 MVC In SAP UI5
 Fragments
 Modularization
 Data Binding
Day 4 – October 9th
 Introduction
 Charts
 Using external JavaScript libraries
 Styling and Theming
 Localization
 Custom Controls
 Security Concepts
 Optimization Concepts
© 2013 SAP AG. All rights reserved. Internal 4
Agenda – part 3

Day 5 – October 11th


 DEMO: Building A Sample Web Application From Scratch
 Final Quiz
 Feedback

© 2013 SAP AG. All rights reserved. Internal 5


Web Programming using
SAP UI5
Day 4 – October 9th
1. Introduction
2. Charts
Overview
The sap.viz.ui5 charting library provides a set of flexible chart controls that
allow to easily represent business data.

CVOM API Reference Demo Snippix Example for line chart


© 2013 SAP AG. All rights reserved. Internal 9
CVOM Chart Types / Part 1

Line Pie Donut Bar

sap.viz.ui5.Line sap.viz.ui5.Pie sap.viz.ui5.Donut sap.viz.ui5.Bar

Column Combination Bubble Scatter

sap.viz.ui5.Column sap.viz.ui5.Combination sap.viz.ui5.Bubble sap.viz.ui5.Scatter

© 2013 SAP AG. All rights reserved. Internal 10


CVOM Chart Types / Part 2 Exercise 24

Stacked Column Stacked Column (%) Dual Bar Dual Line

sap.viz.ui5. sap.viz.ui5. sap.viz.ui5.DualBar sap.viz.ui5.DualLine


StackedColumn StackedColumn100

Dual Combination Dual Column Dual Stacked Column Dual Stacked Column
(%)

sap.viz.ui5. sap.viz.ui5. sap.viz.ui5. sap.viz.ui5.


DualCombination DualColumn DualStackedColumn DualStackedColumn100

© 2013 SAP AG. All rights reserved. Internal 11


Exercise 24 – CVOM Donut Chart

1. Open SNIPPIX in your browser and


load snippet 77042 or your solution
from Exercise 23.
2. Extend the UI5 bootstrap to also load
the CVOM Chart library
• sap.viz

3. Create a dataset after the code for the


OData Table you generated in Exercise 15
• sap.viz.core.FlattenedDataset

4. Set the dimensions, measures and data path:


• Dimensions: axis: 1, name: ‘Name’, value: ‘{CategoryName}’
• Measures: name: ‘Sales’, value: ‘{ProductSales}’
• Data: path: ‘/Product_Sales_for_1997’

5. Set the model on the dataset (same model that is set for the OData Table)
6. Instantiate a CVOM Donut Chart and set the dataset
• sap.viz.core.FlattenedDataset

7. Add the CVOM Chart to the OData Panel

© 2013 SAP AG. All rights reserved. Internal 12


Solution to Exercise 24

Code from the OData Exercise

http://veui5infra.dhcp.wdf.sap.corp:8080/snippix/snippets/43762

© 2013 SAP AG. All rights reserved. Internal 13


3. External JavaScript
Libraries
Inclusion of external JS libraries

If UI5 doesn’t provide controls or behaviors that


other JavaScript libraries offer, these libraries
can be included into the UI5 based pages
Some JS libraries are already included in UI5 and
used by UI5 runtime and can be used without
additional loading, e.g.:
• jQuery, jQuery UI
• dataJS, a Microsoft driven OData library which
handles requests and takes care of creating and
handling requests in JSON and XML format
• D3, an SVG-based graphical library to visualize data
sets

Other libraries need to be loaded separately,


another library of interest is
• Flot, a <canvas>-based jQuery plug-in for displaying
data sets

© 2013 SAP AG. All rights reserved. Internal 15


Inclusion of external JS libraries
To show how to load and use an
external library, we take a look at an
example using Flot

 One can place the script tags for the


library just behind the UI5 bootstrap
script tag in the HTML <head> tag

 the library can be downloaded and


made part of the application project
►For pie chart support you need also the
flot.pie.js plugin

 You can see the pie chart example here

© 2013 SAP AG. All rights reserved. Internal 16


Inclusion of external JS libraries

 Most libraries require a starting // create the HTML control which will be a placeholder
var oHTML = new sap.ui.core.HTML({
point or a placeholder
id: "pieContainer“,
content: "<div id=pieContainer'
 This HTML element can be style=\"height:500px;width: 500px\"></div>"
provided by using the UI5 HTML });
control //starts rendering when the placeholder is rendered
oHTML.attachAfterRendering(

 HTML control’s content is only function(oEvent){


var data = […]; //chart data array
rendered when the page is
$.plot($("#pieContainer"), data, // rendering pie chart
loaded or after an event handler
{ series: {
is finished pie: {
show: true
 The HTML control provides an }
afterRendering event, which }

indicates when the HTML control }

is finished rendering });

© 2013 SAP AG. All rights reserved. Internal 17


Exercise 22 – jQuery flot / Part 1

1. Open SNIPPIX in your browser and


load snippet 37045 or your solution
from Exercise 19.
2. Place these script tags after
the UI5 bootstrap to load flot and flot stack
(hint: include excanvas.min.js if you are
using IE 8 or older)
• <script src='http://www.flotcharts.org/flot/jquery.flot.js'></script>
• <script src='http://www.flotcharts.org/flot/jquery.flot.stack.js'></script>

3. Create a new panel named „Flot Panel“


4. Create two variables with random data
• var aData = [];
for (var i = 0; i <= 10; i += 1)
aData.push([i, Math.random(i)]);

5. Instantiate an HTML control as a placeholder for the chart with a div element as content
and a specific id (“flotContainer”)
• new sap.ui.core.HTML
© 2013 SAP AG. All rights reserved. Internal 18
Exercise 22 – jQuery flot / Part 2

6. Specify a CSS height and width for the div element within the <style> tags
7. Use the AfterRendering event to call the flot chart method
• chartHtml.attachAfterRendering(…)

8. Do the jQuery flot function call in the function attached to afterRendering:


• $.plot($("#flotContainer"), [
{label: "Some data",data: aData},
{label: "Some more data",data: aData2}
],
{
series: {properties for the series}
})

9. Set the stack property for the series to true and show the bars with a width of 0.6

© 2013 SAP AG. All rights reserved. Internal 19


Solution to Exercise 22

http://veui5infra.dhcp.wdf.sap.corp:8080/snippix/snippets/44852

© 2013 SAP AG. All rights reserved. Internal 20


4. Styling and Theming
4. Styling and Theming

• Based on CSS and CSS Parameters


• Generator merges files and appends specific themes to base theme
• Replaces CSS Parameter usages
• Automatic right-to-left generation (For RTL languages like Hebrew)
• One CSS file per control library (library.css)
• SAPUI5 uses LESS to handle the CSS parameters (it also allows calculations,
mixins,...)
• UI5 Framework handles theme switching at runtime (see next slide)

UI5 offers two main options to adjust themes:


1. Adjusting CSS directly with standard tools
2. Changing parameters for the main features of a theme using the Theme
Designer

 See general SAPUI5 Theming Concept


© 2013 SAP AG. All rights reserved. Internal 22
4. Styling and Theming – Switching Themes
Themes can be applied via URL-parameters of via the bootstrap:

OR OR

= =

© 2013 SAP AG. All rights reserved. Internal 23


4. Styling and Theming – The library.css files

© 2013 SAP AG. All rights reserved. Internal 24


4. Styling and Theming – CSS Parameters

• Some values (often: colors) used for different elements


• Parameters: write once, reference often
• Parameters are mixed into the CSS of the controls
• The parameters are usually set in central files
• With the LESS generator the parameter values are inserted and CSS only files are
generated

Example of a color parameter:


@sapUiTextColor: #000000; /* text color is set to 'black' once*/

button {
color: @sapUiTextColor; /* text color can be referenced multiple times*/
[...]
}
h2 {
color: @sapUiTextColor; /* text color can be referenced multiple times*/
[...]
}

© 2013 SAP AG. All rights reserved. Internal 25


4. Styling and Theming – CSS Parameters

Parameter values can be read at runtime with a JavaScript API

• This allows transferring UI5 theme parameters to own HTML parts


• Useful when one uses technology which cannot be influenced by CSS directly,
like Canvas or WebGL

jQuery.sap.require("sap.ui.core.theming.Parameters");

var myColor = sap.ui.core.theming.Parameters.get("sapUiSemanticErrorColor");

© 2013 SAP AG. All rights reserved. Internal 26


4. Styling and Theming – Adjusting Styles

In some cases one needs to adjust only small parts of the theme. There are
two options to style specific elements:

1. One can add <style> or <link> tags in the HTML <head> tag to include new
styles
• These styles are always processed after the UI5 CSS from the themes
• As the last processed CSS wins in case of multiple same CSS rules, the custom CSS always
overwrites the standard UI5 CSS
• The parts to be overwritten can be determined using tools like Firebug in Firefox (or press F12 in all
other browsers)
• It is also important to know that the id given to a control is also the id that the topmost HTML element of
this control gets. Thus, this id can be used as a reference in CSS
• The CSS precedence rules may sometimes lead to the impression that UI5 CSS cannot be overridden.
It needs to be understood that the more specific selector wins.

2. Using the addStyleClass method that every UI5 control has


• One can add a CSS class to the top level HTML element of the UI5 control

USE THESE METHODS WITH CAUTION – MIGHT PRODUCE UNWANTED RESULTS WITH
FUTURE SAPUI5 THEME UPDATES!
© 2013 SAP AG. All rights reserved. Internal 27
4. Styling and Theming – Adjusting Styles

Example of custom
CSS via <style> tag

Example of
addStyleClass method

© 2013 SAP AG. All rights reserved. Internal 28


4. Styling and Theming – Change the Button
Styling
1. Open SNIPPIX in your browser and load
snippet 40861 or your solution from Exercise 15
2. Give an ID to “Submit” Button,
if it doesn’t already have one
3. Add a <style> block
4. Add a CSS rule which assigns new margins to
the element with your ID:
• Top margin: 20px
• Right margin: 0px
• Bottom margin: 20px
• Left margin: 80px
#myId selects a control with the ID „myId“
5. OPTIONAL: Achieve the same effect with the
addStyleClass method

© 2013 SAP AG. All rights reserved. Internal 29


4. Styling and Theming – Change the Button
Styling

id of the button

Alternative solution:

http://veui5infra.dhcp.wdf.sap.corp:8080/snippix/snippets/37045

© 2013 SAP AG. All rights reserved. Internal 30


4. Styling and Theming – The Theme Designer

Parameters can be easily modified using the UI5 Theme Designer

• Easy CSS-free theming/branding as long as mainly colors need to be changed


• Live preview in real applications
• Other SAP UI technologies like Web Dynpro are also covered

© 2013 SAP AG. All rights reserved. Internal 31


4. Styling and Theming – Supported Themes

Themes currently shipped with UI5:


• Blue Crystal (mobile and desktop) – only with sap.m
• Gold Reflection – only with sap.ui.commons, sap.ui.ux3, sap.ui.table, sap.viz
• Mobile Visual Identity (mobile devices only) – only with sap.m
• High Contrast Black – only with sap.ui.commons, sap.ui.ux3, sap.ui.table, sap.viz

Blue Crystal Gold Reflection Mobile Visual Identity High Contrast Black

Demo-Link for Blue Demo-Link for Gold Demo-Link for Mobile Demo-Link for High
Crystal Reflection Visual Identity Contrast Black
Use webkit browser ( switch to “Light Shell” Use webkit browser
such as Google Chrome under: Home > Options such as Google Chrome
to view > Design ) to view
© 2013 SAP AG. All rights reserved. Internal 32
4. Styling and Theming – Theme Designer

1. Open the Theme Designer


in your browser
2. Choose the Gold Reflection
Theme
3. Choose the Shell under
“UI5 Control Previews” -> “UX3
Controls
4. Change the color scheme of the
shell
5. Add some custom css under the
“CSS” tab
6. Rename your theme and export it
as .zip file

© 2013 SAP AG. All rights reserved. Internal 33


4. Styling and Theming – Theme Designer

1. Open the SAPUI5 Developer Studio


and create a new folder „resources"
in the WebContent folder of the
"Training" project
5. Copy the content of your exported
theme .zip file into the “resources”
folder
6. Change the name of the theme in
index.html to your theme name
7. Link the custom.css file to the
index.html

© 2013 SAP AG. All rights reserved. Internal 34


4. Styling and Theming – Theme Designer

1. 2.

3. 4. 5.
Steps in Theme Designer
© 2013 SAP AG. All rights reserved. Internal 35
4. Styling and Theming – Theme Designer

1.

2.

Steps in the Eclipse Project


© 2013 SAP AG. All rights reserved. Internal 36
5. Localization
5. Localization

UI5 has a built-in localization concept, which is aligned to the ResourceBundle


concept in Java

You can get the URL for a resource with this:

var sUrl = sap.ui.resource("sap.ui.table","messagebundle.properties");

Get the resource bundle for a given language (if no locale is given, English is loaded
by default)

jQuery.sap.require("jquery.sap.resources");
var oBundle = jQuery.sap.resources({url : sUrl, locale: sLocale});

And then access the texts in the resource bundle

var sText = oBundle.getText(sKey);

© 2013 SAP AG. All rights reserved. Internal 38


5. Localization

1. Create a new folder "i18n" in the


WebContent folder of the "Training" project

2. Add three empty files to that folder


• i18n.properties
• i18n_de.properties
• i18n_zh.properties

3. Add a property to each i18n-file (one per file)


• MSG_HELLO_WORLD=Hello World!
• MSG_HELLO_WORLD=Hallo Welt!
• MSG_HELLO_WORLD=\u60A8\u597D\u4E16\u754C (ISO-8859-1 encoding!)
4. In createContent, use the resource bundle to init localization
• var oBundle = jQuery.sap.resources({
url : "i18n/i18n.properties",
locale: sap.ui.getCore().getConfiguration().getLanguage() });

5. Change the text property of the Button to make use of localization:


• text: oBundle.getText("MSG_HELLO_WORLD")

6. Test your page with appended URL parameter,


e.g.: ?sap-ui-language=zh

© 2013 SAP AG. All rights reserved. Internal 39


5. Localization

property in the i18n files

shell.view.js

© 2013 SAP AG. All rights reserved. Internal 40


5. Localization

With the ResourceModel, there is a wrapper for resource bundles that exposes the
localized texts as a model for data binding.

A ResourceModel can be instantiated with a bundleName or a bundleUrl which


points to a resource bundle. When using the bundle name the file must have the
.properties suffix.

Example:
var oModel = new sap.ui.model.resource.ResourceModel({
bundleUrl: "myBundle.properties", // will use myBundle_en.properties
bundleLocale: "en“ // optional, default is current language, so better omit it
});
var oControl = new sap.ui.commons.Button({
id : "myButton",
text : "{i18n>MY_BUTTON_TEXT}“ // this points to a named model
});
// attach the resource model with the symbolic name "i18n"
sap.ui.getCore().setModel(oModel, "i18n");

© 2013 SAP AG. All rights reserved. Internal 41


5. Localization
1. Within the controller of the XMLView
implement/uncomment the onInit method

2. Create a
• new sap.ui.model.resource.ResourceModel
with
• bundleUrl: "i18n/i18n.properties"
(the current language is automatically used)

3. Set this ResourceModel as model


on the View or (globally) on the Core, but set it as named model (name: “i18n”)
• ….setModel(oModel, "i18n");

4. Now use data binding to bind the translated text to the Button in the XMLView
5. Binding expression is: "{i18n>MSG_HELLO_WORLD}"

© 2013 SAP AG. All rights reserved. Internal 42


5. Localization

xml.view.xml

xml.controller.js

© 2013 SAP AG. All rights reserved. Internal 43


6. Custom Controls
What Is A Control?

A Control is an object that defines the appearance and behavior of a screen


area.
 A Control typically has properties like "text" or "width" that modify the appearance or relate to
the data displayed by the Control.

 It can aggregate other Controls. This means it is a sort of container or layout Control when
the application can add the child controls to use - or a composite Control if the Control itself
decides what the child Controls are and just re-uses these available components.

 It 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. Typically, these have a meaning that relates to the
Control's purpose and functionality and is on a semantically higher level than "click" or other
browser events. Examples would be triggerSearch in a SearchField or collapse in a Panel.

© 2013 SAP AG. All rights reserved. Internal 45


Overview

There are two approaches to develop UI5 Controls, either with tool support,
or just as part of a plain JS file. This section deals with creating custom
controls in JavaScript with the extend method.

Since an IDE is not needed to create new controls with the extend method
these controls have been named "Notepad Controls".

Technically, this functionality is not restricted to Controls. Arbitrary objects


derived from sap.ui.base.Object can be created or extended.

Snippix-Example "New Control in 19 Seconds"

© 2013 SAP AG. All rights reserved. Internal 46


The extend Method

The extend() method is available on all Controls (and the base classes)
and is used to define a new subclass.
Creating a new control:
• sap.ui.core.Control.extend(sName, oDefinition);
Creating a new Control which inherits from Button:
• sap.ui.commons.Button.extend(sName, oDefinition);
The parameters to this function are the name and the definition of the new control
type. The definition part contains information about the control API, which
properties, aggregations, events, etc. the control has and the implementation of the
control methods.
Some methods such as the getters and setters for the properties and aggregations
or the methods for attaching/detaching event handlers are automatically created by
UI5.

© 2013 SAP AG. All rights reserved. Internal 47


Control Definition

The definition object for a custom control may contain metadata, public and private
methods, event handler and the renderer.

© 2013 SAP AG. All rights reserved. Internal 48


Basic Example

http://veui5infra.dhcp.wdf.sap.corp:8080/snippix/snippets/3357
© 2013 SAP AG. All rights reserved. Internal 49
Control Metadata

The metadata in the control definition consists of objects for the control
properties, events and aggregations.

Properties Example

type: The data type of the Control properties: {


property. title: "string",
btnTxt: { defaultValue: "Search"},
• string for a string property (default)
showLogoutButton: {
• int or float for number properties type: "boolean",
• int[] for an array of integers, defaultValue: true
string[] for an array of strings, etc. },
• sap.ui.core.CSSSize for a custom- width: {
defined type type: "sap.ui.core.CSSSize",
defaultValue: "50px"
defaultValue: The default value of }
the property. (undefined if not set) }

© 2013 SAP AG. All rights reserved. Internal 50


Control Metadata
Events Aggregations

Events are specified by the event Aggregations and associations are


name only. In many cases there is defined by their name, along with an
nothing to configure about them, so object that can have a type, a
just give an empty object. multiple flag and a singularName.

Controls can enable events to be aggregations: {


interrupted by the application, using acceptButton:
the enablePreventDefault flag. "sap.ui.commons.Button",
worksetItems: {
events: { type:
logout: {}, "sap.ui.ux3.NavigationItem",
close: { multiple: true,
enablePreventDefault : true singularName : "worksetItem"
} }
} }

© 2013 SAP AG. All rights reserved. Internal 51


Control Methods

After the metadata is defined, you can add any method implementations to your
new Control. The method names can be chosen freely, some method names must
be avoided though:
• Names of methods that are provided by a super class.
• Methods starting with set, get, insert, add, remove or indexOf may collide with
setters/getters for properties or aggregations you defined.
• Methods starting with attach, detach or fire may collide with methods created for
events.

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: The name of the function that creates the HTML for the control.

© 2013 SAP AG. All rights reserved. Internal 52


Control Methods
Public / private methods
The convention is that private methods start with an underscore. All other methods
are considered public.

init Method
The init() method is invoked by the UI5 core for each control instance right after
the constructor. Use this to set up things like internal variables or sub-controls of a
composite. This method is considered private and only to be called by the UI5 core.

onAfterRendering Method
The onAfterRendering() method is invoked after the controller's View is
re-rendered.

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 UI5 core.

© 2013 SAP AG. All rights reserved. Internal 53


Control Methods - Examples

// public method // init method, invoked when control


divide: function(x, y) { // is instantiated
if (this._checkForZero(y)) { init: function() {
throw new Error("Second this._bSearchTriggered = false;
parameter may not be zero"); this._oSearchBtn =
} new sap.ui.commons.Button(
return x / y; this.getId() + "-searchBtn",
}, { text: "Search" }
);
// private method },
_checkForZero: function(y) {
if (y === 0) { // event handler
return true; onclick: function(e) {
} alert("Control " + this.getId()
return false; + " was clicked.");
}, }

© 2013 SAP AG. All rights reserved. Internal 54


Control Renderer
Example:
The renderer method is renderer: function(oRm, oCtrl) {
responsible for creating the HTML oRm.write("<div");
structure that makes up the oRm.writeControlData(oCtrl);
control. It is different from the oRm.addStyle("width", oCtrl.getSize());
other methods, as it is a static oRm.writeStyles();
one, so the this keyword is not oRm.addClass("myClass");
oRm.writeClasses();
available. Instead, a control
oRm.write(">");
instance and a RenderManager oRm.writeEscaped(oCtrl.getText());
instance are given to the method. oRm.write("</div>");
}

Using an existing renderer:


If an existing renderer should be
used without modification, you renderer: "sap.ui.commons.ButtonRenderer"
can give the name of this
renderer class.
© 2013 SAP AG. All rights reserved. Internal 55
Example with Data Binding

http://veui5infra.dhcp.wdf.sap.corp:8080/snippix/snippets/64805
© 2013 SAP AG. All rights reserved. Internal 56
Example with Charts

http://veui5infra.dhcp.wdf.sap.corp:8080/snippix/snippets/42676
© 2013 SAP AG. All rights reserved. Internal 57
Exercise – Notepad Controls

Add an Audioplayer Control to your


Exercise 16
Music store from Exercise 14 and
have the selected song play

© 2013 SAP AG. All rights reserved. Internal 58


Exercise 16 – Notepad Control / Part 1

1. Open the SAPUI5 Developer Studio and go to the file „musicstore.view.js“ in the „training“
folder

2. Implement a new „AudioPlayer“ control before oTable:


sap.ui.core.Control.extend("AudioPlayer",{
metadata:{
properties:{ src:"string" }
},
setSrc: function(sValue){
this.setProperty("src", sValue);
},
renderer:function(oRm, oControl){
oRm.write("<audio controls='controls' ");
oRm.writeControlData(oControl);
oRm.write(">");
oRm.write("<source src='" + oControl.getSrc() + "'
type='audio/mpeg'>");
oRm.write("</audio>");
}
});

© 2013 SAP AG. All rights reserved. Internal 59


Exercise 16 – Notepad Control / Part 2

3. Add a new column to the table and instantiate the new „Audioplayer“ control as row content:

oTable.addColumn(new sap.ui.table.Column({
label : new sap.ui.commons.Label({
text : "Listen"
}),
template : new AudioPlayer("audioPlayer",{
src : "{previewUrl}"
})
}));

4. Open the index.html in browser that can interpret the <audio> tag
(Chrome 6 and newer, Firefox 3.6 and newer, Safari 5.0 and newer, IE 9 and newer)

The complete View code is available here:


http://veui5infra.dhcp.wdf.sap.corp:8080/snippix/snippets/78902

© 2013 SAP AG. All rights reserved. Internal 60


Solution for Exercise 16
When a song is selected in the Table, it can be played now.

NOTE: Firefox may not support the used audio codec.

© 2013 SAP AG. All rights reserved. Internal 61


7. Security Concepts
Before You Start

Fundamental Security Guides


 Secure Programming Guide
– https://wiki.wdf.sap.corp/wiki/display/PSSEC/Secure+Programming+Guide
 XSS Secure Programming Guide
– https://wiki.wdf.sap.corp/wiki/display/NWCUIAMSIM/XSS+Secure+Programming+Guide
 JPaaS Secure Programming Guide
– https://wiki.wdf.sap.corp/wiki/display/JPaaS/Secure+Programming+Guide+for+JPaaS

Additional Information
 Security - http://sdn.sap.com/irj/sdn/security
 Security Guides - http://service.sap.com/securityguide
 Related SAP Notes - http://service.sap.com/notes http://service.sap.com/securitynotes
 Released Platforms - http://service.sap.com/pam
 Network Security - http://service.sap.com/securityguide
 SAP Solution Manager - http://service.sap.com/solutionmanager
 SAP NetWeaver - http://sdn.sap.com/irj/sdn/netweaver

© 2013 SAP AG. All rights reserved. Internal 63


Architectural Overview

© 2013 SAP AG. All rights reserved. Internal 64


Data Protection And Privacy

SAPUI5 does not store or provide access to any user-related data.


 If an application built with SAPUI5 deals with user-related data, it has to take care of the
data protection rules of the target countries of the application.

 This includes usage of proper authentication, authorization and encryption (e.g. SSO and
usage of https), as well properly securing and logging access to person-related data.

 For more information regarding data protection and privacy, please see the security guide of
your server side framework.

 SAPUI5 doesn't provide any authorization or user management. An application which


implements such facilities based on SAPUI5 has to make sure that SSL is enabled to
prevent clear text passwords sent over the wire. Applications must not store any logon
information on the client.

© 2013 SAP AG. All rights reserved. Internal 65


Browser Security – Cross-Site-Scripting

 The most prominent security issue of web applications within the last years and also the musts dangerous
one.

 Once malicious code is running within your browser, it can be used to steal your session cookies, to
trigger requests within the current session, or even to exploit a known browser vulnerability to do native
code execution.

 For SAPUI5 applications XSS vulnerabilities can exist on different levels:


– Within the HTML page or custom data transports sent to the browser from the server

– Within the JavaScript Code of the application, which is processing server responses

– Within the JavaScript Code of the application, which is processing server responses

 SAPUI5 can only prevent cross site scripting in the processing and rendering of controls. For that purpose
there is input validation on all typed Element properties and output encoding done in the renderer class of
Controls
– There are exceptions to this, for controls which are especially built to include arbitrary HTML (like sap.ui.core.HTML).

 Application is responsible for proper output encoding of all content embedded into the HTML page itself,
as well as for encoding of JSON or XML data sent to the client and secure processing of this data.

© 2013 SAP AG. All rights reserved. Internal 66


Browser Security – HTML5 Features

 Local Storage API


– This API can be used to store a limited amount of data on the browser.

– Access to this data is limited to JavaScript code running from the same domain as it has been stored.

– SAPUI5 offers helper functions to access the local storage on different browsers.

– By default SAPUI5 is not using the local storage, but it can be enabled for the history-capabilities.

 WebGL
– WEBGL allows accessing the graphics API of the computer on a very low level, which may lead to low
level exploits.

– This is the main reason Internet Explorer has no support for WebGL at all, Microsoft recently stated,
that they are not going to support WebGL as they think it can not be implemented in a secure way.

– SAPUI5 is currently not using WEBGL.

© 2013 SAP AG. All rights reserved. Internal 67


Browser Security – HTML5 Features

 WebSockets
– WebSockets offer great new possibilities for the client/server communication of web applications

– There have been many security issues rising while the first implementations were done by the browser
vendors

– SAPUI5 is currently not using WebSockets.

 postMessage and onMessage


– postMessage allows inter-window-communication between windows from different domains

– As soon you are subscribing to the onMessage event, you can receive messages from any other
browser window.

– This can lead to massive security issues.

– SAPUI5 is utilizing postMessage for its debugging and tracing functionality.

© 2013 SAP AG. All rights reserved. Internal 68


Transport Security

 The best security on the client and server doesn't help, if the data transport between client and server can
be read, intercepted or even modified by an attacker.
– HTTP communication is stateless and unencrypted

 Encryption
– Sending the HTTP protocol over a SSL secured connection is not only standardized, but also required for SAP
applications.

– SAPUI5 fully supports usage of HTTPS, but there are some restrictions regarding the CDN version of SAPUI5 when
HTTPS is used.

o It is recommended to enable or at least to test SSL connections in an early stage of application development, as
usually switching to HTTPS causing some issues

 Session Security
– Even if the data transport is secured using SSL, there are possibilities to hijack such a secure connection and sending
malicious requests from the client (Cross site request forgery - XSFR, and session fixation)

o SAPUI5 does only provide XSRF prevention for the data which is sent to the server by SAPUI5.

o This only happens in the OData Model, where a XSRF token is read from the server and used for subsequent write
requests.

o Application is responsible for using XSRF header or other mechanisms to prevent XSRF attacks
© 2013 SAP AG. All rights reserved. Internal 69
Input Validation

• Application point of view: Input validation of user input, must be done on the
server, optional on the client, can be achieved using two way data binding and
model types
• oInput.bindValue("/path", new sap.ui.model.type.Float())

Ensures only a Float value can be entered, otherwise a ParseError will be thrown
• oInput.bindValue("/path", new sap.ui.model.type.String({}, {maxLength: 20}))

Ensures that maximal 20 characters can be entered, otherwise a ValidationError will be


thrown

• Control point of view: Input validation of control properties, so integer


properties only accept integers, enumeration properties only accept an existing
enumeration value.

• While this sounds obvious, in JavaScript it is not 

© 2013 SAP AG. All rights reserved. Internal 70


Output Validation

• All data sent from the server must be properly output encoded according to the
context they are contained in

• When developing custom controls, the following two methods should be used
within the control renderer for HTML encoding:
• RenderManager.writeEscaped(sString)

Encodes the given string and writes it to the HTML output as content
• RenderManager.writeAttributeEscaped(sString, sString)

Encodes the given string and writes it to the HTML output as an attribute
• jQuery.sap.encodeCSS / encodeHTML / encodeJS / encodeURL / encodeXML

Encode the string for inclusion into CSS string / HTML Content / JS String / URL Parameter /
XML content literals or identifiers

© 2013 SAP AG. All rights reserved. Internal 71


8. Optimization Concepts
Modularization in Development Mode

If Modules are configured, our server side component instructs the browser to use a
ModifiedSince approach for detecting resource changes. This allows caching of the
content, but still requires the same number of requests as the unlaced mode
Modularization and Caching together form our development mode: you can modify
a small file and – ideally – the browser has to reload only that module. We do not
only use this internally for development, but also for our central installations. So
whenever we update our central installation (usually several times a day), the
browser should detect changes and reload the files.

© 2013 SAP AG. All rights reserved. Internal 73


Minimized JavaScript Files

Minimization means that unnecessary characters like whitespace, line breaks and
comments are removed from the source code. This considerably reduces the file
size.
During nightly build, we produce optimized versions of our libraries. These include
minimized versions of our JavaScript files, the CSS files are not minimized.
So instead of installing
 sapui5.war, one can install sapui5-opt.war.
 sapui5-light.zip, one can install sapui5-opt-light.zip
The ‘opt’ version currently can be found in the Nexus repository only, it is not
deployed to our central VMWare machines.
“opt” additionally contains the non-minimized debug version of all files. In the Ctrl-
Alt-Shift-P Dialog you can toggle the debug mode.

© 2013 SAP AG. All rights reserved. Internal 74


Reducing the number of JavaScript files

sap-ui-core.js
• loads library.js file for each used library.
• loads control behavior and rendering
files when control is instantiated.
 only needed code is loaded
 many requests

sap-ui-core-all.js sap-ui-core.js: 99 requests, 1,06 MB, 831ms


• loads the complete library, including the
code for all controls
 less requests
 bigger file size, all code is parsed

 In
the „opt“ mode, both advantages are
combined: one request per library, but
every module/control is only parsed
when required (with sap-ui-core.js) sap-ui-core-all.js: 18 requests, 1,54 MB, 439ms

© 2013 SAP AG. All rights reserved. Internal 75


UI5 Download Configurator Tool

The download tool creates merged js Usage:


files with all desired modules.  Load your application page and navigate
through it (, to load all used modules)
You can mix such a merged file with the
 Press CTRL-ALT-SHIFT-P
dynamic on-demand approach: load a (UI5 Technical Info)
big file with the most common modules  Expand the list of loaded modules, select
and let UI5 load the others on demand. and copy it
Please be aware, that the above tool link  Start the merge tool
creates the download configuration for  Paste your module list into the empty white
the nightly build. text area on the right hand side
 Download and Save the custom modules
 Package the custom module into your
application and load it in your page instead
of the sap-ui-core.js

http://veui5infra.dhcp.wdf.sap.corp:8080/sapui5-internal/download/

© 2013 SAP AG. All rights reserved. Internal 76


Configurable Caching

With some configuration either in the web.xml or the server configuration, our
resource handler can be configured to use a different caching strategy (e.g. time-to-
life). This avoids the ModifiedSince requests.

The central UI5 installations are double-configuration installations. When accessed


via port 8080, they use the development mode, but when accessed via port 8090,
they use the caching-mode.

When one doesn’t want to use the ModifiedSince requests, but still wants the
convenience of up-to-date checks, it is best practice to include some version-
specific into the requests URLs (cache buster). Our resource handler provides such
a unique id and also provides a way to automatically convert a static URL request
into a request with that ID.

Load resources/sap-ui-cachebuster/sap-ui-core.js instead of


resources/sap-ui-core.js to trigger this behavior.

© 2013 SAP AG. All rights reserved. Internal 77


Thank you

Contact information:

Bogdan MIHAI
Research Scientist, Performance and Insight Optimization
bogdan-eugen.mihai@sap.com
+40 745 394 340

You might also like