Consume NetWeaver Gateway services via SAPUI5 – Part 1
At SAP Inside Track Milan 2012 I presented in a 6 minutes session (unfortuntely my friend, colleague and co-speaker Fabio Di Micco was unable to present) how you can easily consume NetWeaver Gateway services using SAPUI5 library, in this blog I will resume the concept and the code and share it with the SCN community.
Prerequisite
- SAPUI 5 library (Download here)
- Eclipse IDE for J2EE Developers, I’m using Juno (Download here)
- SAPUI5 Eclipse plugin installed
- HTTP Web Server installed (I’m using Tomcat in this example)
- Basic knowledge of NetWeaver Gateway
Backend – Gateway service
Gateway service can be easily created on you ABAP Gateway system, but to speed up the presentation I used one of the demo services provided by SAP on ES Workplace (available here) and in particular the classical Flight Sample.
Frontend – SAPUI5
Create a new SAPUI5 project in Eclipse and name it “SITMIL” and check “Create an Initial view”, in the next screen name the view “retrieveFlight”
you should have a project structure like below. This looks like a classical MVC structure.
Now we should start coding.
index.html
First of all we need to create the container of our application.
Edit the index.html file an paste this code:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="./resources/sap-ui-core.js" type="text/javascript"
id="sap-ui-bootstrap"
data-sap-ui-libs="sap.ui.ux3, sap.ui.commons, sap.ui.table"
data-sap-ui-theme="sap_goldreflection">
</script>
<script type="text/javascript">
// Create a SAP UI5 shell element
var oShell = new sap.ui.ux3.Shell("flightAppShell", {
appIcon : "http://www.sap.com/global/images/SAPLogo.gif",
appTitle : "Flight manager", });
// Just take the shell and place it in the html area called shellArea
oShell.placeAt("shellArea");
sap.ui.localResources("sitmil");
var view = sap.ui.view({
id : "idFlightService1",
viewName : "sitmil.retrieveFlight",
type : sap.ui.core.mvc.ViewType.JS });
oShell.addContent(view);
</script>
</head>
<body class="sapUiBody" role="application">
<div id="shellArea"></div>
</body>
</html>
Now let’s try to explain the code and understand what we are doing.
First step is to import sapui5 libraries used in this demo
<script src="./resources/sap-ui-core.js" type="text/javascript" id="sap-ui-bootstrap"
data-sap-ui-libs="sap.ui.ux3, sap.ui.commons, sap.ui.table"
data-sap-ui-theme="sap_goldreflection">
</script>
Then we initialize the Shell element, that creates a nice look & feel to our page, and we attach it in block element <div id=”shellArea”>. The shell will be our main container.
// Create a SAP UI5 shell element
var oShell = new sap.ui.ux3.Shell("flightAppShell", {
appIcon : "http://www.sap.com/global/images/SAPLogo.gif",
appTitle : "Flight manager", });
// Just take the shell and place it in the html area called shellArea
oShell.placeAt("shellArea");
As said, the shell will be our main container, what we finally need is to instantiate the main view content and attach it to the shell
sap.ui.localResources("sitmil");
var view = sap.ui.view({
id : "idFlightService1",
viewName : "sitmil.retrieveFlight",
type : sap.ui.core.mvc.ViewType.JS });
oShell.addContent(view);
retrieveFlight.view.js
SAPUI5 plugin automatically creates the main view JS class with two methods
sap.ui.jsview("sitmil.retrieveFlight", {
getControllerName : function() {
return "sitmil.retrieveFlight";
},
createContent : function(oController) {
}
});
what we need it is to implement the createContent method, in this method we will create our user interface.
var layout = new sap.ui.commons.layout.MatrixLayout('layout');
layout.setWidth('80%');
var rPannel = new sap.ui.commons.Panel('rPannel');
var rTitle = new sap.ui.commons.Title('rTitle');
rTitle.setText('All - Flights');
rPannel.setTitle(rTitle);
var oTable = new sap.ui.table.DataTable();
oTable.addColumn(
new sap.ui.table.Column({
label: new sap.ui.commons.Label({text: "AirLine"}),
template: new sap.ui.commons.TextField().bindProperty("value", "AirLineID"),
sortProperty: "AirLineID"
}));
oTable.addColumn(
new sap.ui.table.Column({
label: new sap.ui.commons.Label({text: "Flight Number"}),
template: new sap.ui.commons.TextField().bindProperty("value", "FlightConnectionID"),
sortProperty: "FlightConnectionID"
}));
oTable.addColumn(
new sap.ui.table.Column({
label: new sap.ui.commons.Label({text: "Date"}),
template: new sap.ui.commons.TextField().bindProperty("value", "FlightDate"),
sortProperty: "FlightDate"
}));
oTable.addColumn(
new sap.ui.table.Column({
label: new sap.ui.commons.Label({text: "Airfare"}),
template: new sap.ui.commons.TextField().bindProperty("value", "AirFare"),
sortProperty: "AirFare"
}));
oTable.addColumn(
new sap.ui.table.Column({
label: new sap.ui.commons.Label({text: "Airline Currency"}),
template: new sap.ui.commons.TextField().bindProperty("value", "LocalCurrencyCode"),
sortProperty: "LocalCurrencyCode"
}));
oTable.addColumn(
new sap.ui.table.Column({
label: new sap.ui.commons.Label({text: "Type of the plane"}),
template: new sap.ui.commons.TextField().bindProperty("value", "AirCraftType"),
sortProperty: "AirCraftType"
}));
var oModel = new sap.ui.model.odata.ODataModel(
"http://gw.esworkplace.sap.com/sap/opu/odata/IWBEP/RMTSAMPLEFLIGHT_2",
false,
"GW@ESW",
"ESW4GW");
oTable.setModel(oModel);
oTable.bindRows("FlightCollection");
rPannel.addContent(oTable);
layout.createRow(rPannel);
this.addContent(layout);
}
As did before let’s try to understand our code.
First of all we create a matrix layout, a panel ( something like the tray bar in WDA just to make it clear 🙂 ) and we associate a panel title, this panel will contain the table list of all the fights exposed by our Gateway service
var layout = new sap.ui.commons.layout.MatrixLayout('layout');
layout.setWidth('80%');
var rPannel = new sap.ui.commons.Panel('rPannel');
var rTitle = new sap.ui.commons.Title('rTitle');
rTitle.setText('All - Flights');
rPannel.setTitle(rTitle);
Next step we configure our table layout, it remembers me the WDINIT method in WDA and the ALV configuration. For each column we need to specify the field name of the collection property (FlightCollection in the gateway service, see metadata of our Gateway service for more details) that we want to bind and display in that column
var oTable = new sap.ui.table.DataTable();
oTable.addColumn(
new sap.ui.table.Column({
label: new sap.ui.commons.Label({text: "AirLine"}),
template: new sap.ui.commons.TextField().bindProperty("value", "AirLineID"),
sortProperty: "AirLineID"
}));
oTable.addColumn(
new sap.ui.table.Column({
label: new sap.ui.commons.Label({text: "Flight Number"}),
template: new sap.ui.commons.TextField().bindProperty("value", "FlightConnectionID"),
sortProperty: "FlightConnectionID"
}));
oTable.addColumn(
new sap.ui.table.Column({
label: new sap.ui.commons.Label({text: "Date"}),
template: new sap.ui.commons.TextField().bindProperty("value", "FlightDate"),
sortProperty: "FlightDate"
}));
oTable.addColumn(
new sap.ui.table.Column({
label: new sap.ui.commons.Label({text: "Airfare"}),
template: new sap.ui.commons.TextField().bindProperty("value", "AirFare"),
sortProperty: "AirFare"
}));
oTable.addColumn(
new sap.ui.table.Column({
label: new sap.ui.commons.Label({text: "Airline Currency"}),
template: new sap.ui.commons.TextField().bindProperty("value", "LocalCurrencyCode"),
sortProperty: "LocalCurrencyCode"
}));
oTable.addColumn(
new sap.ui.table.Column({
label: new sap.ui.commons.Label({text: "Type of the plane"}),
template: new sap.ui.commons.TextField().bindProperty("value", "AirCraftType"),
sortProperty: "AirCraftType"
}));
We need to attach our layout (yes we draw the layout until this point) to our oData service. Here it comes the power of SAPUI5 library, with only 3 lines of code we are able to consume an oData resource and bind a collection to our table; each row of our table will be an entity of the FlighCollection
var oModel = new sap.ui.model.odata.ODataModel(
"http://gw.esworkplace.sap.com/sap/opu/odata/IWBEP/RMTSAMPLEFLIGHT_2",
false,
"GW@ESW",
"ESW4GW");
oTable.setModel(oModel);
oTable.bindRows("FlightCollection");
We are almost done, we only need to attach our table to the panel
rPannel.addContent(oTable);
layout.createRow(rPannel);
this.addContent(layout);
Deploy and Execute
Final step is to export the WAR file into Tomcat webapps directory. You can also deploy it on your preferred HTTP web server, for example I also deployed a live demo on my Apache HTTP server.
Warning: You have to accept Cross Origin Request on you browser, otherwise you will see empty tables 🙂
In part 2 we enhance this demo focusing on navigation property. In the meantime, below the recording of my session at SAP Inside Track Milan 2012.
Hi Ivan.
How can we solve this issue?
"Accept Cross Origin Request on you browser, otherwise you will see empty tables"
In Chrome i've tried cmd.exe--> chrome.exe --disable-web-security
but stills the page is blank.
Thanks in advance
Hi Raul,
on Mac bash I'm using
open -b com.google.chrome --args --disable-web-security
maybe you missed --args.
Let me know,
Ivan
Hi again.
1. I opened cmd.exe in admin mode.
2. I've redirect my explorer to folder C:\Users\usuario\AppData\Local\Google\Chrome\Application> which is placed chrome.exe
3. Type chrome.exe --args --disable-web-security
4. I keep the user and pass of your Gateway sample.
5. Page is still blank.
Maybe there are somre restrictions to access services from Gateway server in my country (Peru). Is that possible?
Hi,
it sounds strange... I don't think it is a restriction.
Could you please open the developer console -> Javascript Error and post the result?
Could you try also with firefox?
Just tried on my browser without any issue...
BR,
Ivan
Hi Ivan.
this is the sent message from SAP Gateway Server.
Anmeldung fehlgeschlagen
Was ist passiert ?
Der Aufruf der URL http://gw.esworkplace.sap.com:55080/sap/opu/odata/IWBEP/RMTSAMPLEFLIGHT_2/$metadata wurde aufgrund fehlerhafter Anmeldedaten abgebrochen.
Was k�nnen Sie tun ?
Fehlercode: ICF-LE-http-c:800-l:-T:1-C:5-U:5-P:5-L:6-X:0050568F02DD1ED285E21F23FBF788CE_0050568F02DD1ED285E21F56597DA8CE_1-x:F91017E2DF1FF1C188CE0050568F02DD
HTTP 401 - Unauthorized
Ihr SAP Internet Communication Framework Team
This is the error for no Access-Control-Allow-Origin
Strange that your Chrome is not working, here they suggest to kill all instances of Chrome. Did you?
Did you try to use another browser like Firefox?
Hi Ivan.
Finally I solved with a simple prefix.
In fact there are two kind of solutions.
1. By adding "Allow-Origin..." tag into the jScript file. But sometime it is not compatible with other browsers (Chrome or Firefox)
2. The best -and it was mentioned in SAPUI5 documentation- is adding a prefix into the Gateway Service URL. But this solution is applied to any project deployed and tested in a local server (like my case, I'm on my Tomcat Server with Eclipse EE and playing a bit this your code 🙂 )
So, by replacing this line
with this
that Access-Control-Allow-Origin is over.
Thank you for your attention.
hi Raul Romero,
I have same problem with u.
I tried your solution u talked about by adding a prefix into the Gateway Service URL.
But ,it is still blank table.
So have u done other things to make it work?
Or please give detail code info of first solution.
Thank u very much if u could offer help.
Hi Lisa.
I suggest you to open a new post outside this Ivan Fermia's page in order to preserve the purposes of this article.
In your new post you will publish, please paste your code. And explain us each step you follow. I need some input from you.
1. Did you use the Eclipse plugin for SAPUI5?
2. Did you have your Apache Tomcat Server installed?
3. Show us your code (copy+paste). My code is the same as Ivan, but with the change I've mentioned before.
Thank you. I hope to see your post.
I am suffering with the same problem even though I tried all the suggestions in this post.
My code is the same as Ivan. Changed to proxy and everything else, but not working.
I am getting an empty shell with message "No Data". Any other useful suggestions?
I tried proxy option which does override cross origin but throws up internal server error on safari and
500 (Only allowed for local testing!) on chrome.
the first option mentioned , where exactly do you put allow access origin ?? i am making my request in JS view on click of a button.
we are getting an error like this on safari browser
Origin http://localhost:53770 is not allowed by Access-Control-Allow-Origin.
Refused to get unsafe header "Content-Length".
It works fine in google chrome .
Beware of a change in the rows data binding since version 1.6 of SAPUI5. The example described in this blog works perfectly on SAPUI5 1.4.x, but from version 1.6 onwards you need to change the following code:
with this one:
(mind the leading slash)
This may be another reason why you see an empty data table.
Actually, it is not code problem but network region problem. It works fine if I build it on my own gateway service.
Hi ,
We were successfull in creating desktop app project and run it on localhost.
we want to create mobile app project ,how can we go about this .
Also desktop app that we created , will run only on my local server ? what if i want to run the same on device browser/ any other local server .
Does UI5 support mobile application project development .Please help us on this.All tutorials are targeting desktop app project .Plugin does give two options :-
1 . Desktop App
2. Mobile App
Thanks ,
Amit Nalawade .
Hi,
latest version of SAPUI5 1.8.x allows you to create also mobile enabled applications.
Ivan
Even i can see that option , but how do we create it and run it in browser in form of a simulator ?
There is no proper tutorial i could find on it .
Maybe you can play with PhoneGap, a framework for Android, Blackberry and IPhone devices. Taste it!
Hi Amit,
Have you succeeded in consuming SAP NW gateway services in SAPUI5 mobile application? If yes, please post the code how to display values from gateway to SAPUI5 mobile.
Regards
Sateesh
There are two ways of doing that :-
1. SAP UI 5 Approach ( as per their docs )
var serviceoData = "service url pointing to consumption model of gateway service";
var oModeloData = new sap.ui.model.odata.ODataModel(serviceoData,true,"username gateway", "password gateway");
// setting inputs via filters
var ofilter1 = new sap.ui.model.Filter("crtd_on_from", sap.ui.model.FilterOperator.EQ,"2012/03/21");
var ofilter2 = new sap.ui.model.Filter("crtd_on_to", sap.ui.model.FilterOperator.EQ,"2013/08/21");
List.setModel(oModeloData);
List.bindAggregation("items", "/collection name which has values", oItemTemplateDisplay,null,[ofilter1,ofilter2]);
While creating template :
var oItemTemplate = new sap.m.DisplayListItem({
label : "{value to be displayed}"
});
2. Using Standard oData methods
var oModel = new sap.ui.model.odata.ODataModel(
"service url pointing to consumption model of gateway service",
false,
"uname gtway",
"pass gtway");
OData.read(" url with params included",sucessfn,errorfn);
Hope this helps.
Hi,
The example you have given is for Query operation.
Can you tell me how to do a create operation.
I have created the Model in SEGW transaction with all the CRUDQ operations.
Now from UI5 i am unable to pass the operation type , CSRF token.
Hi,
I have implemented this blog but I am seeing a blank table without any data as output. As suggested by Raul Romero & Kaloyan Raev in the comments, I have replaced the line
with
and also I am prefixing a slash in the line oTable.bindRows("/FlightCollection");
but still I am not getting any data in the table when I am running this application. Any ideas what may be the reason for this?
Regards,
Saurabh
Hi.
1. Did you put all the parameters I mean: user, password?
2. Keep in touch about case sensitive: maybe you have a variable renamed with different names.
Hi Raul,
Thank you so much for your response.
1. Yes, I am passing the user and password in the same line where I am creating the model, like mentioned below:
var oModel=new sap.ui.model.odata.ODataModel("proxy/http://gw.esworkplace.sap.com/sap/opu/odata/IWBEP/RMTSAMPLEFLIGHT_2",
false,
"GW@ESW", "ESW4GW");
2. I double-checked if I had mistakenly spelled any variables (case sensitivity wise) but I did not find it so.
What else should I be checking for getting the data in my table UI?
Warm Regards,
Saurabh
Hi,
I have tried running the application in IE8 and Firefox 18. In both the browsers I am seeing the same output - a blank table with no data, also no Javascript errors are reported in either the Error Console on Firefox or IE8.
Since we are not yet having an AS ABAP system with the SAP NetWeaver Gateway installed, I am trying to use this blog to fetch data from the demo services provided by SAP on ES Workplace.
Warm Regards,
Saurabh
Hi,
I removed the proxy/ from the URL and had just this -
Also I enabled cross origin requests in IE8. This worked for me and I am able to get the data.
Regards,
Saurabh
Hi all,
I had the similar problem..but "/FlightCollection" solved it. Thank you.
The fact that YOUR example does not work on YOUR server
http://www.plinky.it/abap/SITMIL2/index_part1.html
is a major fail and does not inspire confidence.
Peter,
at that time I didn't use the "proxy/" trick, because it was not the scope of the example. "Cross Origin Request" limitation is a client side block of your browser.
Example on Chrome on Mac just do it from shell
open -b com.google.chrome --args --disable-web-security
How do we enable Cross Origin Requests in our browser? When I run this in Internet Explorer, the web service is called and the data renders correctly, however in Chrome and Firefox my tables are blank.
(I have already tried opening Chrome with web security disabled)
Thanks,
John
Hi,
I followed this article and got an working example, thanks for it.
However, when i try to read data from our own Gateway System instead of gw.esworkplace.sap.com, it is not getting any data.
This is the oModel which gets data successfully,
var oModel = new sap.ui.model.odata.ODataModel(
"proxy/http/gw.esworkplace.sap.com/sap/opu/odata/IWBEP/RMTSAMPLEFLIGHT_2",
false,
"GW@ESW",
"ESW4GW");
And this is the sample link that provides the same data and meta-data structure from own Gateway service and it works fine on browsers,
http://xxxx.xxxx.com:8000/sap/opu/odata/IWFND/RMTSAMPLEFLIGHT/
However, when i write this; no data comes up ???
var oModel = new sap.ui.model.odata.ODataModel(
"http://xxxx.xxx.com:8000/sap/opu/odata/IWFND/RMTSAMPLEFLIGHT",
false,
"GwUser",
"Pass");
Any idea will be appreciated,
Yasin,
Hi,
did you try to access via browser to
http://xxxx.xxxx.com:8000/sap/opu/odata/IWFND/RMTSAMPLEFLIGHT$metadata?
Regards,
Ivan
Hi Ivan,
Thanks for the fast reply,
I can not access this ; /sap/opu/odata/IWFND/RMTSAMPLEFLIGHT$metadata
but i can not access to; http://gw.esworkplace.sap.com/sap/opu/odata/IWBEP/RMTSAMPLEFLIGHT_2$metadata/
neither but it works fine,
Also, i can access to;
/sap/opu/odata/IWFND/RMTSAMPLEFLIGHT/FlightCollection/?$format=json
Best Regards,
Yasin
Edit: I can access to ;
/sap/opu/odata/IWFND/RMTSAMPLEFLIGHT/$metadata
Hi Ivan,
If this was a more *real* scenario, we couldn't just run the browser in a mode which allows cross-origin requests.... So what is the best way to handle this. Is Gateway capable of working with CORS if we use the CORS headers in the ajax calls? Or do we have to provide a proxy server (like the simple proxy server provided in the eclipse development tools)?
Regards... Jason.
Hi Jason,
usually I prefer to move into a proxy scenario.
Regards,
Ivan
Thanks Ivan... Have you done this in productive scenario's at all? What proxy setup did you use/recommend?
When developing your own sicf services you can set the CORS headers. Considering that Gateways runs within SICF services itself you wold think that somehow this would also be possible - they could have set it up as a config setting on your OData service but I can't see any documnetation to this effect.
Maybe there are just very few scenarios likes this in PRD environments out there, so most people just use the browser switches to ignore cross-site scripting. 😉
Excellent tutorial! Just in case anyone else has any problems, these troubleshoots worked for me:
Thank you for this nice blog!
thanks a lot to all,i feel temporarily gateway server is not available.
Great tutorial. 🙂
But is there any chance to bind 2 models at 1 table?
Greetings,
Sarah
Sarah,
why you should do this? It seems to me a strange requirement...
Ivan
Hi Ivan,
Thanks for a great tutorial.
It would really be helpful if you can guide me through the same problem which everybody mentioned above. I tried both the solution- appending / at bind rows and modifying the URL to include proxy and nothing worked for me. All the browsers chrome, opera, IE and mozilla still showing empty tables.
Thanks,
Atul
Hi,
This is very nice blog with detail explanation. I tried to run the same programe for my practice but as already discused blank table, I am also geting blank table. I have also added "/" and "proxy" as explained above. In my IE also I have allowed cross domain.Still I am getting a blank table. So please help me out to make this example run.
Tomcat is mandatory? I tried to run on local as Web App. Is that stopping to display table data.
Thanks,
Hi,
in order to avoid the CORS error another solution is to create a very simple SICF handler that acts as a proxy to the Gateway service provider.
Best
Ivan
Hi Ivan,
Can you please tell the steps to create this SICF handler? I was working on this example couple of months back and now I want to resume where I left, and this is the point where I am stuck 🙁 Please help me with the required steps or share any document if you can..
Thanks,
Atul
This gives you some help...
http://scn.sap.com/community/abap/blog/2013/01/24/developing-a-rest-api-in-abap
Hi All,
I am facing same problem. Tried all help as above. But "No Data".
In console:
Please suggest.
Thanks,
Sanjoy
It seems that the Gateway Server is not available... This server is managed by SAP...
"Description: internal error - server connection terminated"
Hi Ivan,
I am facing the issue..Its working fine in webapp preview and internet explorer..But no data is displayed in chrome..
I changed the settings in chrome(--disable-web-security)...
Any help on this?
For anyone who tries to test your SAPUI5 project.
Maybe using Node.js as a web server could be fine because all the messages of Cross-Origin bla bla bla cames in because our machine is not recognized as a web server.
Download Node.Js, execute the webserver script, put that script into your the root of the folder of your SAPUI5 project.
TEst!