REST framework for XPages (2)

In my previous post I announced the framework I’ve been building the last couple of weeks to implement REST services in xPages. In theory you can drag’n’drop a restcontrol on an xpage, bind the apibean to it and you are good to go.

But of course you still need to write code that handles the incoming request. In this post I will explain to you how a normal flow will be in the framework. We will use the demo application found on github (the project is also a demo app ).

A primer

First of all you need to create a new app from the source from github. You can do so by downloading the project and associate it with a new NSF (info) When you have done this please use the agent initialize agent to create the default keywords used by the application.

Next of you can go to index.php and you will be able to add measurements from your energy usage ( electricity / gas / water ). The application supports get, post, put and delete of the very simple measurement object.

All you see at the frontend is bootstrapped and pure javascript

The POST request

So what happens if you enter a date, a value and hit the save button? The framework will go through the following flow (warning! Huge image )

restframework

 

as you can see here a lot is going on. First of all the framework will search if there is a router object that can handle the current endpoint ( ie. /measurement ). If such an entry is found it will forward the request to this object.

This gives you the ability to concentrate the logic that belongs to that endpoint in a single tree of objects. Removing that tree won’t break the api framework only removes the endpoint. If implemented correct you dont end up with 4 methods ( get, post, put, delete ) in the base class (apibean) too handke lots of endpoints. Every endpoint has its own class tree.

Depending the mehod executing the input data is being parsed by the inputhandler object. This is by default a JSON object. The data is being validated ( not in the image ) by so called validators and if this all works out the dataservice object that is going to talk to domino / mysql / other db system is doing its job.

There are , as you can see , several layers where things are happening and the succes of 1 layer decides the flow of the other layers. If there is an error with parsing the request body the dataservice will not be accessed etc etc.

This concludes this post. I hope you have a little understanding of how the framework, at a very high level, does its thing. In the next chapter I will explain to you how to add a new endpoint to the application.

Stay tuned

 

REST Framework for xPages

A couple of weeks ago I wanted to pickup xPages again during my free time. So I created a little app and all worked well. But then for some reason I wanted to add Rest controls again ( as I did a couple of months ago ). This time I wanted to start of easy. First re-explore the workings again and eventually add a java backend to it.

This.. got a little out of hand ;). Instead of creating 1 simple API bean that handles a single type of entrypoint I decided to create a complete framework so that 1 rest control could be used to handle multiple endpoints. I’ve just added the project to github. The framework could do the following

  1. Finds out by itself (using config docs ) depending on the url it was triggered on what class ( ‘servlet’) to load
  2. Load the datastore for it ( IDataService ).
  3. Parses the input.
  4. Depending on the method type ( GET, PUT, POST, DELETE ) validates the input and executes the correct methods
  5. Sets the correct response code and returns data if needed ( with delete/put no data is returned

The great thing about this framework is that also contains simple validation. The framework should not be used in production at the moment but should be used as a bunch of code that shows how you COULD implement a REST API. It’s far from complete ( contains bugs… )

I will blog about the framework in the coming days to explain how it works and how you can modify it to adapt it to your own needs.

Small question regarding Dates and Rest services

To all the people out there who sometimes read my blogposts. What is , in your opinion the best way to represent dates when generating a REST api which returns JSON.

Is it time in milliseconds since epoch

Is it dd-mm-yyyy H:m:s:u ?

or is it mm-dd-yyyy H:m:s:u

or is it simple the ISO 8601 spec which will be something like

Year + “-” + Month + “-” + Day +”T” +Hours + “:” + Minutes + “:” + Seconds + “+01:00”

I’m more towards the ISO spec because its an ISO format and documented and so on but for now I just dont know for sure.. Any input would be helpfull.

RPC Calls ( and notes in 9) to the rescue

After a little downtime on the xPages departement I started to do some xPages again ( a few weeks ago ). Today I faced the following problem. We want to transfer data from one app to the other to generate Word documents using a xpage control. The problem is that the call is done in the ‘website’  database and the real logic is stored in the ‘data’  database. The word document is also generated clientside (don’t ask). So I needed to find a way to transfer data from one app to the other.

I first made the obvious error to set a sessionScope and to get that scope at the other application. But since scopes are not inherited (ofcourse..) that didn’t work. The thing I didn’t want was to add multiple url parameters to acccess the other database. So what’s next?

the Remote procedure call! A colleague told me that they are are using RPC’s all over the application currently and maybe that could be a solution. There was only one problem. I didn’t even know that was possible nowadays in xPages. So I first browsed the source to find the current RPC’s and started to create my own.. but all I’ve got was a call that did throw errors all over the place.

To resolve the issue I checked www.notesin9.com to see if there was someone who did a session in the past about RPCs. And yes there is. John Jardin, who is a great speaker by the way, did a vid about RPC’s. Its very basic but it’s just enough for me to get started!

What would xPages be without http://notesin9.com/ and John Jardin…?

SugarCRM: Logic hook default handlers

This post is a little tip for all those SugarCRM developer noobies out there ( including myself ). When you want to do field validation serverside or do some business calculations while saving the bean(s) you should use logic hooks ( more info here ). Logic hooks can hook into several stages of the applications/module’s process.

Something that I have found very useful is to create a default class for handling all specific events and to copy this file to the instance of the project. Therefore I only need to worry about the customer specific things I have to do. A skeleton class for the module logic hooks could look like this:

Now when you start a new project the only thing you need to do is to make a copy of the file and add it to the correct directory . For instance /custom/modules/Accounts/AccountLogicHookHandler.php

and rename the class in that file to AccountModuleLogicHookHandler. In your logic_hooks.php you need to add the following to get it working for the  before_save

And whenever you need to implement a new hook you only need to add the correct entry in the logic_hooks file and write the implementation. Easy as pie and saves a lot of time finding out which parameters each hook function has etc..

 

Happy coding!

xPages & Beer meeting Presentation

Last wednesday I did a presentation called “Coding Java for xPage Developers” on the Dutch XPages & Beer event. It has been a while since my last presentation so I was a quite a bit nervous. Especially when during the presentation people started to ask questions I didn’t really prepared for. But I managed and got some very nice and positive feedback afterwards.

In the presentation I talked about the techniques that are discussed in one of the best books I’ve ever read: Clean Code: A Handbook of Agile Software Craftsmanship and last but not least a little about the new domino java api

The slides are in dutch/english. If you want a full English version just let me know:

Debugging made easier

This tip is for those people who are using the Debug Toolbar from Mark Leusink. One of the nice things about this toolbar is the embedded logging. You can use logging by means of calling methods on a managed bean ( dbar ) or in your java code you can use the methods info,error,debug or warn. Each method writes log line to the debug (or the log db ) with the corresponding level.

Because in my current project I use this way of logging a lot and because I’m a lazy programmer I started to use code templates. In the Eclipse client it   is possible to predefine certain lines of code which are added to your editor when you type a shortcut followed by the key combo ctrl space.  The most common is the following: syso. This will be translated to System.out.println(). Obviously typing syso and hitting ctrl+space is lots quicker than typing the full line of code.

So I defined 4 new templates. dInfo, dError, dBug, dWarn. The steps to create a new template are :

1) File -> Preferences and type templates in the search box and click on Java ->Editor->Templates

templates_1

2) Press the new Button.

templates_4

3) Fill in a name (dBug, dInfo,dError or dWarn ) and past the following code

templates_3

DebugToolbar.get().info(this.getClass().toString()+”: “);

This will get an instance of the DebugToolbar class and add an info message to the log which contains the current class we are working in. *

4) Click ok, Apply, Ok and see if it works

5) Type dInfo ( or any of the other templates you created ) and hit ctrl+space. The code should be auto completed with the content you have specified in the previous step.

I hope you like this little tip. It makes your life as a developer a little easier !

 

 

 

*keep in mind that the ‘this’ keyword  wont work when you use it in a static method..

 

Hi,

after some down time I’m back again doing some xpages and I already seem to have forgotton to many things. I have the following code:

A datasource:

and a couple of comboboxes

as you can see nothing to fancy. But the problem is as that whenever I do change the value of the idLeagueList combobox and execute the changelistener ( aka it updates the viewscope ). It always retrieves the previous data. I thought I had sorted that out ages ago but apparently not. Can anyone help me out here?

Design patterns in xPages: The repository Pattern (some sort..)

For my current home project I’m busy exploring the Java side of xPages more and more because of my general love for this language. The project involves a little website that should display the current standings and results of hockey teams ( wheelchair hockey ) during the season.

A little feature list

– Support for seasons: Create seasons add teams to a season
– Support for teams: basic crud actions
– Support for competition days and games: basic crud actions
– A list of current standings and results: Realtime calculations for teams etc.

I wanted to use the objectdata datasource for this one. So I searched a bit on the net, remembered the splendid presention from Thimo Janssen and wrote a little code.

Because I didn’t want to fill my pojo’s with the code about how to read and save them I decided to write something called a Repository class. A Repository class is a class that knows all about saving/retrieving an object to and from an datasource for instance a Domino database!

This way we can keep the Object (pojo) itself neat and clean. Now for some code:

I’ll start by showing you the code for the xPage

In the above piece of code you can see the createObject and saveObject properties who are both using the same object called  “seasonService”. This service is the so called Repository class. As said this object is responsible for retrieving and saving an object to the database ( in this case Domino ).

Lets have a look at the code of the Repository Object.

The most important parts for now are the GET and the SET methods. As you can see the GET method is capable of retrieving an entry by Key or create a new object (and what you also see is that when an object by key is not found a new object is created… #bug!). If no key is provided a new empty instance of the season class is returned.

When a key is provided the code will do a getentrybykey search on a predefined view. With this retrieved entry the season object is constructed using the fromEntry method. The fromEntry method is there because on another place in the code we want to retrieve data using a view entry as well. Namely the getAll Method. This retrieves ALL season objects using a predefined key / view name and from every viewentry a season object is constructed. Because I’m lazy and don’t want to write / update the same code on several places I created the fromEntry method.

Secondly the SET method. The set Method accepts an Entity object ( because we defined an interface for the repository object. We will talk about them later in another post.. maybe ). At the beginnning we check if the given object is of type Season. If so we create or update the datastore ( aka the notesdocument ). The update takes place only when the object is not new in other words when a key ( uniqueid ) is provided in the object. If the object doesn’t have such a key we assume the object is new and create a new document and save it. When the save succeeds the universalid of the document is saved into the season object. At last the season object is returned.

This code is not perfect. For instance what to do when the update/save of the season creates an error? Should we throw an error or should we return a null reference to tell the ui the code made a booboo? Anyways.. all comes to an end so this will conclude this little post about Java and xPages. I will , when the project progresses add some more info about Java and xPages. In the meantime. Stay tuned!