Showing posts with label JSF2. Show all posts
Showing posts with label JSF2. Show all posts

Saturday, July 28, 2012

Building a Simple Chat Application with Active Data Service and JSF2 AJAX in Oracle ADF

Data push with Active Data Services (ADS) in Oracle ADF has been available for some years.

AJAX functionality has got attention in JSF2 specification. JSF2 made its way into ADF with JDeveloper Release2.

This blog post provides a simple ADF active Chat application, built by using active data service functionality together with ajax tag of JSF2.

Blog readers might find the sample, available to download and run in JDeveloper R2, useful to become familiar with basic functionality of active data service. Various active data configuration options (transport modes, delays) could be evaluated for specific networking environment by modifying adf-config.xml.

Let's have a look at the building blocks of the sample application in JDeveloper first:


Controller: unbounded flow adfc-config.xml with 2 views chat.jsf and login.jsf, one bounded task flow chat-task-flow-definition.xml, embedded into the container page chat.jsf as a region (chatPageDef.xml page definition contains region binding as a result).

Model: 2 java interfaces Chat.java and ChatListener.java, describing our chat model.

Implementation:  JSF2 annotated beans ChatBean.java and ChatListenerBean.java.

UI: page login.jsf and page fragment chat.jsff.

Web Content and run time behavior of chat sample application


A default unbounded task-flow, named adfc-config.xml contains two view activities: login and chat:
We start the sample by executing adfc-config.xml  (pick a login activity in default run configuration panel) - the page login.jsf gets displayed in a browser:
In my case, the default browser is Firefox, so I pick a username Firefox first and press the button Go to Chat -  Action chat behind the button gets executed - a control flow case chat leads us to the page chat.jsf.
Chat with one user might be boring, so i start browser Chrome, enter the URL, pick a name Chrome and join the Firefox in ADF active chat.

A snapshot of this (simulated) conversation is displayed in a picture:
I leave the browsers to wait for IE to show up and continue with description of the sample.

Note: this sample application is deployed and (probably) running at this location - give it a try.

Usage of af:activeOutputText and JSF2 f:ajax tag


The sample leverages only one ADF active data element - af:activeOutputText tag - to initiate partial refresh for three "conventional" elements on a page: tables containing chat messages and users and the text Alive:true.  

Note: ADF UI Pattern of using af:activeOutputText in combination with af:clientListener, javascript function  (and eventualy af:serverListener in case some server side functionality is involved) is well described in various blog posts and presentations by Lucas Jellema - for example the recent one provides a sample of how changes in a database can be "pushed" through all the layers up into UI. 


Early description of active data service related techniques used in this sample  was provided  in a blog posts Flexible ADS – Combining popups with ActiveDataService and ADF’s Active Data Service and scalar data (like activeOutputText) by Matthias Wessendorf.


This pattern leverages propertyChanged event of af:activeOutputText - propertyChanged  gets fired when value of activeOutputText changes (by a data push from server) because a background color of the text gets changed to "blue" for a moment to indicate a value change for the user.

Let's have a look at the page fragment chat.jsff (essential parts only - layout tags were stripped) how the tag activeOutputText and its event propertyChanged are used in this sample in conjunction with f:ajax tag (available since JSF2):

The tag activeOutputText with a value bound to the "active" property message from a bean chatListenerBean emmits propertyChange event. ActiveOutputText is wrapped by f:ajax tag, which is "interested" in this event:
event="propertyChange" . 

According to description of  f:ajax tag , the attribute render allows declaratively specify a list of components (as space delimited string of component identifiers) to be rendered on the client: render="t1 t2 ot1".

The combination of af:activeOutputText and f:ajax allows to refresh all non active components upon data push from a server declarative way. There is no need to write any JavaScript for this particular usage scenario.

Note: well... no need for any specific JavaScript. There are 2 "strange" tags without particular meaning on a page - see the comments like  "this tag does nothing"  and "anonymous javascript function onevent does nothing". 
Actually, they just have to be there  - nothing else. I didn't figure out exactly why  - otherwise ADS didn't work for me. 

Let's go to the model part of the sample.

Defining a model for the chat


Two simple interfaces define a model: Chat and ChatListener.

The idea expressed in Chat interface is to accept a login or logout of ChatListener, to provide a list of current users (getUsers) and messages (getMessages) and one method addMessage(String message) to broadcast a new message to the listeners:

The idea of ChatListener is to be able to identify itself by a user name, receive new messages (as propertyChanged events in this case) and to provide a possibility for the chat to check, if the listener is not gone (isAlive). Note:  The readers might advance the model and extend it for their needs in case of interest.

Implementing the model as JSF2 beans


The idea behind the implementation was to leverage a JSF managed beans and their scopes. Our chat is intended to be there for everyone, so ApplicationScope is a natural  fit for it.

ChatListener can come and go, so ViewScope was selected for that.

JSF2 annotations were used in a sample to define manage beans and their scopes and inject their property values.

There is also a reasonable amount of comments in the source files describing specific details.  

Developer's Guide for Oracle Application Development Framework - 45 Using the Active Data Service  provides a comprehensive description about Active Data Service and configuration options of it.

To finish this section I provide a complete source:
Source of ChatListenerBean (imports stripped, active data service part is based on the description in this blog.)
And the Source of ChatBean (imports and header stripped):

Conclusion

Server side data push can be considered a little bit challenging due to the nature of connectionless HTTP protocol. 

Oracle ADF provides a built-in implementation for the data push taking care about the challenging aspects of it. By using simple principles described or referenced in this blog post, "non-active" parts of UI could be "activated", like in the sample chat application. 

Ongoing efforts in HTML5 address this issue by providing a connection-oriented WebSocket. Once the standards behind HTML5  are widely accepted and implemented - the architecture of web applications will probably shift  (back)  to the client-server, bringing new(old) possibilities for developers of active applications.

Que Sera, Sera (Whatever Will Be, Will Be) - there is no need to wait for the future - the data push functionality provided by Oracle ADF is ready to use now :)

Tuesday, May 1, 2012

Using JMX Data Control in Oracle ADF to manage users in Weblogic LDAP

One of key concepts in Oracle ADF is a binding layer and Data Controls. In this post the readers are going to  find an example usage of:
  • ADF JMX Data Control used to create a user in Weblogic server embedded LDAP  a declarative way.
  • Custom JSF2 exception factory and handler implementation to handle exceptions coming from JMX MBean and JMX ADF Data Control
Some basic features of ADF built-in easy to configure authentication and authorization are also touched in the post.

Use case “User Registration”

The application, available to download  and run in JDeveloper R2,  implements a simplified use case “User Registration”. It contains one secured page protected by configuring ADF security in order to test a login of a user after successful registration:

Two links are displayed on a home page:
 The first link navigates to user registration form:
One click on Submit registration - new user with a given name and password is going to be created in Weblogic embedded LDAP Server:
Well, something went wrong. In this case, password validation policy (deep in Weblogic security configuration) is not satisfied, so we modify a new password (testpassword1) according to the policy and give another try. New user is created successfully:

Following the links Go home and Go to protected area (from home page)  we can try to access a protected area now, by using credentials of a user created in a previous step:

The expected result is a successful authentication and access granted to the area, protected by ADF Security (which is based on JAAS):
 Let’s take a look into Weblogic default security configuration. Open a integrated Weblogic Administrative Console , for example direct from JDeveloper like this:
We can find our user in Weblogic console (Security Realms > myrealm > Users  and Groups):

Please refer to Weblogic Server documentation for further information about security configuration and security concepts of it.

The steps used to create a sample application in JDeveloper (fast forward)

Start JDeveloper, create a new Custom Application named UserRegistrationApp with project named JMXDataControlSample, create Java (bean) class UserBean.java with properties username and password, note a usage of  @ManagedBean configured in a @ViewScope (one of new JSF2 scopes). 
Create ADF bounded Task Flow named register-user-task-flow-definition.xml. The unbounded task flow adfc-config.xml is created implicitly.
As a further step, three views were created by D&D and wired like this:
A view home (page home.jsf)  in unbounded task flow adfc-config.xml serves as an entry point.

A control flow case protected navigates to a page, protected by ADF Authentication and Authorization. An access to protected page is granted to authenticated-role (one of built-in roles provided by Oracle Platform Security Services). HTTP Basic Authentication was chosen in JDeveloper wizard Configure ADF Security.

The page named protected is aimed to show a secured area protected by ADF security, so an empty page definition was created by doing right-click on it and selecting “Go to Page Definition” in a context menu. Pages with a page definition are automatically protected by ADF security once it is enabled, so  view access for other pages and user registration flow was granted to to anonymous-role.

The page registerUser is a container for a bounded task flow register-user-task-flow-definition.xml  (embedded as a region doing D&D) to provide a user registration form.   

Register User task flow

A bounded task flow register-user-task-flow-definition.xml  contains one view with a page fragment userRegistrationForm.jsff  to display new user registration form.
Basic layout was used to put it into a shape together with input fields bind to attributes of UserBean and buttons for an appropriate actions.

Control flow case submitRegistration navigates to method binding createUser provided by the JMX Data Control.  The following chapter describes a steps used to create it in more detail.

Creating JMX Data Control to access embedded LDAP server in Weblogic

NOTE: start integrated Weblogic and check if it is up and running before doing the following steps.

In JDeveloper menu File -> New choose a JMX Data Control in a New Gallery:

Click on Ok. The editor Define JMX Data Source shows up:
 Click on + icon (Add) to add JMX Connection:
 Provide a name for a connection (localWeblogic) , check the Port ( 7101 in this case) , check if integrated Weblogic is running - start it otherwise. Check the connection by click on Test Connection. Ok, Next. Step 2 : Editor “Choose Fully Qualified MBeans “is displayed:
 Choose myrealmDefaultAuthenticator and add it to Selected panel like displayed in a picture.  Attention: pick myrealmDefaultAuthenticator from DefaultServer tree-node (there is also one with the same name a level higher at Security node), otherwise you will get NPE at run time.

Other JMX MBeans of Weblogic server are also listed and accessible this way. Refer to documentation of Weblogic server , like Developing Custom Management Utilities with JMX, for the further description and the usage of them.

Next: default settings were taken for all next steps.  We have got a new JMX Data Control as the result:
 The operation createUser is available for D&D in ADF.  Of course, all  other operations provided by MBean can be used  the same way, for example to integrate user management functionality (addMemberToGroup, changeUserPassword etc.)  into a custom  ADF application.

As referenced  in James Bayer blog, the embedded Weblogic LDAP can be used to manage a “reasonably small environments (10,000 or fewer users)”. 

The usage of JMX Data Control  is also described in a blog of Edwin Biemond. One comment in the blog points to some problems related to Weblogic embedded LDAP access, so i proceed with description of my sample application in order to show how to achieve that.

Drag a method createUser and drop it on a flow diagram of register-user-task-flow-definition.xml. The following dialog shows up:

Note: we need to type value expressions for input parameters manually (unfortunately, EL Expression Builder in JDeveloper R2 leaks at this place yet - our bean is not visible in it):
  •  userName: #{userBean.username}
  • password: #{userBean.password}
  • description: static text was used in a sample..
Click on OK and open the page definition with bindings for createUser  (JDeveloper created it behind the scenes).  It is supposed to look like this (after doing a D&D):

Action binding createUser  points to a method iterator myrealmDefaultAuthenticatorIterator which  points to our JMXDataControl.
There is one additional iterator in a Panel Executables: createUserIterator.
Delete it :) Otherwise the operation createUser gets executed twice.

The section bindings and executables should  look like this:

 By doing these steps we integrated some functionality of JMX Provider (embedded LDAP server in Weblogic)  in ADF declarative way.

Dealing with exceptions

New  facility provided by JSF2 (described in blog post JSF2 global exception handling) was used to create and configure a global exception handler in a sample application to deal with ADF-specific exceptions thrown by JMX Data Control.
Especially, in our sample use case the information transported by exception is also meaningful for users: password validation rules etc.
The source code of CustomExceptionHandlerFactory.java together with comments provides  additional implementation details.

JSF2 custom exception handler factory is configured in faces-config.xml:


Global exception handling provided by JSF2  is  powerful option worth to explore and consider in ADF applications (from JDeveloper R2) in order to consolidate the application specific error processing at a single global place.


The sources of sample application are available at github to explore, modify and use for your specific project needs.

Wednesday, April 11, 2012

Set Initial Focus component for Oracle ADF Faces

Oracle ADF Faces components provide rich functionality out of the box. One small feature is missing somehow:
a convenient way to set initial focus on input component.

For the inpatient readers: sample workspace to download and start with JDeveloper 11.1.2.1
(11g Release 2) containing a custom tag <adfExt:setInitialFocus/> and a sample usage of it.

<adfExt:setInitialFocus/> features:
  • Drag and Drop usage  from Control Palette in JDeveloper: ADF Extensions -> Set Initial Focus
  • Drop on editable components, like inputText etc.
  • Handles multiple usage of the tag - initial focus is placed on first input component rendered in a view
  • Handles submit on a same view - the focus should stay where it is
  • Handles  properties readOnly, disabled, visible of input component.
    Initial focus doesn't provide much value in case an input component is not visible or read only.
  • Works with regions and therefore with components reused multiple times
The implementation takes advantage of JSF2 (JDeveloper R2)  features like facelets tag library, @FacesBehavior annotation and Behavior API.

NOTE: The principles of implementation can be successfully applied in a previous versions (11g R1 with JSF 1.x) , feel free to take a code and adapt it to your needs.

Steps to get the tag into your web project and use it in JDeveloper Component Palette (directory structure of a sample web project is assumed):
  1. Copy the file SetInitialFocusBehavior.java  (implementation of the tag) into your project.
  2. Copy the file adfExt.taglib.xml (facelets tag library with a definition of it) into WEB-INF\resources directory 
  3. Add the following context parameter  into web.xml:

Check if tag library is present in JDeveloper Project Properties:

Once configured, a new library ADF Extensions should be available in JDeveloper Component Palette:

There is one component in a library:


Drag and Drop it on some input component, like af:inputText:



Once the page is rendered, a cursor should be placed on that component:

Lets take a closer look to the use case of "Set Initial Focus" component.


User experience

A user opens an input form (built with ADF Faces) to enter some data. The cursor is placed on first editable field, so he can proceed using a keyboard instead of grabbing a mouse first.  After initial focus is set, the user takes a control on cursor position. Once the user took a control and started to navigate ( using TAB or arrow keys), he can finish his work and submit a data entered.


Note: the first input field might not always be the case  - a developer might choose the most suitable component to set initial focus on, based on specific requirements. 


Developer experience 

A software developer might expect to mark a component as a candidate for the initial focus with almost no effort:
  • set a property on appropriate component (initialFocus = true)
    or
  • Drag a control, like "Set Initial Focus" from a component palette in JDeveloper and drop it on the input component of a page.

Implementation challenges

ADF is designed for reusability, especially the bounded task flows facilitate that. One of the challenges covered in this blog post  from Frank Nimphius is related to the naming containers and the naming path: it is not always a case to know it in advance. It results in difficulties to locate a component in Javascript.
Reusable components are (and shouldn't be) not aware about a usage context of them. The simplest way to set a focus is on the other hand to call a Javascript function focus() on component once it has been rendered. We need to get an instance of component in Javascript, therefore need a client Id in order to find it.

ADF Faces provide a build-in AJAX functionality to reload  parts of a page. The implementation using Javascript has to take care about it. In case of partial refresh, a user is still on a same page and doesn't expect the cursor to jump away (see the blog post from Edwin Biemond and the first comment on it).

Addressing the challenges

The implementation of <adfExt:setInitialFocus/> tag is aimed to address the issues described in order to provide an experience  users and developers expect. Some new features provided by JSF2 are used.

One of the features used is Behaviour. See the blog post Das Behavior API with a description of it (oups - it is german link, sorry -  I took a notice about a language only reviewing a post. I leave the link  - modern browsers offer built-in translation, so it helps to google for additional resources in case of interest). My expectation on ClientBehaviour was to get an access to the clientId of component in java code. I'm not sure, if its by design, but one might expect that in case a ClientBehaviour tag is attached, the ADF Faces component renders also a client-peer of it. In that case, there is no need to set a "client Component=true" every time you use initial focus tag. The implementation and my simple tests met the expectation. Drop me a line in case you are familiar with internals of ADF Faces in relation with  ClientBehavior.

Facelets in JSF2 allows to build a tag libraries with ease, so it was selected to provide initial focus functionality for developers as custom tag.

The sources of sample project and implementation are available on public Github repository. In case someone might want to extend, rewrite or fix some issue - it is aimed to facilitate that.

It would be nice to get a feedback on usage of the tag - does it behave in your environment like expected?

To finish the post, a snippet of the source provides the rest of implementation details: