Friday, June 11, 2010

Dynamic Regions with Task Flow in Jdeveloper 11G

I made a new dynamic region example but now build with the JDeveloper 11G production release. In this project I have a jsf page which has a Tree and a dynamic region. This example uses the the department and employee tables of the HR demo schema.
Here are some pictures of the result.


These are the steps I did to get this result.
First I used the ADF Business Components wizard the fill the model project. I changed the Application Module so the tree has its own iterators.

Create a new JSF template in the viewcontroller project with 2 facets definitions. In this template I add a panel splitter with two facet ref's.
Open the adfc-config and create a view called mainPage to the Task Flow. Select the view and create the jsf page based on the just created template.
Drag the departmentsViewTree viewobject from the datacontrol to the Tree facet of the jsf page and select the ADF Tree option.

Also add the EmployeeTreeView to the tree binding.
Create two task flows called employee-task-flow-definition and department-task-flow-definition.

First we open employee-task-flow-definition where we add a view and we also drag the SetCurrentRowWithKeyValue operation of the employeesView to the task flow. ( do this from the datacontrol). Next we add a control flow case between the SetCurrentRowWithKeyValue method and the view. Make sure you set the SetCurrentRowWithKeyValue method as the default activity ( so it fires when the region is loaded).

It looks a bit strange to add an SetCurrentRowWithKeyValue operation in the Task Flow to lookup the right employee because in JDeveloper 10.1.3 we used an invoke action in the page definition to fire the SetCurrentRowWithKeyValue operation on an iterator. Invoke action in JDeveloper still works but has some side effects.
Select the employee_region view and create the JSF page fragment. In this page fragment we can drag the employeesView from the datacontrol and select a read only form option.
The last step is to add an input parameter to the Task Flow so this parameter can be used by the SetCurrentRowWithKeyValue method.

Select the SetCurrentRowWithKeyValue method and go to the page definition of this task flow method, where we will use the input parameter value.


Do the same with the department task flow.
Go the main jsf page where we will drag the employee or department Task Flow to the body facet of the main jsf page. We will get an option if we want to create a dynamic region.

JDeveloper gives you the option to create a new backing bean where it will add the necessary code for the dynamic region. Here the code of the backing bean.
  1. package nl.ordina.view.backing;  
  2.   
  3. import oracle.adf.controller.TaskFlowId;  
  4. public class MainPageBean {  
  5.     private String taskFlowId = "/WEB-INF/employee-task-flow-definition.xml#employee-task-flow-definition";  
  6.   
  7.     public MainPageBean() {  
  8.     }  
  9.   
  10.     public TaskFlowId getDynamicTaskFlowId() {  
  11.         return TaskFlowId.parse(taskFlowId);  
  12.     }  
  13.   
  14.     public String employeeRegionLayout() {  
  15.         taskFlowId = "/WEB-INF/employee-task-flow-definition.xml#employee-task-flow-definition";  
  16.         return null;  
  17.     }  
  18.   
  19.     public String departmentRegionLayout() {  
  20.         taskFlowId = "/WEB-INF/department-task-flow-definition.xml#department-task-flow-definition";  
  21.         return null;  
  22.     }  
  23. }  

We have to change this backing bean scope to session or application. Open the adfc-config for this

Now we can change the tree in the mainpage so the right key is passed on and the right region is activated. We use a switcher and setActionListener for this. The setActionListener copies the department or employee Id to a pageflowscope variable. The value is passed on to the input parameter of the region task flow. ( This happens in the page definition of the main page)
  1. text="Department Employee Tree">  
  2.   value="#{bindings.DepartmentsViewTree.treeModel}"  
  3.            var="node"  
  4.            selectionListener="#{bindings.DepartmentsViewTree.treeModel.makeCurrent}"  
  5.            rowSelection="single">  
  6.     name="nodeStamp">  
  7.           facetName="#{node.hierType.viewDefName}">  
  8.             name="nl.ordina.model.dataaccess.DepartmentsView">  
  9.               text="#{node}"  
  10.                               action="#{MainPage.departmentRegionLayout}">  
  11.                 from="#{node.DepartmentId}"  
  12.                                       to="#{pageFlowScope.TreeKey}"/>  
  13.                 
  14.               
  15.             name="nl.ordina.model.dataaccess.EmployeesView">  
  16.               text="#{node}"  
  17.                               action="#{MainPage.employeeRegionLayout}">  
  18.                 from="#{node.EmployeeId}"  
  19.                                       to="#{pageFlowScope.TreeKey}"/>  
  20.                 
  21.               
  22.             
  23.       
  24.     
  25.   

The last step is to change the page definition of the main page. Where we need to change the refresh conditions and the value of the inputparameter. This inputparameter has to have the same name as the inputparameter name of the region task flows.


We are finished. Here you can download the project
Friday, February 26, 2010

Play with try-catch-finally blocks

Okay, let's try that out with few interesting programming scenarios. You'll find few code-snippets below and you may like to figure out the corresponding outputs to see how many of them you actually hit correct :-) Hope you get all of them right!

Scenario #1: try throwing an exception; catch and finally both having return statements




public class TestFinally {

/**
* @param args
*/
public static void main(String[] args) {

System.out.println("Inside main method!");
int iReturned = new TestFinally().testMethod();
System.out.println("Returned value of i = " + iReturned);

}

public int testMethod(){

int i = 0;
try{
 System.out.println("Inside try block of testMethod!");
 i = 100/0;
 return i;
}catch(Exception e){
 System.out.println("Inside catch block of testMethod!");
 i = 200;
 return i;
}
finally{
 System.out.println("Inside finally block of testMethod!");
 i = 300;
 return i;
}
}
}


Output: a return (or any control transfer for that matter) in finally always rules!




Inside main method!
Inside try block of testMethod!
Inside catch block of testMethod!
Inside finally block of testMethod!
Returned value of i = 300


Scenarios #2: try having exception-free code and a return; catch and finally both have return




...
try{
System.out.println("Inside try block of testMethod!");
i = 100;
return i;
}catch(Exception e){
System.out.println("Inside catch block of testMethod!");
i = 200;
return i;
}
finally{
System.out.println("Inside finally block of testMethod!");
i = 300;
return i;
}
...


Output: did you get the first one right? This is a cakewalk then. With the same logic that any control transfer in finally always rules we can easily predict the output to be similar to that of Scenario #1 with the only difference that in this case the catch block won't be executed as no exception thrown... all right? Here is the output:




Inside main method!
Inside try block of testMethod!
Inside finally block of testMethod!
Returned value of i = 300


Scenario #3: try having exception; finally doesn't have a return




...
try{
System.out.println("Inside try block of testMethod!");
i = 100/0;
return i;
}catch(Exception e){
System.out.println("Inside catch block of testMethod!");
i = 200;
return i;
}
finally{
System.out.println("Inside finally block of testMethod!");
i = 300;
//return i;
}
...


Output: no return in finally means whatever executable return encountered on the way to finally will be executed once finally completes its execution, so the output would be:




Inside main method!
Inside try block of testMethod!
Inside catch block of testMethod!
Inside finally block of testMethod!
Returned value of i = 200


Scenario #4: try and catch both having exception; finally having a return




...
try{
System.out.println("Inside try block of testMethod!");
i = 100/0;
return i;
}catch(Exception e){
System.out.println("Inside catch block of testMethod!");
i = 200/0;
return i;
}
finally{
System.out.println("Inside finally block of testMethod!");
i = 300;
return i;
}
...


Output: control transfer in finally overrules the exceptions thrown in try/catch, hence the output would be:




Inside main method!
Inside try block of testMethod!
Inside catch block of testMethod!
Inside finally block of testMethod!
Returned value of i = 300


Scenario #5: try and catch both having exception; finally NOT having any return




...
try{
System.out.println("Inside try block of testMethod!");
i = 100/0;
return i;
}catch(Exception e){
System.out.println("Inside catch block of testMethod!");
i = 200/0;
return i;
}
finally{
System.out.println("Inside finally block of testMethod!");
i = 300;
//return i;
}
...


Output: since no return in finally, hence after the execution of the finally block the sheer need to have an executable return statement (which doesn't exist in this case as catch also has an exception) would throw the exception encountered right before the finally execution started, which would be the exception in catch block in our case...right? So, the output would be:




Exception in thread "main" java.lang.ArithmeticException: / by zero
 at TestFinally.testMethod(TestFinally.java:24)
 at TestFinally.main(TestFinally.java:10)
Inside main method!
Inside try block of testMethod!
Inside catch block of testMethod!
Inside finally block of testMethod!


Scenario #6: try, catch, and finally all three having exceptions




...
try{
System.out.println("Inside try block of testMethod!");
i = 100/0;
return i;
}catch(Exception e){
System.out.println("Inside catch block of testMethod!");
i = 200/0;
return i;
}
finally{
System.out.println("Inside finally block of testMethod!");
i = 300;
return i/0;
}
...


Output: evidently the exception would be thrown, but which one? The one which was encountered last i.e., the one encountered in the finally block. Output would be:




Inside main method!
Inside try block of testMethod!
Inside catch block of testMethod!
Inside finally block of testMethod!
Exception in thread "main" java.lang.ArithmeticException: / by zero
 at TestFinally.testMethod(TestFinally.java:30)
 at TestFinally.main(TestFinally.java:10)


Scenario #7: try and catch both fine; finally doesn't have any return




...
try{
System.out.println("Inside try block of testMethod!");
i = 100;
return i;
}catch(Exception e){
System.out.println("Inside catch block of testMethod!");
i = 200;
return i;
}
finally{
System.out.println("Inside finally block of testMethod!");
i = 300;
//return i;
}
...


Output: well... first thing first. If try is fine, do we need to even think about catch? A BIG No... right? Okay, so we have try and finally blocks to focus on. Let me first show you the output and then we would discuss if you have any doubts. Here is it:




Inside main method!
Inside try block of testMethod!
Inside finally block of testMethod!
Returned value of i = 100
Monday, February 8, 2010

Handling exceptions in Struts 2

Struts 2 provides a declarative exception handling mechanism that can be configured globally (for an entire package), or for a specific action. This capability can reduce the amount of exception handling code necessary inside actions under some circumstances, most notably when underlying systems, such as our services, throw runtime exceptions (exceptions that we don't need to wrap in a try/catch or declare that a method throws).
To sum it up, we can map exception classes to Struts 2 results.
The exception handling mechanism depends on the exception interceptor. If we modify our interceptor stack, we must keep that in mind. In general, removing the exception interceptor isn't preferred.
Global exception mappings
Setting up a global exception handler result is as easy as adding a global exception mapping element to a Struts 2 configuration file package definition and configuring its result. For example, to catch generic runtime exceptions, we could add the following:



This means that if a java.lang.RuntimeException (or a subclass) is thrown, the framework will take us to the runtime result. The runtime result may be declared in an element, an action configuration, or both. The most specific result will be used. This implies that an action's result configuration might take precedence over a global exception mapping.
For example, consider the global exception mapping shown in the previous code snippet. If we configure an action as follows, and a RuntimeException is thrown, we'll see the locally defined runtime result, even if there is a global runtime result.


/WEB-INF/jsps/ch9/exceptions/except1-runtime.jsp

...
This can occasionally lead to confusion if a result name happens to collide with a result used for an exception. However, this can happen with global results anyway (a case where a naming convention for global results can be handy).
Action-specific exception mappings
In addition to overriding the result used for an exception mapping, we can also override a global exception mapping on a per-action basis. For example, if an action needs to use a result named runtime2 as the destination of a RuntimeException, we can configure an exception mapping specific to that action.


...
As with our earlier examples, the runtime2 result may be configured either as a global result or as an action-specific result.
Accessing the exception
We have many options regarding how to handle exceptions. We can show the user a generic "Something horrible has happened!" page, we can take the user back and allow them to retry the operation or refill the input form, and so on. The appropriate course of action depends on the application and, most likely, on the type of exception.
We can display exception-specific information as well. The exception interceptor pushes an exception encapsulation object onto the stack with the exception and exceptionStack properties. While the stack trace is probably not appropriate for user-level error pages, the exception can be used to help create a useful error message, provide I18N property keys for messages (or values used in messages), suggest possible remedies, and so on.
The simplest example of accessing the exception property from our JSP is to simply display the exception message. For example, if we threw a RuntimeException, we might create it as follows:
throw new
RuntimeException("Runtime thrown from ThrowingAction");
Our exception result page, then, could access the message using the usual property tag (or JSTL, if we're taking advantage of Struts 2's custom request processor):

The underlying action is still available on the stack—it's the next object on the value stack. It can be accessed from the JSP as usual, as long as we're not trying to access properties named exception or exceptionStack, which would be masked by the exception holder. (We can still access an action property named exception using OGNL's immediate stack index notation—[1].exception.)
Architecting exceptions and exception handling
We have pretty good control over what is displayed for our application exceptions. It is customizable based on exception type, and may be overridden on a per-action basis. However, to make use of this flexibility, we require a well-thought-out exception policy in our application. There are some general principles we can follow to help make this easier.
Checked versus unchecked exceptions
Before we start, let's recall that Java offers two main types of exceptions—checked and unchecked. Checked exceptions are exceptions we declare with a throws keyword or wrapped in a try/catch block. Unchecked exceptions are runtime exceptions or a subclass.
It isn't always clear what type we should use when writing our code or creating our exceptions. It's been the subject of much debate over the years, but some guidelines have become apparent.
One clear thing about checked exceptions is that they aren't always worth the aggravation they cause, but may be useful when the programmer has a reasonable chance of recovering from the exception.
One issue with checked exceptions is that unless they're caught and wrapped in a more abstract exception (coming up next), we're actually circumventing some of the benefits of encapsulation. One of the benefits being circumvented is that when exceptions are declared as being thrown all the way up a call hierarchy, all of the classes involved are forced to know something about the class throwing the exception. It's relatively rare that this exposure is justifiable.
Application-specific exceptions
One of the more useful exception techniques is to create application-specific exception classes. A compelling feature of providing our own exception classes is that we can include useful diagnostic information in the exception class itself. These classes are like any other Java class. They can contain methods, properties, and constructors.
For example, let's assume a service that throws an exception when the user calling the service doesn't have access rights to the service. One way to create and throw this exception would be as follows:
throw new RuntimeException("User " + user.getId()
+ " does not have access to the 'update' service.");
However, there are some issues with this approach. It's awkward from the Struts 2's standpoint. Because it's a RuntimeException, we have only one option for handling the exception—mapping a RuntimeException to a result. Yes, we could map the exception type per-action, but that gets unwieldy. It also doesn't help if we need to map two different types of RuntimeExceptions to two different results.
Another potential issue would arise if we had a process that examined exceptions and did something useful with them. For example, we might send an email with user details based on the above exception. This would amount to parsing the exception message, pulling out the user ID, and using it to get user details for inclusion in the email.
This is where we'd need to create an exception class of our own, subclassed from RuntimeException. The class would have encapsulated exception related information, and a mechanism to differentiate between the different types of exceptions.
A third benefit comes when we wrap lower-level exceptions—for example, a Spring-related exception. Rather than create a Spring dependency up the entire call chain, we'd wrap it in our own exception, abstracting the lower-level exception. This allows us to change the underlying implementation and aggregate differing exception types under one (or more) application-specific exception.
One way of creating the above scenario would be to create an exception class that takes a User object and a message as its constructor arguments:


package com.packt.s2wad.ch09.exceptions;
public class UserAccessException extends RuntimeException {
private User user;
private String msg;
public UserAccessException(User user, String msg) {
this.user = user;
this.msg = msg;
}
public String getMessage() {
return "User " + user.getId() + " " + msg;
}
}


We can now create an exception mapping for a UserAccessException (as well as a generic RuntimeException if we need it). In addition, the exception carries along with it the information needed to create useful messages:
throw new UserAccessException(user,
"does not have access to the 'update' service.");
"Self-documenting" of code could be made even safer, in the sense of ensuring that it's only used in the ways in which it is intended. We could add an enum to the class to encapsulate the reasons the exception can be thrown, including the text for each reason. We'll add the following inside our UserAccessException:
 

public enum Reason {
NO_ROLE("does not have role"),
NO_ACCESS("does not have access");
private String message;
private Reason(String message) {
this.message = message;
}
public String getMessage() { return message; }
};
We'll also modify the constructor and getMessage() method to use the new Reason enumeration.
public UserAccessException(User user, Reason reason) {
this.user = user;
this.reason = reason;
}
public String getMessage() {
return String.format("User %d %s.",
user.getId(), reason.getMessage());
}

 
Now, when we throw the exception, we explicitly know that we're using the exception class correctly (at least type-wise). The string message for each of the exception reasons is encapsulated within the exception class itself.
throw new UserAccessException(user,
UserAccessException.Reason.NO_ACCESS);
With Java 5's static imports, it might make even more sense to create static helper methods in the exception class, leading to the concise, but understandable code:
throw userHasNoAccess(user);
________________________________________