OpenSAP HANA1-1 Week 5 Transcripts

23
openSAP Introduction to Software Development on SAP HANA WEEK 5, UNIT 1 00:00:13 Welcome to week five, unit one: Server-Side JavaScript. In the previous week, we saw how we can use the generic OData service generation framework for the creation of REST-based services and how they're also consumed from the user interface. Now this OData framework is very nice in that it’s easy to use and with a simple service definition document we can have a running service in a matter of seconds, but it does have a few limitations. 00:00:41 Currently in HANA 1.0 SP5, only read operations are supported so if you want to create, update, or delete data, you need another option. 00:00:53 Also, you can only do OData services. So what if you want a custom body format? What if you want some custom validation logic before you fire into reading of your view or your table? In all of these situations we have another option, to be able to programmatically create services on our own. That’s what we’re going to talk about all this week: using JavaScript as a programming language for implementing REST-based services, where JavaScript is the primary programming language used in the XS Engine, in the Extended Application Services. 00:01:30 So let’s review for just a moment the primary development model in SAP HANA Extended Application Services. We see various parts of this overall development model and we’ve talked about many of them already. 00:01:47 But the overall rules that we have seen: One that the UI client rendering is completely done in the client side so there’s no server-side UI framework. We simply have REST-based services that expose data and logic to the client side. All the event handling is done inside the client side and then browser code, as we have seen, either the UI elements were provided SAPUI5 or JavaScript running on the client side is used to consume these services and then inject the data into the page. 00:02:22 On the server side, our programming language for all procedural logic is JavaScript. We have seen how we can use SQLScript as the main programming language for data-intensive logic down in the database. But it is designed—although it has some imperative logic features—it is primary designed for data-intensive operations. 00:02:46 On the other hand, JavaScript is well suited to more imperative logic so having validation is also well suited for the creation of services and control flow logic. But yet all of the development artifacts, whether it’s our user interface, our server-side JavaScript, our OData definitions, the underlying data-intensive logic, even the definition of the catalog artifacts that exist in the database, they're all stored in the SAP HANA Repository. This document contains a transcript of an openSAP video lecture. It is provided without claim of reliability. If in doubt, refer to the original recording on https://open.sap.com/.

Transcript of OpenSAP HANA1-1 Week 5 Transcripts

Page 1: OpenSAP HANA1-1 Week 5 Transcripts

openSAPIntroduction to Software Development on SAPHANA

WEEK 5, UNIT 1

00:00:13 Welcome to week five, unit one: Server-Side JavaScript. In the previous week, we saw howwe can use the generic OData service generation framework for the creation of REST-basedservices and how they're also consumed from the user interface. Now this OData frameworkis very nice in that it’s easy to use and with a simple service definition document we canhave a running service in a matter of seconds, but it does have a few limitations.

00:00:41 Currently in HANA 1.0 SP5, only read operations are supported so if you want to create,update, or delete data, you need another option.

00:00:53 Also, you can only do OData services. So what if you want a custom body format? What ifyou want some custom validation logic before you fire into reading of your view or yourtable? In all of these situations we have another option, to be able to programmaticallycreate services on our own. That’s what we’re going to talk about all this week: usingJavaScript as a programming language for implementing REST-based services, whereJavaScript is the primary programming language used in the XS Engine, in the ExtendedApplication Services.

00:01:30 So let’s review for just a moment the primary development model in SAP HANA ExtendedApplication Services. We see various parts of this overall development model and we’vetalked about many of them already.

00:01:47 But the overall rules that we have seen: One that the UI client rendering is completely donein the client side so there’s no server-side UI framework. We simply have REST-basedservices that expose data and logic to the client side. All the event handling is done insidethe client side and then browser code, as we have seen, either the UI elements wereprovided SAPUI5 or JavaScript running on the client side is used to consume these servicesand then inject the data into the page.

00:02:22 On the server side, our programming language for all procedural logic is JavaScript. Wehave seen how we can use SQLScript as the main programming language for data-intensivelogic down in the database. But it is designed—although it has some imperative logicfeatures—it is primary designed for data-intensive operations.

00:02:46 On the other hand, JavaScript is well suited to more imperative logic so having validation isalso well suited for the creation of services and control flow logic. But yet all of thedevelopment artifacts, whether it’s our user interface, our server-side JavaScript, our ODatadefinitions, the underlying data-intensive logic, even the definition of the catalog artifacts thatexist in the database, they're all stored in the SAP HANA Repository.

This document contains a transcript of an openSAP video lecture. It is provided withoutclaim of reliability. If in doubt, refer to the original recording on https://open.sap.com/.

Page 2: OpenSAP HANA1-1 Week 5 Transcripts

Page 2 Copyright/Trademark

00:03:22 So let’s talk a little bit more on what we’re going to focus on this week, which is the server-side JavaScript. So server-side JavaScript is very well suited to lightweight procedural logic.

00:03:34 We choose JavaScript for a couple of reasons. First of all, the execution of JavaScript isrelatively fast. I might not have wanted to say that a few years ago, but we’ve seen a lot ofimprovements in the compilation in execution of JavaScript and this largely comes becausewe now see competition in amongst the browsers.

00:03:58 And that competition between Chrome and Firefox and Internet Explorer has caused all thebrowsers to improve the execution speed of their JavaScript. Because we see JavaScriptbeing the main component for the execution in HTML5–based applications.

00:04:15 Added to this, SAP did not write our own JavaScript virtual machine. It would have been kindof silly, considering there is already so many good open source options. So we decided touse the Mozilla SpiderMonkey virtual machine, that’s the JavaScript virtual machine that runswithin Firefox.

00:04:36 Now this virtual machine is well suited to our needs. It allowed us to extend the virtualmachine and add in things like the HANA native data types, and we could also add our ownAPIs to the virtual machine as well. We’ll talk more about those APIs in just a moment.

00:04:58 But because we choose an open source JavaScript VM, we can quickly adapt improvementsthat the open source community makes to that VM. That largely means that as newerversions of Firefox come out and the JavaScript encryption is improved in those versions ofthe browser, we can fairly quickly adapt those improvements into the server-side JavaScriptexecution engine inside of HANA Extended Application Services.

00:05:28 This also means that we're open, not just because we're using an open source VM butbecause JavaScript is a very open, very widely known programming language.

00:05:37 This also lends us to being able to reuse existing JavaScript code, so we're able to executestandard ECMA-compliant JavaScript. And as long as that JavaScript doesn’t assume thatits running in a Web browser and try to do something specific with the client, like try toaccess the DOM, the document object model, something that wouldn’t exist on the serverside. As long as your code doesn’t try to do any of those things, it’s going to execute server-side JavaScript inside HANA Extended Application Services as well.

00:06:12 So that means that you can take existing open source libraries and you can take existingcontent that you find on the Internet, lots of JavaScript examples out there, and you can veryquickly and easily integrate them into the server-side execution environment.

00:06:29 It also means that you have one language to learn and use for both the client-side and theserver-side development. So with HTML5, even if you’re not using SAPUI,5 just about all theother major HTML5 environments, development environments, you’re going to need to knowsome JavaScript.

00:06:51 To do modern Web development you have to be well versed in JavaScript. There’s really noavoiding it. That means you’re already going to have to go out and learn JavaScript, you'regoing to have to have developers who are familiar with JavaScript. You might as wellcontinue to leverage that knowledge and use the same programming language on the serverside.

Page 3: OpenSAP HANA1-1 Week 5 Transcripts

Page 3 Copyright/Trademark

00:07:10 We also find that there’s widespread knowledge of JavaScript. Most any student coming outof university with a programming degree these days will have some experience doingJavaScript already.

00:07:21 Very commonly used programming language because it’s so widely used in the Web. Arecent survey that looked at all public perforce and gift hub repositories found that JavaScriptwas the most commonly used language in all those open repositories.

00:07:39 And there is tons of information available. Information on the Internet for free, there are goodbooks that are out there, it’s incredibly simple to find educational materials on JavaScripteven if you aren’t already familiar with the programming language, and it’s really quite easyto learn.

00:07:59 And then finally, JavaScript lends itself well to rapid development. There’s no long compile orbuild cycles. You don’t have to do a nightly build or anything like that. You can write yourJavaScript code, save it, activate it, and it is immediately executable.

00:08:13 Therefore it lends itself well to test-driven and iterative development; you can make a fewchanges to your code, activate it immediately, test those changes, and then maybe go backand continue adding to the code.

00:08:23 And that's a model we want to follow inside of SAP to support rapid and agile development.

00:08:33 So a little bit about the server-side JavaScript code itself. We have some HANA nativeapplication-specific APIs. Therefore when you write the server side JavaScript, it is going tobe largely very specific to HANA, very specific to HANA Extended Application Services.

00:08:55 This is where you write all the control flow between the client and the HANA sever. You’llnotice that our primary APIs are to give us access to the HTTP request and the HTTPresponse object.

00:09:11 We have direct access to those objects we can read data directly from them so we can wecan read our HTTP headers. We can write directly into the response body.

00:09:22 We can set response headers so we have a lot of control. So that also means that we have alot of responsibility for properly formatting the body and setting the correct headers andthose sorts of things.

00:09:34 So there isn’t a lot of programmatic framework where things are provided for you. If you wantthat then we have the generic OData services, but once you choose to use the server-sideJavaScript you have this really low level of control.

00:09:48 Now the JavaScript artifacts are stored in the content repository like all the otherdevelopmental artifacts that we have seen so far. And the developmental process forcreating them and then committing them and activating them is largely the same aseverything up to this point. Now we do have a dedicated server side JavaScript or XSJSeditor and debugger.

00:10:12 And we created a dedicated editor. What we really did was we took the standard EclipseJavaScript editor and then we we're just able to subclass it and add some features to it.

00:10:25 We wanted to be able to display all of our added APIs in the class overview in a project. We

Page 4: OpenSAP HANA1-1 Week 5 Transcripts

Page 4 Copyright/Trademark

wanted to be able to add code completion for our APIs. And we wanted syntax highlightingthat didn’t just have the standard JavaScript syntax highlighting, but also had some of ouradditional features.

00:10:50 And then we wanted a debugger. We wanted this even though its JavaScript and inJavaScript you generally think about executing on the client side and then therefore beingdifficult to debug because it’s running inside of the Web browser. Well this is executing onthe server. It should be just as simple as any other programming language to set abreakpoint, run your Web page that calls to the HTTP service, and the Web browser stopsand the clips debugger comes up and you have full debugging capabilities. And that’sexactly what we have introduced in HANA 1.0 SP5 for the server-side JavaScript.

00:11:28 Now there are several APIs, and this is the code that we have added to the JavaScript VMand largely it allows you to interact with various pieces of SAP HANA or the ExtendedApplication Services runtime itself.

00:11:46 Now the important thing here, the APIs are not written in JavaScript. They are actuallywritten in C but we can expose them to the JavaScript programming model and they look likethey're JavaScript functions.

00:11:58 So it’s really kind of nice. You get the ease of use of it being as simple as calling it anotherJavaScript function, but at the same time these are implemented in very powerful multi-threaded C environment.

00:12:15 So these APIs, only the SAP HANA development team can create them. If a customer orpartner wants to create any reusable code, they would use JavaScript and we’ll see in asecond how you would create reusable functions.

00:12:33 But SAP is able to create these powerful reusable functions and then expose them asJavaScript functions and these are the functions that we will use to access the database tosend SQL commands down to the database and get results sets back. We have an API thatrepresents the results set in such a way that the data doesn’t have to be transformed fromthe HANA native data types.

00:12:58 It’s not until really you cast some of that data into a JavaScript variable that it finally has tobe transformed.

00:13:04 And this is one of the powerful benefits of using HANA Extended Application Services is thatthe application server layer understands the HANA native data types can store and processthe HANA native data types.

00:13:16 And with these APIs, we basically have the ability to expose data to the outside world to formupdates, inserts, delete data...basically anything that you can do with SQL clusterprocedures we can do all that via the database API.

00:13:33 We also have the request API, and that's what gives us access to the HTTP request and theresponse object.

00:13:40 And in the screenshot you see some additional APIs that will be coming in HANA 1.0 SP6.So we're adding an API for outbound connectivity, so you will be able to consume REST-based services or really consume anything over HTTP or HTTPS.

Page 5: OpenSAP HANA1-1 Week 5 Transcripts

Page 5 Copyright/Trademark

00:13:59 And a repository API. So we've seen how from the studio we can check things in and out andactivate them, but we also want that all to be programmatically exposed to server-sideJavaScript as well.

00:14:11 And we’ll continue with this approach of the HANA team taking HANA functionality andexposing it to the JavaScript programming model through the form of these built-in APIs.

00:14:24 And then finally we also have the concept of creating server-side JavaScript libraries, orXSJS lib files. This is when you want to create some reusable code. You have a function thatdoes something you want to use in more than one application, then you put it in this XSJS libfile and no matter where it is in the content repository it can be shared with all other projects.

00:14:54 Basically we have the syntax $import and we give the package path pointing to where thisXSJS lib lives, and then we give the name of the XSJS library. And then we're able to callfunctions that exist inside that library, either by using this full pass $ and then the fullpackage path name of the library, and then .name of the function, or you can even, as you’llsee in the source code examples in subsequent units, you can even declare like a shortcutname for that so you don’t have to repeat the whole path each time you call a function.

00:15:31 And this is a great way to reuse existing open source examples, open source code, andthird-party JavaScript code. I personally use this, I’ve gone out to the Internet and foundsome great JavaScript samples. Using some the other day to do some decode encode fromBase64, there was an example of creating a zip file, zipped content and compressingcontent. These were open source and just example JavaScript code. We were able to justcut and paste the code from the online repository or the Web page that it came from and putit in an XSJS lib, and then it’s perfectly functional inside the server-side JavaScript as well.

00:16:21 This is also a great way if you have repetitive tasks like handling of forms or conversion ofday time strings or parsing URLs that you could put in one of these XSJS libraries, and it’s anice way of reusing this code so you’re not cutting and pasting it into each of yourapplications.

00:16:41 I did this one the other day. I needed a little function that would add a day or add anyarbitrary amount of time to a time stamp, and I needed that in two or three applications.

00:16:55 I didn’t want to cut and paste the code. It was only three or four lines of code but it was stillbetter to put it into a reusable function in one of this server-side JavaScript libraries and thenit’s easily reusable for multiple applications.

00:17:07 So you see with the syntax how we can import these libraries into other XSJS applicationsand then it’s very easy to call functions from that reusable library.

00:17:20 So in this unit we have given you your first introduction to the concept of server-sideJavaScript talked a little bit about how the architecture works, the APIs that are available,and how we can create reusable libraries.

00:17:36 In the subsequent units we’ll go into the system and we’ll start creating some example code.We’ll show you what the development environment looks like, how we then consume theseservices from the client-side JavaScript of SAPUI5, and then finally how we can debug ourserver-side JavaScript code.

Page 6: OpenSAP HANA1-1 Week 5 Transcripts

Page 6 Copyright/Trademark

WEEK 5, UNIT 2

00:00:13 This is week five, unit two: Creating an XSJS Service. So in the previous unit we saw a lot offundamental concepts about server-side JavaScript and how it can be used , when it can beused, and just a little about the syntax. In this unit we’re going to go into the system andwe’re going to create our first simple server-side JavaScript service.

00:00:37 This will be mostly focused on just working with the APIs and development environment.We’re not going to create something that is fabulously powerful, but is a simple example toget us started. In the subsequent units we’ll have more complex examples.

00:00:55 So first of all we’ll use the HANA studio. And we do have a file new wizard for the server-sideJavaScript. We have one for creating the source file which is an executable server-sideJavaScript service end point, and we have a separate wizard XS JavaScript library file, that’sfor creating the reusable libraries that we spoke about at the end of the previous unit.

00:01:22 So this will create the .xsjs source file and this is where we can put all of our application logic.We then commit and activate it just like all the other development artifacts that we’ve workedwith so far. And then, of course, you’ll have a service end point that’s reachable via HTTP orHTTPS. We can then write a user interface on top of that, we’ll see that as well in asubsequent unit. We can also just go out to the Web browser and directly test our serviceend point.

00:01:59 In this example we’re going to keep it really simple, we’re going to have a service that takesin two parameters, two numbers, and we’re going to multiply them together and then put theresults into the body of the response object.

00:02:15 Now, not that you would ever have to come back to the server to be able to do multiplication,it’s certainly something you could do on the client side, but I intentionally wanted to choose avery simple example to start with so that you can focus on things like: How can we get URLparameters out of the request project? How do we write into the response body? How can wehandle error situations? without really having to get deep into a lot of Java syntax or anycomplex calculations or anything like that on the Java server side.

00:02:53 You notice here we’re also not interacting with the database yet so in this example we’resimply going to use the request and response APIs and in a later example we’ll show youhow to interact with the database. Obviously, most times when you have a server-sideJavaScript service, you’re going to be doing something with the database. Otherwise whywould it be running on SAP HANA?

00:03:17 The end result is we’ll have one function to perform the multiplication, and there’s variousvariables we’ll have in there to hold the two numbers that we’ll bring in. The answer to themultiplication, a variable to hold our command—because also from the URL parameter we’llpass in which command we want. This way we can have a single service endpoint that doesmultiple things and for our test we’ll start off with one that does multiplication and then we’regoing to add additional functions to it in subsequent units.

00:03:47 Finally we have the body. This is where we can build up the content we want to inject into theresponse body. Anything that goes into the HTTP response body will be displayed by theWeb browser. We’ll see this when we test our service in the Web browser.

00:04:06 So at this point let’s go back over to the HANA studio, I’m in my SAP HANA dDvelopmentperspective. I’m going to switch to the Project Explorer and of course I have the project that

Page 7: OpenSAP HANA1-1 Week 5 Transcripts

Page 7 Copyright/Trademark

we’ve been working on all along. Now I’m going to add to the services folder. This is whereI’ve already created our XS OData service. Now we’re going to extend it and add someserver-side JavaScript services as well. So from this package I’ll say New—>Other and then Ican come down here and under SAP HANA Development we see the various wizards wehave, similar to much earlier when we created the role via one of the wizards.

00:04:48 We have a dedicated wizard here for the XS JavaScript source file. I just say Next. You’llnotice that I already put a file name in here but it has the .xsjs file extension already on theend of it. We’ll just say Example1. It doesn’t really matter what I name the service other thanthat this will be part of the URL that we call later.

00:05:17 Say Finish and this opens in the XSJS editor. And you remember early on when we createdour project, we created an XS project. And part of the reason we did that is so we can getthese JavaScript resources. These JavaScript resources show us what ECMA3 basicfeatures we have in the JavaScript language. You won’t find all of this in SAP’sdocumentation.

00:05:48 In our online documentation, we only document the APIs which we add to the JavaScript VM.There are lots of standard capabilities built into the JavaScript VM– being able to do math,being able to do text manipulation, and so forth. All these APIs are available here. We cansee information about them. We can even drill-in to them and we’ll see the interface for thesefunctions, so that’s the standard.

00:06:27 In our built-in library, these are additional features that we see here, here we have Math,complex math functions, Number, Object, Regular Expressions built into the language itself.These are also all coming from the standard JavaScript VM.

00:06:54 Let’s go back to our example, at this point I’m going to cut and paste in my code and thenwe’ll talk about it. You notice that I get nice code syntax formatting here, it helps with thereadability of the code. Now what we usually do with our server-side JavaScript is that wehave to list all of our functions first, but the block of code at the end of all our functions list,that’s where the program execution comes in.

00:07:30 So when a web browser will access this Example1.xsjs, the processing will start here. Thefirst thing that we’re going to do is we’re going to use the API. All our APIs start with the dollarsign, so $.request. So we’re going to access the HTTP request object. and then we’re usingthe parameters objects, we’re saying those are any url parameters that were passed in.We’re saying get the parameter named CMD.

00:08:04 So this is where from a programming standpoint there is no set definition of parameters,unlike OData where the OData specification decides what the parameter name should be.You as the developer have to decide which parameters you expect and then correspondinglyuse the same parameter names when you call the service.

00:08:22 In this case, I’ve decided I want a parameter named cmd and that’s where I’m going to passin which operation I want to perform. I then go into a case on that cmd or whatever value thatI’ve pulled out of that URL parameter and when it’s multiplied, I’m going to branch into thisfunction to perform multiply.

00:08:44 If I pass something that’s completely invalid, if I didn’t pass multiply into cmd, then I’m goingto set the response. status and we have some built-in constants to be able to tell it “that’s thecode for error, that’s HTTP500, status code 500”, and then the response. setBody will put

Page 8: OpenSAP HANA1-1 Week 5 Transcripts

Page 8 Copyright/Trademark

content directly back in the body. So I’m going to say Invalid Command and take whateverwas passed back in and put it back in to that error message.

00:09:17 Now in the performMultiply, this is going to be relatively simple, we’re going to get the URLparameter named num1. We’re going to get the url parameter num2. We’re going to multiplythem both together and put the results in answer. And then answer would be a numeric atthis point, but we want to cast it into this body, which is a string, so we’re going to sayanswer.toString.

00:09:41 And then the body will be set into the response body and if we got this far and everything isokay. We’ll use net.http. OK, so it’ll be HTTP status code 200 will go back to the client. Solet’s go ahead and save our service and we will activate it. So at the time of activation, if Ihave any syntax errors that’s when it would tell me. If I were to come here and put insomething that’s syntactically incorrect…already I have a warning here that I’m missing asemicolon. But let’s go ahead and try and activate this. This should produce a nice hard errorhere. There we are. It let me know that I have errors, do I want to activate anyway? I can seethe results of the syntax check. It expected a semicolon, instead it’s all body.

00:11:02 Line 8 position 27, so I know exactly where my problem is. So I can go ahead (of course, Iput that line in, knowing it was bad, to demonstrate what the syntax errors look like) andcorrect it, reactivate, and now everything’s okay.

00:11:25 So with that, once it’s activated, I have an executable service. I can go to the Web browser.I'll just open another tab here, go to my package path, which would beworkshop.sessiona.00/services. But now I just put in Example1.xsjs. I’ll put a question markso I can start putting in my URL parameters, so cmd= multiply&num1=5&num2=10.

00:12:14 I run my service and I get 50 back. No formatting because we aren’t putting any HTML tags inthe body, we’re just putting that raw data, that answer.toString, so we’re converting thenumeric value to a string, putting that string directly in the body. Therefore the browser getsthat response so it does it’s best to display it exactly as we told it to.

00:12:41 So once again, services, although we can test them from a Web browser, it’s not somethingwe give to our end users to be able to run. This isn’t how they would run the service. Theservice gets embedded into a larger overall user interface.

00:12:57 Let’s maybe make a mistake here. Let’s change the command to a command we haven’t yetimplemented multiply2. And we’ll go ahead and run this and you’ll see, now I get my errorcode I get Invalid Command: multiply2. And if I were to go ahead and turn on the developertools, and I’ll refresh that, you see that I get a 500 Internal Server Error. So if I was calling thisservice say, via Ajax, as we’ll do in the user interface, we’ll be able to test the HTTP responsestatus and right away we know we’ve got a 500, I go into some sort of error condition. If Icorrect this then it works correctly and I get a 200.

00:13:45 So this has been a very simple example, but hopefully it's let you focus on how themechanics of how we create a server-side JavaScript and what the basic program flow is. Inthe subsequent units, we will certainly get into more complex examples. We’ll interact withthe database, we’ll have some reusable libraries, and then we’ll consume the service in theuser interface.

Page 9: OpenSAP HANA1-1 Week 5 Transcripts

Page 9 Copyright/Trademark

WEEK 5, UNIT 3

00:00:13 This is week five, unit three: Extending the XSJS Service. In this unit we’re going to take theXSJS service we built in the previous unit and then we’re going to add some morefunctionality to it. We’re going to be able to access the database and then we’re going to takethe data that’s returned from the database, loop over it and format it, and create a text tab-delimited response body.

00:00:39 This also shows us how we can differentiate from the OData database services. In the caseof the OData services, we can only return JSON or Atom XML format. Sometimes you mightneed a custom body format or to return binary content that’s stored in the content repository.These are the kinds of things that server-side JavaScript can do for you.

00:01:03 At the end, we want the service to have an additional operation that will allow us to take ourpartner data and format it as text tab-delimited, so we can send it out as a file attachment andit will look like an Excel file that opens when we click on a link. This shows two things, not justthe custom body format that I mentioned previously, but also with server-side JavaScript wehave complete control over the HTTP headers.

00:01:34 We’re able to set the proper HTTP headers so that this will not look like the main responsebody that will be displayed in the Web browser, but instead it will show that it’s a fileattachment and the browser will treat it appropriately and therefore prompt us to open or savethe file. And if we say Open, then it will open in Microsoft Excel.

00:01:55 The other thing that we’re going to introduce in this exercise is some reusable libraries. So Ihave already prepared a server-side JavaScript library that contains some processing forissuing error messages. So we’ll see how we can use that inside our application and I’ll evengo into this library and have a look at the coding inside of it.

00:02:22 So we’ll add a new function called downloadExcel. It will be responsible for retrieving the datafrom the database tables and views and then formatting that into text tab-delimited and thensetting the proper headers so it will display in the Web browser as a file download with theExcel type.

00:02:42 In order to do that, we’ll have to loop over the result set and concatenate together a stringand put in the proper formatting as we pull the various pieces of data out of the record setand put it into that text tab-delimited string.

00:02:59 We’ll also have to set the custom HTTP headers, and so we’ll have to set the contentType totell it that this is Excel. That’s what the browser uses to know which application on the clientside to open the content with. And we’ll have to set the Content-Disposition header so we cansay that this is an attachment and set the file name.

00:03:23 And then finally we’ll also see how we can perform SQL queries. We have a JDBC or ODBC-like syntax for executing SQL statements. We have a query object that we build up, make aconnection to the database, do a prepared statement from that query, and then we executethe query.

00:03:46 Now it’s important to note that even though the syntax is like JDBC or ODBC, the execution isstill quite different. So everything we told you earlier about the closeness of the extendedapplication services to the SAP HANA database, that’s all still true. Just because we usesyntax that looks like JDBC/ODBC doesn’t mean that the data has to be transformed or it’sbeen sent across the network or anything like that.

Page 10: OpenSAP HANA1-1 Week 5 Transcripts

Page 10 Copyright/Trademark

00:04:13 We simply wanted the programming interface to look familiar to developers. In reality the SQLstatement is being preprocessed inside the XS Engine and there’s some directcommunication to the index server going on. Very efficient processing of this query, veryefficient processing of the results set that comes back.

00:04:32 You’ll notice that when we execute the query, we’re putting it back into an object, this rsobject. That is a special API we’ve added to the JavaScript VM to represent results sets, torepresent data that’s being returned from the database. As long as the data stays in thatresults set, it stays in its HANA-native data type format.

00:04:53 Once again, no data transformations have to take place as the data is returned to theapplication server. Let’s go into the system now and lets extend our example. So let’s pullthis back up again to refresh what we had in the previous unit. Our processing comes in atthis point. We look at our URL parameters and get the action we want to perform from thecmd. In this case, we only have the one, which was multiply. We branch into ourperformMultiply function and we very quickly do our multiplication of two import parametersand put them into the body.

00:05:33 So let’s go back over here, let me add two things right away. Let me first add this importstatement, so $.import. And then I give it the package path and the file name. So I’m sayingimport from SAP.hana.democontent.epm.services. So here I have“SAP.hana.democontent.epm, so this is the project that that’s in and I said services and thenI said messages, so that's this messages.xsjslib, that’s the content that we’re pulling in.

00:06:11 So we’ll now have access to all the functions in here, the escape and the getMessagefunctions. And like I said earlier, we can call those functions by specifying this whole longstring here. We can also create almost like an alias for this path, so I’m going to say varMESSAGES and MESSAGES=$.sap.hana.democontent.epm.services.messages.

00:06:38 Now we have easy access to call those functions via the shorter name of MESSAGES. AndI’ll actually use that right away. Let’s rewrite this error handling, so let’s and change this errorhandling. The status is the same, but now in the set body we’ll call MESSAGES.get Messageand we’ll pass a message class and a message number and any variables we want to parseinto that message.

00:07:13 What this allows us to do is do language-independent error message processing. So insteadof hard coding the text in here I’m going to have this reusable function called getMessagethat will go to the database and will look up the error message for this message class andthis message number, for the current logon language.

00:07:32 If no message exists for that logon language, then it’ll fall back to English and then it’ll takethe resulting error message and it’ll parse in any parameters that we have here. So let’s seehow this is done, we’ll bring up this messages.xsjslib. Inside here we expect messageClass,messageNumber, and up to four parameters that can be parsed into the error message.

00:07:59 Then we’ll use another API that we haven’t seen yet, $.session. So this is where we can getinformation about the user session. I’m going to use this to get the current language and justto be safe; I’m just going to get the first two characters of the language. Next I’ll get aconnection to the database. Now with the getConnection, you’ll notice that I don’t have tospecify any connection string.

Page 11: OpenSAP HANA1-1 Week 5 Transcripts

Page 11 Copyright/Trademark

00:08:25 In JDBC/ODBC you would, of course, have to specify something which would tell you whatserver to connect to, what port, what user name and password to use. Well XSJS knows thatit’s living inside of HANA therefore when I say getConnection, it knows the database alreadyand there’s no functionality to do a getConnection to a foreign database. At least, that’s notfunctionality we have yet.

00:08:48 The only reason we even really have this API getConnection is we can pass in a parameterhere and that parameter would be the name of a SQL CC entry. The idea of a SQL CC entryis maybe you want an anonymous service, so I don’t want the user to have to authenticate tomy service. That’s fine, we can do that. You can go into your .XSaccess file and you can sayauthentication:null and then it’ll run as an anonymous service. It will not prompt for our username and password.

00:09:23 But when you get in your code, we can execute JavaScript code but as soon as you try andgo to the database, that will fail. You always have to have a user associated with yourconnection. The SQL CC is a tool you can set up and put a user name and password in thistool and save it with a unique ID. And in this getConnection you simply specify the SQL CCID and that user name and password will be used automatically.

00:09:54 That avoids us having to hard code user name and password into our program code. I don’thave an anonymous service, it’s using my user authentication on the Web browser so it’sgoing to run as my database user that’s logged in. I don't need to specify anything in thegetConnection. Next I have my SELECT statement. So I’m selecting Description from tablemessages and you’ll notice here in the WHERE clause, I’m saying message class=?,message number=?, and language=?.

00:10:28 So this is a parameterized query and you want to follow this pattern any time that you haveWHERE conditions, particularly if the values for those WHERE conditions are coming fromthe client side or coming from outside the service. We want to protect against somethingcalled SQL injection. That’s where someone could maliciously call our service and forceadditional content into the parameters.

00:10:53 So you could imagine if maybe they would try to say here MessageClass= and we pass in avalue and we just directly can concatenate that value in from outside. Someone might havemaliciously overloaded that and said MessageClass=123 AND MessageClass= somethingelse and be able to get access to more data than we intended them to have access to.

00:11:20 Well if we use the question mark and the parameterized query statement, then when we dothe prepareStatement, we can take the prepareStatement and set those values in. So I’ll saysetString 1, meaning the first question mark, replace it with the value messageClass, andwhen I use the set functions of the prepared statement the system will automatically do atype check for me to make sure that the data coming in matches the data type of theparameter of the WHERE condition that I’m matching it up to.

00:11:57 We’ll also safe encode the content that’s coming in to make sure you can’t add on additionalinformation, like add on more WHERE conditions, like an AND or OR condition or somethinglike that. So it protects you against SQL injection and as long as you use theseprepareStatement set functions, you’ll be pretty safe against SQL injection.

00:12:22 If you just concatenate these values directly into the string, well, then you’re vulnerable toSQL injection. So then we’ll say executeQuery. We get a record set back. Now record sets,we always use a WHILE loop over record sets. We want to process it one record at a time.

Page 12: OpenSAP HANA1-1 Week 5 Transcripts

Page 12 Copyright/Trademark

We can only do forward processing for a record set. Once I’ve gone forward, once I’ve readthe next record, I can never go backward.

00:12:53 There’s no .previous or anything like that. You can think of it almost like a destructive read, ifyou will. The idea is if you need random access to the record set, you need to read a specificrecord, you loop through until you find that record. If you need to be able to go back and reada previous record you’d actually have to have two record set objects. So it just meansperforming the query twice. Because it’s an in-memory database, and we have efficient datatransfer we can do things like that and it doesn’t come at a high cost.

00:13:26 So all we’re doing here is we’re saying get rs.next, so that’s going to get us the first record.And then we’re going to get a string parameter out of there, so get the first value, which isjust the text because we said SELECT description. So the getNString(1) there is going to getthe first field that’s in the record set, which was only one, it’s a description. Put it in ourmessage text. If the message text is blank then we can assume that there was no record inthe database for whatever language we were logged in as or maybe that was a record, butsomebody hasn’t maintained any text for it. Either way we wanted to try going to Englishinstead.

00:14:10 So you notice what we do here is we just switch the language to English. And this is anotheradvantage to using the prepareStatement. I don’t have to re-prepare the statement. I can usethe same prepareStatement, just reset the values into it, and then perform the query again.This can lead to much more efficient processing particularly if you’re firing the same queryover and over again inside of a loop.

00:14:32 Although if you’re going to do a large number of operations like that we also have the idea ofbatching. So you can do a special type of prepareStatement that is set as a batch, add abunch of operations to that batch and then instead of “execute query” you have instead“execute batch”. And when you use the “execute batch” it will send all the requests to thedatabase as a bundle.

00:14:56 The database can process them in a parallel fashion and return the results back to theapplication server. In this case, we’re just going to re-execute the query and this time we’regoing to get the string value back, even if it was blank at this point we’re going to just have toissue a blank error message to the user.

00:15:14 We’ll close our record set. We’ll close our prepareStatement. And now we do ourconcatenation. Remember we had four parameters that are passed in that we might want toreplace in the string, and we just set this rule that if inside the text of the error message wejust use an &1, &2, &3, and &4 to be placeholders for values that might be passed in.

00:15:37 So in this case we’re going to say replace &1 with whatever p1toString is and we do escapingon it. This is to make sure that we’re taking a parameter that’s passed in from the userinterface that once again, somebody doesn’t do something malicious. Somebody couldpotentially pass say, JavaScript or HTML or a hyperlink that says, “You’ve committed anerror, click here” that could redirect them to a malicious site, a phishing Web site.

00:16:11 We want to protect against that sort of thing so we want to safe encode anything that camein, so basically replacing the HTML tags so that they’ll show up as comments instead of beinginterpreted by the Web browser. So this is the other nice thing about having a reusable libraryis that we can build in things like automatic escaping and then we don’t have to do that everyplace in our code.

Page 13: OpenSAP HANA1-1 Week 5 Transcripts

Page 13 Copyright/Trademark

00:16:34 So for instance now we have our MESSAGES.getMessage and now we have the safeencoding of this aCmd, so whatever value is being passed in via this cmd user parameter. Solet’s get the rest of our code. We want to add an additional case statement for Excel, for ourdownload to Excel, and now let’s add our function.

00:17:02 That processes our download to Excel. There we are, let’s walk through what this is doing.So we’re building our query similar to what we did in our messages.xsjslib. We’re going toretrieve the top 25,000 records. Simply for the purpose of the demonstration I didn’t want todownload too much data to Excel, you wouldn’t necessarily want to send millions of recordsto Excel. I guess you could get more sophisticated here and have various filters and WHEREconditions passed in.

00:17:39 Once again, this is a demonstration. Let’s focus more on the formatting of the data and howwe’re passing it down and not really on how I’m giving the data. But I’m getting 25,000records, choosing the fields that I want from the purchaseOrderHeaderExt view, and I’mordering them by purchase order ID.

00:18:00 Now I’m using the trace statement here. This is another API. If I’m having problems with theprogram, if trace is activated and I go into the system configuration and I’d set the trace levelfor the XS Engine to debug, then whatever’s the query string will be written into the trace logand I could then observe that. So even without debugging, if something was going wrong Icould see, well, is it my query that’s wrong?

00:18:30 Now this is a hard-coded query. It has no parameters coming into it, so maybe that’s not allthat valuable, but sometimes it’s nice to have these trace statements in and there’s othertrace levels that you can set as well, information, warning, error, and so forth. So I get myconnection to the database, prepare my statement with my query, and then I’ll execute thatquery.

00:18:55 So in the body now I want to build column headers. And I want those column headers to belanguage-independent as well. So I’m actually reusing my messages and this time I’m notgetting error messages, I’m just getting a plain text block with the column headers that I want.I’m going to concatenate those altogether and just make them text tab-delimited, so the \t inJavaScript is the way we insert a tab.

00:19:21 Then I’m going to loop over my record set and want to concatenate it together, so I’m justgoing to take each of the fields here and concatenate them separated by the tab, at the end,a carriage return, the \n. I do have some error handling, so this entire block is inside of a tryblock so if anything goes wrong then I’m going to go in here, I’m going to catch the error, andthen all I’m really doing is taking that error message and I’m outputting it in the body.

00:19:49 But I am setting the internal server error as well. So if something would be wrong with thedatabase connection, my authorizations, maybe one of my data types was cast wrong hereor something like that, it would all be caught by this error exception handling. If there were noerrors then I can go ahead and set the string into the body. I’ll set the content type. This ishow the browser will know that this is Excel.

00:20:14 I’ll set a custom header, the Content-Disposition header, and that will let the browser knowthat this going to come down as a file attachment and what the file name should be. And thenthis other header, access-control-allow-origin, this is for cross-site scripting. This would allowthis service to be callable if the Web page was running on a different server than what the

Page 14: OpenSAP HANA1-1 Week 5 Transcripts

Page 14 Copyright/Trademark

service is running on.

00:20:39 Now I’m going to consume this later in SAPUI5. The UI5 is running on the same server, so Iwould not need this control allow origin but if I were say, to call this from a mobile device andI had HTML running in the hybrid container from the SAP mobile platform, then that would bea cross-domain access.

00:21:02 Or if I had a Web page or a .NET Web page running on a .NET server and it was going toconsume the service, then I’m going to have a different URL for the Web server than I havefor the service. And once again I would have cross-site access and I would need thisadditional line in the header to set that.

00:21:20 That completes our service, so let’s go ahead and save it. And we will reactivate it and nowwe can go to the Web browser and let’s re-run our test. Let’s put in our package path andnow instead of multiply we will say Excel and I think I did, capital E, so Excel. I’ll just make mybrowser a little larger there. And you notice that the file attachment comes down. We havethe open option here so I’ll go ahead and open that.

00:22:07 And then Microsoft Excel will open and I’m just getting that warning because it’s text tab-delimited and now I have my data down here opened in Excel. And you’ll notice that we’veeven got some nice formatting here, like on the Created At, we get this nice long name. It’staken the time stamp and re-formatted it, and that came from the if we go back to thestudio...that came from the automatic processing when we said getDate. It didn’t just take theraw date format and insert it. It really turned it into its string representation so we get some ofthis automatic type casting and formatting applied when we pull the data out of the record setand basically put it back into a JavaScript variable, in this case concatenating it into aJavaScript variable.

00:23:01 So in this unit we’ve seen a more complex example, we’ve seen how to use re-usablelibraries, how to connect to the database, and the benefits of having this lower-level accessto be able to write custom body formats into the HTTP response as well as set the HTTPheaders.

Page 15: OpenSAP HANA1-1 Week 5 Transcripts

Page 15 Copyright/Trademark

WEEK 5, UNIT 4

00:00:13 This is week five, unit four: Calling XSJS from the User Interface. So far this week we’veseen the basics on how to create server-side JavaScript-based REST services. In this unitwe want to build a user interface using SAPUI5 that will consume these services.

00:00:35 We’re actually going to take that very first simple service that we had that took two inputparameters and multiply them together and display the result. So let’s take a build a userinterface for that.

00:00:48 That means we’ll have a fairly simple user interface that has two input fields. We’ll use thelive change event on those input fields so that every time I type something into them, everycharacter will trigger a call to the server asynchronous, execute the server side JavaScriptand display the results in the screen.

00:01:12 We’ll also format those results so that the numeric value is formatted correctly according tothe user’s logon locale. To do this we’ll take our existing SAPUI5 project from the previousweeks. We’ll extend it and add a new view to it.

00:01:33 And we’ll copy the HTML file that is the bootstrap. We’ll just make a couple of changes tothat bootstrap file to point to the new view and then most of our logic will be in the view andthe controller. Unlike our previous exercises where we didn’t use the controller, this time wewill use the controller because SAPUI5 doesn’t necessarily have a built-in event that knowshow to call our custom service, so we wouldn’t expect it to.

00:02:01 So this is a nice contrast to our OData UI where we had an SAPUI5 control and of course, itknew how to call standard OData services. The table control could be bound to it. This timewe have to custom code the event handler, which is not all that difficult to do, and you’ll seehow we use the jQuery.ajax to asynchronously call to the server and execute our service.

00:02:27 And that will really be the focus of what we code on the client side. We’ll build a URL thatpoints to our service with the proper command and multiply and the two import parametersparsed into that URL, and then we’ll call jQuery.ajax to that URL and if the call is successfulit will branch into the onCompleteMultiply function. And if it’s not successful then we’ll go tothe onErrorCall.

00:02:57 Let's switch over to the system and we’ll have our Example1.xsjs service that we’re going tocall. Let’s go to our user interface: Project, which remember, is embedded inside of ourlarger project and we’ll tell it that we want a new view.

00:03:18 It’ll launch the wizard for this and we’ll call this xsjsTest, say Finish, and we’ll see now insideour exercise UI we’ve got a new XSJS controller and a new view. We just need to copy theHTML file so now we have our xsjsTest.html. Inside here we just need to make a littlechange so we can change the ID. Like I said earlier, that isn’t absolutely necessary, but I liketo do it to keep my IDs consistent with the name of the objects they represent.

00:04:05 But here we’ll change the name of the controller, xsjsTest, so our HTML file is good. Now ifwe go to our view...once again, I’m just going to cut and paste the code because you do notwant to watch me type, no fun in that.

00:04:27 We come here to the createContent. That’s where we do all of our rendering. And let’s talkabout what we’ve just put in here. First of all, I want a panel. A panel is just a grouping UIelement. It has a nice expand/collapse capability and we’ll have the ability to set some text in

Page 16: OpenSAP HANA1-1 Week 5 Transcripts

Page 16 Copyright/Trademark

the description of the panel.

00:04:48 We’ll set some other properties. We’ll set the AreaDesign to Fill, the BorderDesign to Box.These are all cosmetic features/cosmetic properties that we’re setting of the panel. Theninside the panel we create a layout. Layout is how inner UI elements will be arranged. We’regoing to use the Matrix layout but there are other layouts available depending upon whetheryou want a flow-based organization of the inner UI elements. I’m just saying Matrix auto, andthen it will evenly position based on the number of columns that I have in here.

00:05:26 So I add the layout to my panel, but then inside the layout itself I’m going to want to render aTextField for val1 and val2, and then a TextView to show the results. A TextView for theequals sign and a TextView for the multiply sign.

00:05:50 Now I’ll take the text fields, the actual input fields, and I want to attach an event to them. SoI’m going to say, attach the liveChange event. And this is where I’m going to use thecontroller because I’m going to say, any time the liveChange event occurs on this field,trigger the onLiveChageV1 function inside my controller object. oController represents mycontroller, which right now is empty but we’re going to have to add these functions to it.

00:06:21 And then the same thing with the second field. It just goes to a different live change event.We’ll say Layout—>Create row. So this is the order that all the UI elements be rendered in.And then we return the panel and it gets rendered into the page. So that’s our user interface,so now let’s bring up our controller.

00:06:50 So once again, let’s cut and paste here, back to my controller. These are all standard eventhandlers in the controller so onInit, BeforeRendering, AfterRendering, onExit. So if you wantto implement the standard event handlers that are controlled by the SAPUI5 framework, youcan.

00:07:11 In our case, we really just need our onLiveChangeV1 and onLiveChangeV2. In these caseswe’re going to build up the URL. I just need to adjust this because I named my serviceExample1. I’m building up to say cmd=multiply. I’m taking num1= ...and I want to escape thisso it’s properly escaped for putting into a URL.

00:07:52 Then I say Event.getParameters( ).liveValue, so whichever UI element triggered the eventwe have to use the .liveValue to get the currently typed value. We can’t just go and read thevalue in the UI element. The event is actually occurring before the value is put back into thescreen.

00:08:12 But then for the field that it isn’t being typed into we can just say getValue. That’s why weneeded two different event handlers, to be able to trigger this differently for the two differentfields. All we’re doing here is saying now num1 is getValue whereas num2 is theEvent.getParameters( ).liveValue.

00:08:34 Once we have our URL pointing to our service then we use standard jQuery.ajax. This iswhat we were talking about earlier, a couple of weeks ago, when we first introduced SAPUI5and we said SAPUI5 is based upon jQuery, and anytime that jQuery had some functionalitythat was sufficient we just use it, there’s no reason to replace it with anything SAP-specific.

00:09:00 Therefore to make an asynchronous javaScript request, an AJAX request, we simply usejQuery.ajax. We give it the URL, it’s a GET method, we expect JSON to be returned. It’sreally just standard text but it really doesn’t matter and then, if it’s just successful—in other

Page 17: OpenSAP HANA1-1 Week 5 Transcripts

Page 17 Copyright/Trademark

words, if the HTTP status code is 200–then branch to onCompleteMultiply. If we get any sortof error code back then we go to onErrorCall.

00:09:28 And the nice thing about this is that it then releases processing. The browser’s open andavailable for the user to go on working. If this service takes a couple of seconds to process itdoesn’t lock the Web browser. There’s no wait clock or anything like that. But of course theservice won’t take a couple of seconds to process, it’s going to process very quickly.

00:09:49 If we had an error, we would branch down to the onErrorCall and the jQuery.ajax will buildsome additional parameters in here. It’s going to pass this jqXHR, which is going to haveinformation about the error message, textStatus and the errorThrown. So these are all thingsthat the jQuery.Ajax will extract out of the response object for us.

00:10:18 Here I’m just calling the SAPUI5 MessageBox.show, and I’m putting whatever error messagecame back in the body into the screen. In the onCompleteMultiply, if everything workedcorrectly, we’ll take the result so we can say sap.ui.getCore( ).byId(“result”). So this is howwe access any UI element that’s already rendered on the screen. This oResult will be the UIelement; the sap.ui.getCore is a core API of SAPUI5 and is a helper to be able to give us aJavaScript object for a particular UI element on the screen.

00:11:04 We’re then able to say if(myTxt==undefined, then that meant there was some sort of errorthat wasn’t caught. We really didn’t get any result back because myTxt will have the textualbody of the response object in it and therefore as long as that’s not undefined, we’ll put theresult back into the oResults. If it is undefined, then we’ll go ahead and just put it back intothe result that will let the user know that basically something went wrong, and it will replacethe current value that’s there.

00:11:42 If it was good, then we go ahead and use jQuery.ajax.require, so we’re going to load anadditional library at this point, the SAPUI5 core number formatter. And then we’re going touse this number formatter to say that this is an integer instance, that the maximum numberof digits is 12, that grouping is enabled. Therefore, using those settings and the jQueryformatter will also look up our locale, will properly format that number, putting in commas anddecimal points and things like that. Once it’s been formatted, we can take that text, format it,and put it back in the screen using the oResults.setText.

00:12:31 So at this point let’s go ahead and save both of these objects. I do the Save all and now inour UI we can activate our HTML, our controller, and our view.

00:12:52 It’s activating all three objects. They’re all active so now I can go back to the user interfacehere, workshop.sessiona.00/ui/Exercises_UI/WebContent/xsjsTest.html.

00:13:28 So we see our panel being rendered. That’s the title, the title is here with the blue line andthe little notch that lets us expand and contract it. And if I begin typing, already you see thatI’m getting some values here. It’s actually executing the service here, every time I type. NowI haven’t put a value in the other side so any number times 00, as soon as I put a number inthere, then we start to see it coming out. You notice the formatting automatically beingapplied.

00:13:56 And every time that I’m typing...just to show you this I’ll turn on the developer tools and you’llsee each request going across the network. The number gets increasingly large so you seethe request being fired. If I put in a non-numeric field I’m not catching that on the server.Remember our logic was very simplistic.

Page 18: OpenSAP HANA1-1 Week 5 Transcripts

Page 18 Copyright/Trademark

00:14:27 I really, probably, should have some logic to do some type checking on the server to makesure I’m not trying to multiply a character field with a numeric field. I’m getting a Not Definederror because I didn’t catch it on the server side, but you do at least see the error status andthen I get my pop-up so I’m going into my onErrorCall and I get my dialog here, so this is anice SAPUI5 dialog error message.

00:14:55 Now, the message itself is not very nice but once again, that’s because I didn’t have verygood handling on the server side to throw a proper error message when that occurred. But Ican recover gracefully and now I’m back to multiplying.

00:15:11 So in this unit we’ve seen how we can build an SAPUI5 user interface that will consume ourcustom XSJS services. We’ve seen how jQuery is used to call these services usingasynchronous JavaScript. And hopefully you have a much better idea of the end-to-endprocess of both using XSJS to create these services, but also how they’re consumed in theuser interface.

Page 19: OpenSAP HANA1-1 Week 5 Transcripts

Page 19 Copyright/Trademark

WEEK 5, UNIT 5

00:00:00 Welcome to week five unit five: debugging server-side JavaScript. Any good developmentenvironment of course needs good debugging tools.

00:00:10 We've already seen in SAP HANA Native Development the SQLScript debugger, and in this unitwe will see the interactive debugger for server-side JavaScript.

00:00:20 We will show you a little bit about the onetime prerequisites you have to do to set up JavaScriptdebugging in your system,

00:00:30 we will talk about some of the differences that have been made to the server-side JavaScriptdebugging in SP6, as opposed to when it was first introduced in SP5,

00:00:40 and we will show you some demos of how you can perform debugging both from the SAP HANAstudio tools as well as the new Web-based IDE.

00:00:51 So let's talk about the administrative setup you have to do to be able to enable debugging ofserver-side JavaScript in HANA.

00:00:59 A lot has changed from SP5 to SP6 in the area of debugging of server-side JavaScript. In SP5we had to not only enable the debugger, but we had to list the specific port that it ran on.

00:01:14 Well now, in SP6 we use Web sockets and therefore we debug over the http port.

00:01:21 So we no longer have to specify a separate port. This also means that you can keep thedebugger enabled, and it's not nearly as much of a security risk as it was in SP5.

00:01:33 In SP5 we debugged basically as an un-authenticated super user. Therefore we said you shouldreally only turn on debugging on nonproductive systems and for a very brief amount of time -just while you’re debugging, and then immediately turn it back off.

00:01:53 And you should also protect that port at the firewall level. Well now because we're debuggingwith Web sockets, we authenticate the user so that the user running the application will be theone that's debugging it.

00:02:06 And that that means that we can more safely keep the debugger enabled, and it also means thatwe need a special authorization on our user ID to be able to debug.

00:02:17 And that’s what we see here in this slide, in the configuration under the xsengine / ini section youneed to have a section for debugger, and then you need to add the parameter enabled, and itneed to be equal to true,

00:02:31 and then your user needs the new debugger role added to it. Now let’s go into the system and I’llshow you where each of these items are set up.

00:02:46 So here I am in the HANA studio and I will go to my system connection, I’ll go to administration;and this the kind of thing your developer user may not be able to do in your system.

00:03:00 You may have to ask the system admin to do the initial debugger setup, the enablement, but thisshould likely now be a onetime type activity and you could, in your development system, at least,keep the debugging turned on.

00:03:13 So from the system information screen, we can go to Configuration and then xsengine.ini, andthen we would open the debugger section,

00:03:31 or you might have to add it, - you might have to right mouse click here and say Add Section, andthen you'd have this Debugger section and then we see Enabled and we have it marked as true.

00:03:44 So this system is able to do debugging, and then I’ll come back over here; I want to look at myuser ID as well, so I go to the Security tab and I’ll look at my openSAP user.

00:03:47 Now I don’t have this role directly assigned to my user. That's OK because we've actuallycreated this workshop role that grants us all the necessary access to do all the activities in the

Page 20: OpenSAP HANA1-1 Week 5 Transcripts

Page 20 Copyright/Trademark

workshop,

00:04:12 and when we drill into this workshop role you’ll notice that it actually has many roles assigned toit, many standard roles in some other ones that we’ve created, but it most importantly has thisdebugger role that our user will need in order to do debugging.

00:04:30 We then also need to create a debugger configuration. We want to do this once on our developermachine for each system that we’re connected to.

00:04:39 So this is very similar to creating the SQL script debugger configuration, but unlike the SQLscript debugger configuration, we don't have to put in the exact object that we’re debugging orinput parameters or anything like that.

00:04:54 Here we simply supply the system host name, the http port that your system is running on - andthat will be 80 - and then the instance number of your system, and then you supply theusername and password you want to debug under.

00:05:11 Now lets go into system and have a look at the creation of this debug configuration. So I'll comehere to the Debug button,

00:05:23 and choose Debug Configurations – you can see all the configuration types that we have listedhere - and I’m wanting to do server-side JavaScript, so I’ll just say New…

00:05:38 …I can name this configuration, and then I’ll give it my host name and then my port number - myinstance that I'm running on is actually instance 50, so my http port will be 8050 - and then myusername and password.

00:06:10 And then I’ll say Apply. At this point we could go ahead and start debugging, but we haven't setany breakpoints yet: we'll see all that in a moment. For now, just go ahead and close out thedebug configuration, and it’s ready for us as soon as we want to start debugging.

00:06:23 Once we start the debugger itself you'll see a screen just like the one in this presentation. This isthe standard Eclipse debugger, and it has many configurable features. For instance, you cancontrol whether you want to see the breakpoints, you want to view the variables, you want anoutline of the source code block that your debugging within,

00:06:45 and we'll see all this in action in the system in just a moment.

00:06:51 Now when we debug inside server-side JavaScript code we can go to the xsjs editor, so wesimply open one of our server-side JavaScript artifacts or an xsjs library file

00:07:05 and we set a breakpoint in the code or multiple breakpoints, and then we're ready to begindebugging.

00:07:13 When we start the debugger, it's going to ask us for a session ID. It will bring up a list of all thesession IDs that are currently active in the system for your user ID.

00:07:24 Now the little trick I will show you for getting this session ID is basically you go to your Webbrowser, and you use some form of developer tools in the Web browser to be able to get thesession ID, because it's displayed in a Web browser has a cookie.

00:07:39 So we'll see this session ID Cookie, we'll be able to match it up with one of the session IDs onthe server, and then we'll be able to start debugging.

00:07:50 From that point we’ll stop at our first breakpoint, we’ll have the ability to look at the variousvariables and their values, to stop and start the debugger, pause, resume, skip ahead to anotherbreakpoint - all the kinds of things you’d expect in an interactive debugger.

00:08:09 So once we’ve stopped at a breakpoint, or if we want to enable a breakpoint we can do this quitesimply, we can double-click in the little bar area in the left inside our editor,

00:08:22 that will toggle the breakpoint, or we can right mouse click in that same area and set the

Page 21: OpenSAP HANA1-1 Week 5 Transcripts

Page 21 Copyright/Trademark

breakpoint as well.

00:08:29 And once the debugger is running we have the ability to go to the Variables tab, and we can findvariables and a list of all the possible variables.

00:08:40 We also see our variable values, for instance here we have a query, and we’ll look at the valuethat’s in that query, and we even have the ability to change those variables during debug time.

00:08:52 And it’s often quite useful when debugging to change the values and see the impact that it hason the running program.

00:09:01 So let's go back to the HANA studio and see the debugger in action. So switch back over to theProject Explorer and go into the project we've been working in and to the Example1.xsjs servicethat we've built up so far

00:09:19 and it’s in this perform multiply function that I want to set some breakpoints and debug it. To setbreakpoints you can simply double-click in the little left and bar next to the line numbers

00:09:36 or you can right mouse click and choose toggle breakpoint. Let's go ahead and set a couple ofbreakpoints. We’re ready to debug. I can go and start the debugger, but like I said earlier the firstthing it will ask you for is a session ID,

00:09:53 and we want to go ahead and look up that session ID in the browser.

00:10:03 So a couple of things I want to do here; I want to first turn on the developer tools, so: Tools->Developer Tools. I’m doing this in Chrome.

00:10:14 Now I like the Chrome developer tools because they're built in; I don't need any additional add-ons or installations. Similar tools are available for all the other browsers, though.

00:10:28 So lets put in our path to the service: workshop session “a”, group 00, and servicesExample1.xsjs, and then the command Multiply, and my two input parameters num1 and num2.

00:11:06 There we are. Now I will go ahead and run that service and I see my results.

00:11:14 And if I click on that request and I look at the headers I can also see my session ID.

00:11:25 So here is this xsSessionID it begins B-F-D 830. I don't have to remember the whole thing, butthis is what I'm going to have to choose when I start the debugger.

00:11:37 So now, if I come back to the studio, I go to the Debug tab, and I’m going to go ahead and startthe debugger for the configuration I created previously.

00:11:50 You notice it comes up and it asks me, or gives me a list of session IDs for my user, and if I lookonce again, I want session ID B-F-D 830, already I can see, there’s that session.

00:12:09 This is the one I want to debug, so I’ll select that. And the debugger is now running. Now I don’tgo immediately into the debugger. Its obviously not until I trigger another request from the clientside that the debugger will start.

00:12:22 At this point I could go ahead and just do a refresh and now the debugger is running. You noticethat the browser is waiting, it’s running, it’s made a request to the server and it’s sitting andwaiting for the response.

00:12:34 The server has started execution of this XSJS service and it has stopped here on my firstbreakpoint.

00:12:41 Now at this point I can go ahead and step into, step over, so I can go to my next breakpoint, andwe see already here that num1 and num2 have values. I can see that in my variables - 5 and 10the two values that came in.

00:12:58 I can see that answer has a value of 50 and for instance here, I could change this value. I'veclicked on it and changed it and this should change the output result.

Page 22: OpenSAP HANA1-1 Week 5 Transcripts

Page 22 Copyright/Trademark

00:13:13 We can now step forward and the response is going to go back and in step return that exitscompletely out of the debugger and returns control to the desktop,

00:13:27 and there we see the answer 51, which is obviously not correct. 5 times 10 isn't 51 but we seethe impact we've had via the debugger.

00:13:37 Now I want to show you one additional way to debug, and that's using the SAP HANA Web-based Development Workbench.

00:13:45 So instead of starting in the HANA studio, we do have browser-based development tools as wellnow in SP6: we can do our editing, and we can also do our debugging of our server-sideJavaScript from here as well.

00:13:58 And it has one major advantage, is that because the tools are running in the browser as well, wedon't have to go and look up that session ID. The browser’s going to know that session ID andautomatically use it to debug the session that we’re currently in.

00:14:15 So the processes is rather similar. I don't have to create a debug configuration here either, Iwould simply go to my XSJS Service that I want to debug, and I would go ahead and set mybreakpoints,

00:14:38 and now I can say Execute in a new browser window, and it gets an invalid command there,that's OK.

00:14:48 I just wanted to do that to get the URL. I actually want to type the rest of the parameters on theURL, and I'll do that from a new browser tab.

00:15:01 So there's a our command Multiply, and you’ll notice it’s doing the same thing; it’s stopped, it’swaiting, and we’re now if we return to the Web browser-based Development tab,

00:15:16 you see that we have stopped on our breakpoint. And we have very similar tools and capabilitieshere; we see that I have the same Variable view, I can now, if I step forward a little bit.

00:15:34 Let’s just go and step forward, and now I have my two values ten and five, if I continue to stepforward I’ll see the multiplication into answers - there we get the results - 50

00:15:51 and if I continue processing - I’ll just go ahead and step out - and it’s finished processing, andwe see our results coming back. So very much the same tooling experience, very similar at leastto what we have in the HANA studio,

00:16:07 but a little simpler workflow, plus the advantage that you would not have to check out the projectin order to set the breakpoints and things like that; you can do everything from the Web browser.

Page 23: OpenSAP HANA1-1 Week 5 Transcripts

© 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.

www.sap.com