Monday, May 28, 2012

How to Align Managed Bean Scope and Bean Data Control in Oracle ADF

Bounded task flows are natural building blocks of modular Oracle ADF applications. A bounded task flow facilitates the isolation of specific implementation details in its own memory scope - a page flow scope. For example, a managed bean  in pageFlow scope has a lifespan of its bounded flow.

The other commonly used building blocks in ADF application are data controls and bindings. I assume, that readers are familiar with ADF facility of Bean Data Control: it is very easy to create one on any java class by doing Right-Click->Create Data Control on it.

This post shows a technique how to align a scope of java bean defined as manged bean in pageFlow Scope with an instance of the same bean exposed as bean data control.

The sample, available to download and run in JDeveloper R2, shows the technique and one particular  usage scenario of it.

Short description of the sample application 

An entry point to the sample is home.jsf.  The page contains a bounded task flow sample-task-flow, embedded as a region.  There are  two view activities defined in the sample-task-flow:  first and second. There is one method binding doSomethingUseful, which gets executed on transition between them:


Flow controller managed bean exposed as bean data control

One managed bean (Name: flowController, Scope: pageFlow) is defined in a sample-task-flow-definition.xml:

There is a property sampleValue and one method doSomethingUseful() in SampleFlowController.java:

The bean  flowController  is also exposed as (sparse) Bean Data Control:

Therefore , it can be used a declarative way and provides the same rapid design time experience ADF developers are likely familliar with.

The run time functionality provided by ADF Model, like currentRow and implementation of CollectionModel etc. is still available, so the combination of java and ADF enables to design highly modular service oriented view and controller layer and implement it using the strenghts of both approaches - declarative and java centric one.

The page first.jsff includes one element inputText bound to a sampleValue -  created by D&D:


The bindings section of the page definition ,created implicitly by JDeveloper:

The method doSomethingUseful() was dragged&dropped on a flow diagram, so an appropriate pageDefinition file was also created implicitly, which looks like this:
The page second.jsff doesn't contain a page definition. It is aimed to show, that the instance of  flowController managed bean and its attributes can be used directly "JSF" way.
We pick a value of bean attribute sampleValue in JDeveloper Expression Builder. The bean  flowController is accessible in a section ADF Managed Beans:

And a value expression of inputText element on a page looks like this:

Lets start the sample to have a look at behavior of it.

Running the sample 

Once we start it (run home.jsf), ADF managed bean facility creates an instance of flowControler managed bean in a flow scope. We provide some value for the inputText element:

Click on Go to the next  page and perform something useful  -  navigation case next to the second page is performed and a method doSomethingUseful() gets executed on a way to it.
The text on a second page is now converted to upperCase (it is aimed to show some useful functionality provided by the method):
We modify the text a little bit:
and press Go back to the first page. The result shows our modified value available on a first page:
It is supposed to show, that the scope of controller bean, defined as a managed bean in a page flow scope and exposed as bean data control is aligned.
The same instance of flowController bean is used, regardless of the way a bean is bound to some elements in a flow and pages of it.

Implementing flow scoped bean data control


To finish the post, i provide a complete source code (basically one line of code and one naming convention do the job) for the flow scoped data control  used in a sample.

The implementation of SampleFlowDataControl.java:

And a generic implementation of base class FlowScopedDataControlBase.java for all flow scoped data controls:


The sample JDeveloper R2 workspace is provided at github.

Sunday, May 13, 2012

Detecting emotions by using JSON and REST services in Oracle ADF

Developers using Oracle ADF to build applications most likely get in touch with ADF Business Components (exposed as Data Controls) first. The framework provides few other types of Data Controls out of the box , like URL Data Control, to facilitate an access to various data sources and services. There are plenty of services available on the Internet which are  based on REST protocol and JSON format  -  consuming them in ADF might be of interest.

The sample application consumes two external JSON+REST services in ADF by using URL Data Control.  It provides a Timeline of some twitter user visualized in ADF UI together with emotion, automatically detected in a message text:


The color and the sign  :)  stands for positive ,  :| for neutral,  :(  for negative emotion detected in a message text.

As one can see, the emotional state discovered in  tweets of twitter user named @ladygaga is quite versatile and shows user feelings changing during a day. Just to compare, the twitter user  @adf_emg seems to keep stable neutral emotional state for a longer period of time:


Let’s take a closer look at technical implementation of the sample. It is available to download and ready run in JDeveloper 11g R2.

Once executed  (Run home.jsf), it should display a page like this:


The response of REST+JSON services is displayed on the page. A panel on a right-side shows an output of TwitterTimlineService. The output of EmotionAnalyzerService for the current row (upon selection in a table) is displayed at a bottom of the page.

Of course, tweets of any public twitter user could be analyzed - just enter  a user name and press “show tweets” in case of interest.

Note: there is no special exception  handling in a sample app, so the results in case of network failure might not be pretty. In case of errors running it locally check your network settings (proxy settings in JDevleoper for example) and the name of twitter user entered - does it exists?

Using JSON+REST services as URL Data Controls

The sample consumes  two simple REST+JSON services as ADF URL Data Controls: Twitter TimelineService and FeelingAnalyzerService.

Readers interested  in Twitter API might find a test Console as good starting point to explore it. 

The FeelingAnalyzerService ,included  in a sample project, was kindly provided by Enrique López-Mañas. I came to his blog post "Flirting with sentimental analysis..."  by looking for some JSON-REST service suitable for ADF JSON-REST sample. Refer to Enrique in case you are interested in  “magic” which helps to turn computers to humans :) 

I proceed  with  description of this small “value added” solution showing how to integrate two REST + JSON services in ADF.

Three Data Controls are used in the sample:


POJO Data Control ShowTweetsPageAdapter,  built by doing a Right-Click -> Create Data Control in JDeveloper on ShowTweetsPageAdapter.java class, contains a method transformTwitterJSONString2Tweets:


The method  takes return value of TwitterTimelineService (tweets in JSON format), transforms the tweets from JSON format to domain model (TwitterTimeline POJO) and makes a call to FeelingsAnalyzerService (URL Data Control) in java for each Tweet to detect emotion in a message text.

The other two data controls, built by using Create URL Data Control wizard in Jdeveloper, provide one method called loadData,  which returns a single column (name Colum0 , type string) as a result:


URL Data Controls were configured to parse an output as CSV yet (JSON parsing support in ADF might come in a future release of ADF).

Let's take a look at the properties of TwitterTimelineService Data Control, which is built on a service statuses/user_timeline.json  creating  TwitterAPIConnection on a way by using Create URL Data Control wizard in JDeveloper.


Setting {tab} as Delimiter and Quotechar to {none} enables to get JSON output as single Column of type String.
The property Source points to a path of a service URL together with a query_string screenName. ##ScreenName## is a placeholder for  query value being supplied at run time.

TwitterApiConnection (created using JDeveloper Wizard together with URL Data Control) points to URL connection  in a Panel Application Resources (persisted in a file connections.xml):



The connection carries URL endpoint of Twitter API:

URL Data Control FeelingAnalyzer and URL connection FelinganalyzerApp  was created  in JDeveloper using the same technique.

Structure of the sample application


The application contains one default unbounded flow adfc-config with one page , called home.jsf as a container for  the bounded flow  tweets-task-flow-definition.xml, embedded as a region.
The flow tweets-taks-flow-definition.xml contains default view activity, named showTweets. A page fragment  showTweets.jsff carries a UI of the application and includes some EL expressions as inline-style to color it a little bit.

Three services (2 provided by URL Data Controls and one from Bean Data Control) are wired in a page definition of showTweets.jsff  declarative way.


Wiring service calls 

Readers familiar with ADF Bindings are already aware,  that a method Binding gets executed implicitly in case the return value of it is displayed on a page or consumed as an input value of some other method binding. Lets look at Bindings section of page fragment showTweets.jsff:





Column0 binds a return value of method loadData from TwitterTimelineService data control. It was created first by Draging a Column0 from Data Controls and dropping it to a page ( area on a right side in a sample application).

The second step was performed to transform a tweets from JSON string to a list of tweet domain objects. We continue with a D&D in order to display the list of Tweets on a page:



Drag&Drop a tweetList  on a page (ADF ReadOnly Table was chosen to display it). Editor Edit Action Binding shows up:



We need to provide a value for input parameter tweetsJsonString. So we can use a value of Column0 , which contains exactly what is needed here: tweets in JSON format as String.

Using Drag&Drop twice, both method calls (loadData of Twitter URL Data Control and transformTwitterJSONString2Twets of Bean Data Control) are wired declarative way to provide a list of Tweets on a page.

Emotions are still missing, so we  call a FeelingsAnalyzerService in order to detect them and enrich our tweets.

First, create a method binding by doing another D&D with  return value of FeelingsAnalyzerService service method loadData:


Drag the Column0  (selected in a picture) and drop it on a same page showTweets.jsff (bottom area in a sample application was chosen as a drop target). Edit Action Binding shows up. We provide a value for parameter of the method (it expects some text  in order to detect emotion in it):


The expression points to a currentRow of tweetListIterator.  The expression-part  dataProvider returns a POJO  behind a row, in our case it is an instance of java bean Tweet.java. The message is an attribute of the been, so this part of  EL resolves to method call tweet.getMessage() on instance of the been.

NOTE: because of ADF Table  “stamping” rows  into variable “row” (which is not available in bindings), this method is NOT executed  for each row when table is rendered. The current row points to the first row in iterator binding, the method gets executed  with a value of a message from a Tweet behind a first row.

The last step was therefore a preparation in order to call this method in java for each row (Tweet) and do it by using  method binding defined in a page definition.

Few lines of java code are used to achieve that. First we get an instance of method binding:

Second part is to provide an input value for a method call, execute it and retrieve the result:

The rest of the source code, included in  ShowTweetsPageAdapter.java, is basically used to deal with JSON parsing by leveraging the reference JSON parser implementation and to transform it to custom domain objects.

To finish the post, the summary provides a list of  ADF and JSF2 specific design features, used in the sample application.

Summary


  • “Twitter Timeline” designed as reusable component and implemented using ADF Faces bounded task flow with parameters.
  •  Functionality provided by ADF leveraged to consume two JSON+REST services a declarative way using ADF URL Data Control (CSV)  and Connections.xml
  • The functionality of JSON parsing, which is not (yet) available  as ADF Data Control , compensated  in  java (ShowTweetsPageController.java) by leveraging third party JSON parser.
  • The result of Twitter Timeline service enriched with emotions by calling a method binding of URL Data Control (which is based on external REST+JSON service) in java.
  • JSON output transformed to domain model and exposed to UI as a POJO Data Control.
  • A value stored in JSF2 @ViewScope used to provide an input to a task flow embedded as region.


The source code of it is available on github.

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.