Showing posts with label ADF. Show all posts
Showing posts with label ADF. Show all posts

Tuesday, December 1, 2009

To Restrict Resizing of ADF Table's column


<af:column sortable="true"headerText="#{bindings.EmployeesView1.hints.EmployeeId.label}" id="c12" align="center"
minimumWidth="100" partialTriggers="::t1">

<af:outputText value="#{row.EmployeeId}"
id="ot11">

<af:convertNumber groupingUsed="false"

pattern="#{bindings.EmployeesView1.hints.EmployeeId.format}"/>

</af:outputText>

<af:clientListener method="setColumnWidth"
type="propertyChange"/>

<af:serverListener type="server"
method="#{yourBackinbean.serverL}"/>

</af:column>

and your javaScript will be:

<af:resource type="javascript">

function setColumnWidth(event) {

var source = event.getSource()

source.setWidth("100px");

AdfCustomEvent.queue(source,"server", {}, false);

}

</af:resource>

and your method in backingbean will be :

public void serverL(ClientEvent clientEvent) {

RequestContext.getCurrentInstance().addPartialTarget(clientEvent.getComponent().getParent());

}





Hint : If you know how to refresh the table from javaScript
you don't need a serverListener

Tuesday, August 4, 2009

Doubts related to JavaScript

go through
http://thepeninsulasedge.com/frank_nimphius/adf-faces-rich-client-javascript-programming/

Thursday, June 18, 2009

How to Implement Dependent Drop Down List in ADF

In this How-to example, I am going to explain, how dependent drop down list can be implemented in ADF.

Here I am creating two drop down lists "Department" and "Employee".
On selecting department, the list of employees will change.


I am assuming that you have sample HR schema installed in your database.

Create View Object DepartmentListVO for Department SelectItems.
Query: Select department_id, department_name from departments

Create View Object EmployeeListVO for Employee SelectItems.
Query: select employee_id, first_name from employees where dapartment_id = :DeptId

Define Bind variables DeptId in EmployeeListVO

Create View Object EmpDeptVO for defining the form elements.
This query varies according to your requirement. At least include employee_id and department_id in your select clause.

Define an Application Module and add above view objects to this application module.

Create a jspx page, drag EmpDeptVO to the jspx page and drop EmpDeptVO as ADF form.

Delete form elements for employee_id and department_id from the page.

Drag DepartmentId from data control under EmpDeptVO and drop as select one choice.
Click on add to define binding for List. Select DepartmentListVO from the Add data source drop down.
Select Display Attribute as DepartmentName.

Id of this select one chioce is auto populated as selectOneChoice1
Drag EmployeeId from data control under EmpDeptVO and drop as select one choice.
Click on add to define binding for List. Select EmployeeListVO from the Add data source drop down.
Select Display Attribute as FirstName.

Id of this select one chioce is auto populated as selectOneChoice2

Select selectOneChoice1 in structure window and go to properties.
Set AutoSubmit property to true

Select selectOneChoice2 in structure window and go to properties.
Set PartialTruggers property to selectOneChoice1

          <af:selectOneChoice value="#{bindings.Departmentid.inputValue}"
label="Department"
id="selectOneChoice1" autoSubmit="true"">
<f:selectItems value="#{bindings.Departmentid.items}"
id="selectItems1"/>
</af:selectOneChoice>
<af:selectOneChoice value="#{bindings.Employeeid.inputValue}"
label="Employee"
id="selectOneChoice2"
partialTriggers="selectOneChoice1">
<f:selectItems value="#{bindings.Employeeid.items}"
id="selectItems2"/>
</af:selectOneChoice>


Right click on the page and go to page definition.
Right click on Bindings -Select 'Insert Inside Bindings' - Select 'Generic Bindings' - select 'Action'

Select EmployeeListVO from data collection
Select Iterator as EmployeeListVOIterator
Select Operation as ExecuteWithParams
Set the value of parameter 'DeptId' as #{bindings.Departmentid.inputValue}
Click OK

Right click on executables - Select 'Insert Inside executables' - select 'InvokeAction'

Give one meaningful id 'InvokeExecuteWithParams'.
Set 'Binds' as 'ExecuteWithParams'
Set 'Refresh' as 'RenderModel'
Click Finish

Drag InvokeExecuteWithParams above EmployeeListVOIterator

Run the page.

  <bindings>
<action IterBinding="EmployeeListVOIterator" id="ExecuteWithParams"
InstanceName="HRAppModuleDataControl.EmployeeListVO"
DataControl="HRAppModuleDataControl" RequiresUpdateModel="true"
Action="executeWithParams">
<NamedData NDName="DeptId"
NDValue="#{bindings.Departmentid.inputValue}"
NDType="oracle.jbo.domain.Number"/>
</action>
..........
..........
</bindings>

<executables>
<invokeAction id="InvokeExecuteWithParams" Binds="ExecuteWithParams"
Refresh="renderModel"/>
<iterator Binds="EmployeeListVOIterator" RangeSize="-1"
DataControl="HRAppModuleDataControl" id="EmployeeListVOIterator"/>
...........
...........
</executables>



How to avoid JBO-35007 error?

When row currency validation fails JBO-35007 error is reaised.

Row currency validation safe gaurds ADF application from browser back button issue.

What is browser back button issue?
Form Duncan Mills ""Oracle JDeveloper 10g for Forms and PL/SQL Developers" book :
Users may be accustomed to clicking the browser's Back button to return to the preceding page or the Refresh button to reload the page. This can cause problems with web applications that use a Controller layer, like the JSF controller or Struts, because the browser Back button returns to the preceding page in the browser's page history without calling code in the Controller layer. The controller will therefore, not know the state of the application's data and the preceding page will either not load properly or may place the application into an inconsistent or unstable state. The same problem occurs with the browser's Refresh button, which just reloads the same page, again without calling Controller layer code. This is a problem in all web applications, not only those using J2EE technology or ADF libraries.

How to ignore row currnecy validation?
There are two ways to avoid this validation.(Note: As Row currency validation safe gaurds ADF application from browser back button issue, it is not suggested to ignore row currency validation)

Method I
Set the EnableTokenValidation to false in the page definition file.
1)In the Application Navigator, right-click the JSP page for which you want to disable validation, and choose Go to Pa ge Definition.
2)In the Structure window, right-click the pagenamePageDef node and choose Properties from the context menu.
3)In the PageDef Properties dialog, select the Advanced Properties tab.
4)In the Enable Token Validation box and choose False. The EnableTokenValidation attribute is added to the PageDef.xml file namespace with a value of false.

Method II
Disable row currency validation on an iterator by setting the "StateValidation" property of an iterator to "false" without disabling it for all iterators in the page definition.

Tuesday, May 19, 2009

Custom Component On top of ADF - JSF UI Components

Building Custom JSF UI Components

Overview

One of the key strengths of JavaServer Faces (JSF) is that not only does it provide substantial technology for easy, out of the box component based J2EE Web applications assembly, but it also is a very flexible API which allows for a wide breadth of customizations in numerous and innovative ways. This article introduces and explores the component developer's experience of building custom JSF user interface (UI) components.

Intended Audience

First off, this article is intended for component developers who already have an understanding of the overall JSF application development process but want to learn how to start developing their own custom JSF UI components. For those who are still new to JSF development, readers are highly recommended to first consult JSF application tutorials such as Rick Hightower's article on basic JSF development:

#http://www-106.ibm.com/developerworks/library/j-jsf1/

Or my earlier JavaPro article, which also introduces JSF:
http://www.fawcette.com/javapro/2004_01/magazine/features/cschalk/

In contrast to those introductory JSF articles, this article introduces the more advanced task of building custom JSF UI components by first explaining all of the "moving parts" associated with custom UI Components starting with a simple custom "HelloWorld" UI Component as an example.

The article then shows how to extend the simple "HelloWorld" component into more useful examples that show live stock quote information using a Web service. At the end of the article readers will have an appreciation of what exactly are the key tasks associated with building custom UI Components along with a full understanding of all the various sub-components that make up a typical "JSF UI Component".

When to Customize JSF .Before jumping into custom JSF component development just for the sake of it, some research should be done on whether custom development is necessary at all and at what level it is needed. As mentioned before, JavaServer Faces' base UI component library actually provides a modest amount of practical UI and non-UI components in its specification. In addition to visible components such as input/output fields, menu components and form buttons the JSF specification also has non-UI components which handle things like basic validation and/or data conversion. In many cases a developer may find that he/she may only need to customize a specific sub-component such as a new validation method as opposed to building an entirely new UI Component.

An easy google search or browsing through sites such as jsfcentral.com many usable and often free component libraries (and implementations) that can be experimented with. Some of the more popular and powerful ones include:

MyFaces - A general purpose and open source component library and implementation. - http://myfaces.apache.org


Oracle's ADF Faces - A rich library of useful JSF UI Components - http://www.oracle.com/technology ... ange/jsf/index.html

JScape's WebGalileo Faces - http://www.jscape.com/webgalileofaces/

Once the decision has been made to build some custom components as opposed to just using some existing ones, here's how to get started.

The "Moving Parts" of a JSF UI Component

The term "JSF UI Component" is generally used to describe a set of sub-components which each which perform their own specific task such as rendering the component, validating its input, and/or performing any data conversions (such as a String to a Date conversion). This may often give the impression to a novice JSF developer that JSF component development is fairly complicated and possibly tedious, but this is also JSF's strength in that each UI Components' sub-components can be individually customized and re-configured into new and varied combinations. In fact it is JSF's flexible API and it's "pluggable renderering" technology which allows UI Components to written for multiple Web clients thus drastically decreasing the complexity for the Web developer of assembling multi-client Web applications. Let's review the various "moving parts" of what constitutes a JSF UI Component.


The general term "JSF UI Component" refers to a collection of the following:

UIComponent Class - A Java class derived from either the UIComponentBase or extended from an existing JSF UIComponent such as outputText. This is the actual Java class representing the core logic of the component. It can optionally contain the logic to "render" itself to a client, or rendering logic can be separated into a separate "renderer" class.


Renderer Class - This is a class that only contains code to render a UIComponent. Rendering classes can provide different renderings for a UI Component. For such as either a button or hyperlink for the UICommand component. Renderers can also provide different rendering options for the same UI Component on different client types such as browsers, PDAs etc. This allows JSF the ability to run on any client device providing a corresponding set of renderer classes are built for the specific client type.

UI Component Tag Class - This is a JSP tag handler class that allows the UI Component to be used in a JSP. It can also associate a separate renderer class with a UIComponent class. (Note: The UI Component Tag handler class is only required for usage in a JSP deployment environment. Keep in mind that UI Components can also be used in non-JSP environments.)

Tag Library Descriptor File - This is a standard J2EE JSP tag library descriptor (tld) file which associates the tag handler class with a usable tag in a JSP page. (Required only For JSP usage only.)
Associated helper classes - These include a collection of standard (included in JSF RI) or custom helper classes such as Converters, Validators, ActionListeners etc., that can be programmatically bound to UI Components. For example a JSF UI Input Field component can be associated with a built-in number range Validator which ensures that an entered number is within a certain range. These helper classes can also be customized to perform any type of validation not provided out of the box with the JSF RI. For example a custom credit card Validator could be used with a JSF Input field to validate credit card numbers or a custom Converter could be used to convert currencies.

A Simple "HelloWorld" Custom UI Component Example

Before showing how to build a "Hello World" custom component, let's review quickly how to use it. To invoke the component we have a JSF enabled JSP page with an extra taglib directive specifying a custom tag library (tld) which contains the custom tag, "jsfhello", which is associated with our custom UI Component. To use the jsfhello tag, we simply place it into the body of the JSP and set an optional "hellomsg" attribute.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"><%@ page contentType="text/html;charset=windows-1252"%><%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%><%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%><%@ taglib uri="http://theserverside.com/customfacescomponents" prefix="cf"%><f:view> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"></meta> </head> <body> <h:form> <p>A simple HelloWorld Custom Component:</p> <p>The HelloWorld UI Component:</p> <cf:jsfhello hellomsg="Hello world! This is output from a custom JSF Component!" /> </h:form> </body> </html></f:view>
When the page is run, the JSF UI Component displays the "Hello World" message provided in the "hellomsg" attribute along with the current date and time. We'll review the details of the tag library and how the tag handler class invokes the UI Component shortly, but first let's review how to build the core UI Component class.

Building the"HelloWorld" Custom UI Component Step 1: Creating a UIComponent Class

For our HelloWorld example, our UIComponent will extend the UIComponentBase abstract class, which is provided in the JSF specification, and render a formatted HelloWorld message. Note: We could have also based our new UI Component class on the concrete UIOutput base class which is basically the same as the UIComponentBase with the exception that it has a "value" attribute. Since we aren't using one, we'll simply base it on the UIComponentBase abstract class.

package tss.hello;

import java.util.Date;
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;
import java.io.IOException;
import javax.faces.context.ResponseWriter;
public class HelloUIComp extends UIComponentBase
{
public void encodeBegin(FacesContext context) throws IOException
{
ResponseWriter writer = context.getResponseWriter();
String hellomsg = (String)getAttributes().get("hellomsg");
writer.startElement("h3", this);
if(hellomsg != null)
writer.writeText(hellomsg, "hellomsg");
else
writer.writeText("Hello from a custom JSF UI Component!", null);
writer.endElement("h3");
writer.startElement("p", this);
writer.writeText(" Today is: " + new Date(), null);
writer.endElement("p");
}
public String getFamily() { return "HelloFamily"; }
}
As you can see, this custom UI Component renders a formatted Helloworld message using and encodeBegin() method. Also notice that we have defined a method getFamily(). This is actually required for UI Components that extend UIComponentBase since it could come from any component family. Since in our example we won't be creating a new family of components, we can just return any String value such as "HelloFamily". Before examing the code further, a quick note on encoding and decoding.

A Quick Note on Encoding Methods

UI Components and/or associated renderer classes use encode*() methods display themselves to a client. The above HelloWorld example simply renders an HTML header (h3) with the custom hello message (if supplied) along with a paragraph containing the current date and time. For this component a single encodeBegin() (or encodeEnd() ) method is all that is needed to render the complete tag since it does not contain any children. The encodeBegin actually renders the beginning or the complete (bodiless) tag. UI Components with children tags/components will override encodeChildren() along with encodeEnd(). The encodeChildren() method allows children components to be rendered and encodeEnd() renders the closing parent tag.

A Closer Look at the encodeBegin() Method

Upon closer examination of the encodeBegin() method, we see that it receives the FacesContext as an argument. An extension to the servlet and JSP context, the FacesContext provides access to the many useful objects for JSF/JSP/Servlet development. In this example, we simply extract a "writer" object in order to "write" our rendered response back to the client.

public void encodeBegin(FacesContext context) throws IOException { ResponseWriter

writer = context.getResponseWriter();
Next we get the value of the attribute "hellomsg" which is passed from the tag from our JSP page using getAttributes(). The getAttributes method comes from the UIComponentBase class which is the base class for all UI Components.
String hellomsg = (String)getAttributes().get("hellomsg");
Rendering the HTML message is done using the writer methods in the code:
writer.startElement("h3", this);
if(hellomsg != null)
writer.writeText(hellomsg, "hellomsg");
else
writer.writeText("Hello from a custom JSF UI Component!", null);
writer.endElement("h3");
writer.startElement("p", this);
writer.writeText(" Today is: " + new Date(), null);
writer.endElement("p");
which when executed displays a formatted HTML "HelloWorld" message to the client.
Note: You'll notice that when the attribute (hellomsg) or "property" is written to the client, an additional String value representing the name of the property "hellomsg" is also included as an argument to the writeText() method. The idea behind this is to provide development tools environments the ability to display the name of the property in a visual editor. Leaving the second argument null is also acceptable and will not harm the execution of the component.
Step 2. Registering the custom UI Component in Faces-config.xml
Before moving on to building a JSP tag handler and a TLD file, we'll add a required entry for our custom component in the faces-config.xml file. The syntax for adding our custom UI component is:...
<faces-config xmlns="http://java.sun.com/JSF/Configuration"> <component> <component-type>tss.hello.JsfHello</component-type> <component-class>tss.hello.HelloUIComp</component-class> </component>
...</faces-config>
The component-type is the "JSF recognized" name of our custom component: "tss.hello.JsfHello". (We'll refer to this later in our tag handler.) The component-class is the actual class path address of our UI Component.
Step 3. Building a Custom JSP Tag Library
In order to be able to use our custom component in a JSP, we need a custom tag library comprised of a tag library descriptor file (TLD) along with references to taghandlers classes. (This example uses just a single tag handler.)
Building the Tag Handler
For JSF component development, the JSP taghandler class is derived from javax.faces.webapp.UIComponentTag. It's main purpose is to:
Associate a JSP callable tag (handler class) with the UI Component.
Associate a separate renderer class (if needed) to the UI Component.
Set the properties from the submitted tag attribute values to the UI Component.
Here is the source code for our tag handler class:
package tss.hello;
import javax.faces.application.Application;
import javax.faces.webapp.UIComponentTag;
import javax.faces.component.UIComponent;
import javax.faces.el.ValueBinding;
import javax.faces.context.FacesContext;
public class FacesHelloTag extends UIComponentTag
{
// Declare a bean property for the hellomsg attribute.
public String hellomsg = null;
// Associate the renderer and component type.
public String getComponentType() { return "tss.hello.JsfHello"; }
public String getRendererType() { return null; }
protected void setProperties(UIComponent component)
{
super.setProperties(component);
// set hellomsg
if (hellomsg != null){
if (isValueReference(hellomsg)){
FacesContext context = FacesContext.getCurrentInstance();
Application app = context.getApplication();
ValueBinding vb = app.createValueBinding(hellomsg);
component.setValueBinding("hellomsg", vb);}
else

component.getAttributes().put("hellomsg", hellomsg);
}
}
public void release(){
super.release();
hellomsg = null;
}
public void setHellomsg(String hellomsg){
this.hellomsg = hellomsg;
}
}
The first thing to note is the "hellomsg" bean property of type String along with its associated getter and setter methods at the bottom of the class. The hellomsg bean property, "hellomsg", is also an attribute in the JSP tag. (<sf:jsfhello hellomsg="Hello world!"../>)
Next we see two methods which associate this tag handler with our registered UI Component: "tss.hello.JsfHello" as well as associate the renderer. Since we don't have a separate renderer class, this statement returns a null value.
// Associate the renderer and component type.
public String getComponentType() { return "tss.hello.JsfHello"; }
public String getRendererType() { return null; }
The next method, setProperties(), sets the incoming values from the JSP tag by first calling the parent class' setProperties method along with custom code to set the value from the hellomsg tag attribute. Notice that a check is first done to see if the incoming attribute is a "ValueReference", which takes the form of a JSF EL expression: #{Bean.Property}. If a "ValueReference" is detected, it uses slightly different logic to set the application's value binding.
protected void setProperties(UIComponent component)
{
super.setProperties(component);
// set hellomsg
if (hellomsg != null)
{if (isValueReference(hellomsg)){
FacesContext context = FacesContext.getCurrentInstance();
Application app = context.getApplication();
ValueBinding vb = app.createValueBinding(hellomsg);
component.setValueBinding("hellomsg", vb);
}else
component.getAttributes().put("hellomsg", hellomsg);
}
}
Asides from the hellomsg getter and setter methods the only method required in the taghandler class is the release() method which resets the bean properties back to an unused state.
public void release()
{
super.release();
hellomsg = null;
}
and that's it for our tag handler class. Next we'll quickly review the JSP Tag Library Descriptor (TLD) required for this tag.

Step 4. Building the Tag Library Descriptor File

In order for us to use our custom JSP tag handler class, we need to create an associated TLD file which contains the tag entry associated with the tag handler class. Here is an example of the TLD file needed for this tag. The TLD associates the tag name, "jsfhello" with the tag class "tss.hello.FacesHelloTag" along with it's associated attributes. For our tag, we include our custom attribute, "hellomsg", along with the superclass' core attributes: "id", "binding" and "rendered".

<?xml version="1.0" encoding="ISO-8859-1" ?><!DOCTYPE taglib

PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"

"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd"><taglib><tlib-version>0.01</tlib-version><jsp-version>1.2</jsp-version>

<short-name>simple</short-name>

<uri>http://theserverside.com/simplefacescomponents</uri>

<description>This tag library contains simple JSF Component examples.</description>

<tag><name>jsfhello</name><tag-class>tss.hello.FacesHelloTag</tag-class>

<attribute> <name>binding</name> <description>A value binding that points to a bean property</description></attribute>
<attribute> <name>id</name> <description>The client id of this component</description></attribute>
<attribute> <name>rendered</name><description>Is this component rendered?</description></attribute>
<attribute> <name>hellomsg</name><description>a custom message for the Component</description></attribute>
</tag>
</taglib>
Following standard J2EE architecture, the custom TLD file is placed in the /WEB-INF/. sub-directory of the J2EE Web Module containing the application.
Running the simple HelloWorld Example
Just to review, our custom JSF component java classes must be compiled and available on the classpath of a J2EE Web Module. The Web Module must also have in it's class path the required JSF runtime jar files which include: jsf-api.jar, jsf-impl.jar along with the commons jar files (commons-beanutils.jar, commons-collections.jar, commons-digester.jar, commons-logging.jar). The other two required jar files come from JSTL (jstl.jar and standard.jar).
For more info on the Commons and JSTL libraries refer to the Jakarta Apache Project website: http://jakarta.apache.org/ .) For a runtime deployment, all the required jar files must be placed in the /WEB-INF/lib subdirectory of your J2EE Web Module.
Assuming your runtime environment is properly configured, you can test the simple JSF Hello World custom component by first creating a JSF enabled JSP page and then adding the taglib directive and dropping the tag into your page. (As explained before..)
When the JSF page is run, you will see the execution of your HelloWorld JSF Custom Component!
Extending the HelloWorld Custom Component
Now that we've created a simple HelloWorld component, we can now expand upon this very easily. One straightforward extension would be to make the HelloWorld component call a Web service for a specific stock symbol and print out it's value. So instead of providing a hellomsg, our tag/component attribute will contain a stock symbol. The renderer code will then query a stock quote Web service (made available to us via another class) with the symbol provided by the tag and print the current price in the response.
Here's how to modify the HelloWorld Custom Component to display a live stock quote using a Web service.
Create a Web Service Proxy Client
In order to call a Web service from java, you'll need to create a proxy java client which enables any other Java class the ability to call a stock Web service. Many free stock quote Web services are available on the Internet. This example uses the "Delayed Stock Quote Service" available from Xmethods.com. The actual Web Proxy creation step is left to the reader to implement since it is out of the bounds of JSF development however several Java Integrated Development Environments such as Oracle JDeveloper, can automatically generate the necessary client code which enables communication to a Web service.
Oracle JDeveloper 10.1.3 Preview's Web Service Proxy Wizard
Once a Web service Proxy class is created, we'll modify our hellomsg attribute to become a stock symbol attribute and call the Web service with this value and then print it out. This involves the following changes:
Create or Modify the HelloWorld UIComponent Class to Work with "Symbol" Attribute
Change or create a new UIComponent class which refers to a stock symbol attribute, "symbol", instead of the "hellomsg".
public class StockUIComp extends UIComponentBase
{
public void encodeEnd(FacesContext context) throws IOException
{
ResponseWriter writer = context.getResponseWriter();
String symbol = (String)getAttributes().get("symbol");...
Note: If you create a new UI Component such as StockUIComp, don't forget to register it in your faces-config file ( You could use the name: "tss.hello.JsfStock" mapped to the classpath address "tss.hello.StockUIComp").
Once you've retrieved the attribute value for the stock symbol, you can call your Web service proxy class to get the current price:
//get stock price using generated Web service Proxy
String stockprice = NetXmethodsServicesStockquoteStockQuotePortClient.getStockPrice(symbol);
Rendering the the stock price is easily done with the following code:
writer.startElement("p", this);

if(symbol != null)
writer.writeText("The stock price for " + symbol + " is: " + stockprice + ".", null);
else
writer.writeText("You must provide a Stock Symbol by setting the symbol attribute.", null);
writer.endElement("p");
The changes to the tag handler and TLD is a trivial search and replace of "hellomsg"" with "symbol". Your tag handler class will also have to refer to the different Stock UI Component: "tss.helloJsfStock", but the remaining code in the taghandler is basically the same as before with the "symbol" attribute replacing the "hellomsg" attribute:
public class StockTag extends UIComponentTag {
public String symbol = null;
public String getRendererType() { return null; } public String getComponentType() { return "tss.hello.JsfStock"; }
protected void setProperties(UIComponent component)
{
super.setProperties(component);
// set symbol
if (symbol != null){
if (isValueReference(symbol)){
FacesContext context = FacesContext.getCurrentInstance();
Application app = context.getApplication();
ValueBinding vb = app.createValueBinding(symbol);
component.setValueBinding("symbol", vb);

} else
component.getAttributes().put("symbol", symbol);
}...
Once you've updated your TLD with a new tag "simplestock" mapped to the taghandler "StockTag", you can then add the new tag to your JSP:
<p>The SimpleStock UI Component:</p> <sf:simplestock symbol="orcl" />
Here's the output for the HelloWorld Component along with the new Stock UI Component:
Extending the Stock UI Component Further
Now that we've extended the HelloWorld UI Component into something useful, let's further extend the stock component to make it more user friendly. Our modified stock component will now render an input field along with a submit button. This will allow users to enter a new stock symbol at runtime as opposed to hardcoding the attribute value in the JSP source.
This modification will introduce how to build a decode() method which is used to "decode" the incoming form field values as opposed to simply retrieving tag attribute values. We will also extend our simple encode() method to now render in input field along with a submit button.
Back to the UI Component
This time we'll name the UI Component "HtmlInputStock" following the JSF specification's naming convention. This time we'll extend extend the class from the UIInput component since it will be accepting input.
public class HtmlInputStock extends UIInput
{...
This component will have a more detailed encode() method. This time our encodeBegin() method will call separate encode methods to render the differerent elements: an input field, a submit button, and an output field which displays the returned price of the stock. Notice that I've add the identifiers ".inputbutton" and ".submitbutton" to the clientIds respectively when calling the encode methods. This will ensure that the names of the rendered HTML: fields will be unique on the client. In general this is good practice should you need to refer to the rendered name of the HTML field.
The encodeBegin() method is as follows:
public void encodeBegin(FacesContext context) throws IOException {

ResponseWriter writer = context.getResponseWriter();
String clientId = getClientId(context);
encodeInputField(writer, clientId+".inputbutton");
encodeSubmit(writer, clientId+".submitbutton");
encodeOutputField(context);
}
The encodeInputField() method is as follows:
private void encodeInputField(ResponseWriter writer, String clientId) throws IOException {
// render a standard HTML input field
writer.startElement("input", this);
writer.writeAttribute("type", "text", null);
writer.writeAttribute("name", clientId, "clientId");
Object v = getValue();
if (v != null)
writer.writeAttribute("value", v.toString(), "value");
writer.writeAttribute("size", "6", null);
writer.endElement("input");
}
Notice the name of the input field is assigned the clientId. We'll use this later to identify the field when we decode the input.

The encodeSubmit() is rendered with:

private void encodeSubmit(ResponseWriter writer, String clientId) throws IOException {// render a submit buttonwriter.startElement("input", this);writer.writeAttribute("type", "Submit", null);write.writeAttribute("name", clientId, "clientId");writer.writeAttribute("value", "Enter Stock Symbol", null); writer.endElement("input");}And finally the encodeOutputField() which is similar to before:public void encodeOutputField(FacesContext context) throws IOException{
ResponseWriter writer = context.getResponseWriter();
String symbol = (String)getAttributes().get("value"); // The "value" attribute is used to pass the stock symbol.//get stock priceString stockprice = NetXmethodsServicesStockquoteStockQuotePortClient.getStockPrice(symbol);writer.startElement("p", this);if(symbol != null)writer.writeText("The current price for " + symbol + " is: " + stockprice + ".", null);else

writer.writeText("", null); writer.endElement("p"); }

Now let's move on to the decode() method who's job is to parse the incoming field values and act upon it.public void decode(FacesContext context) {Map requestMap = context.getExternalContext().getRequestParameterMap();String clientId = getClientId(context);try {String string_submit_val = ((String) requestMap.get(clientId+".inputfield")); setSubmittedValue(string_submit_val); setValid(true);}catch(NumberFormatException ex) {// let the converter take care of bad input, but we still have// to set the submitted value, or the converter won't have// any input to deal withsetSubmittedValue((String) requestMap.get(clientId));}
}

Let's review some of the key statements in our decode() method. First our decode() method obtains a requestMap from the JSF Context.

Map requestMap = context.getExternalContext().getRequestParameterMap();The requestMap is a container which allows us to access the values submitted in the http request.
The next statement extracts the clientId which is the unique identifier of the client issuing the request. (i.e. submitting the form)


String clientId = getClientId(context);With the unique client identifier we can obtain the value of the submitted value contained in the requestMap for this client. We can then set the submittedValue to the value submitted in the form. Note: For this example, we are simply setting the value that was submitted as is, but in other cases we may wish to perform a conversion or validation on the submitted value before setting the value as "valid".

try {

String string_submit_val = ((String) requestMap.get(clientId)); setSubmittedValue(string_submit_val);
setValid(true);

}

catch(NumberFormatException ex) {

setSubmittedValue((String) requestMap.get(clientId));
}
That takes care of our new and improved UIComponent rendering (encoding and decoding). I'll leave out the step of registering this component in the faces-config and highlight the remaining trivial code modifications in the tag handler and the TLD.
For the tag handler we have only minor changes. This tag handler as before extends from the same UIComponentTag but will have a bean property of "value" instead of "symbol". The "value" property is the value submitted in the input field and is handled exactly in the same manner before as the symbol. The only other difference from before is that our tag handler is now registered with the StockInput UI Component Class.
public String getComponentType() { return "tss.hello.StockInput"; }
The setProperties method is basically the same as before but operating on the "value" instead "symbol":
protected void setProperties(UIComponent component) {

super.setProperties(component);

if (value != null)
{
if (isValueReference(value))
{
FacesContext context = FacesContext.getCurrentInstance();

Application app = context.getApplication();


ValueBinding vb = app.createValueBinding(value);

component.setValueBinding("value", vb);
}

else

component.getAttributes().put("value", value);

}

Updating the TLD Similar to before, the new TLD tag entry can be as follows:

...

<tag><name>stockinput</name><tag-class>tss.hello.StockInputTag</tag-class>

<attribute> <name>binding</name> <description>A value binding that points to a bean property</description></attribute>

<attribute> <name>id</name> <description>The client id of this component</description></attribute>

<attribute> <name>rendered</name><description>Is this component rendered?</description></attribute><attribute> <name>value</name><description>A value for submitted stock symbol..</description></attribute>

</tag> ....

Running the Stock Input Component

Invoking this component is done in a similar fashion as before where we simply add the tag to the page:

<sf:stockinput id="stockinput" value="" />

Notice that we can leave the value attribute blank but specify it later when we run it. Once the page is running, enter a test stock symbol such as ORCL or AMZN and check out the result!

Summary

As you can see, building custom JSF UI Component is a fairly straightforward process. Once you understand the mechanism detailed in the encode() and decode() methods in the rendering code, the rest is a fairly trivial process of providing the necessary "plumbing" with tag handlers as such to enable usage in a typical client such as a JSP based client.

Future articles on JSF Component development will also build upon these simple examples and show how to build other non visual JSF components such as Validators and Converters.
For More Deatils thepeninsulasedge.com

Monday, May 18, 2009

Complex Calculated Values in Oracle ADF af:table Component

Title of this post not accidentally contains word 'complex', developed sample application is really a bit complex, but I will try to describe it in easy way. Some time ago I was blogging about how to include calculated column into af:table component - Calculated Column in ADF Faces af:table Component. But, it was just separate read-only calculated column based on values available in other columns. However, what if you need to include calculation logic for database table related column and on the same time allow it to be editable.

Developed sample application - CalculatedComplex.zip is based on HR schema available in Oracle XE database and implements logic that allows to edit two calculated columns - MinSalary and MaxSalary.

Calculation rule applied for MinSalary:

* IF (MaxEmployeeSalary - AvgEmployeeSalary <>

Calculation rule applied for MaxSalary:

* IF (AvgEmployeeSalary + MaxEmployeeSalary > MaxSalary) THEN update(MaxSalary)

If described conditions will not be satisfied, this means value that was entered by user will be stored in database.

MaxEmployeeSalary and AvgEmployeeSalary are values calculated in EmployeesQueryView:


Calculations for both columns are done in Backing bean, methods are invoked through dummy binding to ReadOnly property:


All calculations related to MinSalary are done in getCalculatedMinSalary() method. Based on JobId parameter are calculated AvgEmployeeSalary and MaxEmployeeSalary values, and if specified condition is satisfied MinSalary is updated:


MaxSalary is calculated in exactly the same way as MinSalary.

Now I will show how it works. Let's say we want to focus on PU_CLERK salary:


If in Employees table we set Salary values for PU_CLERK to 1900, 1600, 1700, 1600, 1500 and press Save button - MinSalary in Jobs table for PU_CLERK is updated to 240:


MaxSalary is not updated, because AvgEmployeeSalary + MaxEmployeeSalary = 3560 and this is less comparing to current 8000. So, user can set MaxSalary manually to let's say 5000 and this value will be stored in database:


When running sample application, don't forget to add adf-faces-impl.jar and jsf-impl.jar to application's WEB-INF\lib directory.

Sunday, May 10, 2009

call method on page load in ADF – [JDeveloper Version 10.1.3]

In this example we will see how we can call a method inside your backing bean or application module when page is getting loaded.
The scenario I am taking here is you have to show the current row index of the view object row on page load in ADF table column.
1) Create a view object based on Job table in HR schema with name OnPageLoadJobVO. Do generate the VOImpl and VORowImpl java classes for the created view object.



2) Add a transient variable inside your view object with name
“myCurrentRowIndex”



3) Add the above created view Object inside your application module.
4) Add the following code inside your application module Impl class.

public void setJobCurrentRowIndex() {
System.out.println("I am here inside AM");
OnPageLoadJobVOImpl vo = getOnPageLoadJobVO1();
OnPageLoadJobVORowImpl row=null;
long fetchedRowCount = vo.getEstimatedRowCount();
RowSetIterator jobVoIter = vo.createRowSetIterator("jobVoIter");
if (fetchedRowCount > 0)
{
jobVoIter.setRangeStart(0);
jobVoIter.setRangeSize((int)fetchedRowCount);
for (int count = 0; count < fetchedRowCount; count++)
{
row=(OnPageLoadJobVORowImpl)jobVoIter.getRowAtRangeIndex(count);
row.setmyCurrentRowIndex(new Number(count));
}
}
jobVoIter.closeRowSetIterator();
}
5) Expose the above created method in application module to the client.
6) Drag and drop the OnPageLoadJobVO object to your jspx page as ADF read only table.
7) Create a new Managed bean using faces-config.xml with
name= OnPageLoadBackingBean and
class= OnPageLoadBean

8) Copy and paste the following code inside your newly created managed bean class.
package viewlayer.backing;
import javax.faces.application.Application;
import javax.faces.context.FacesContext;
import javax.faces.el.ValueBinding;
import model.common.AppModule;
import oracle.adf.controller.v2.lifecycle.Lifecycle;
import oracle.adf.controller.v2.lifecycle.PagePhaseEvent;
import oracle.adf.controller.v2.lifecycle.PagePhaseListener;


public class OnPageLoadBean implements PagePhaseListener{
public OnPageLoadBean() {
}
public void afterPhase(PagePhaseEvent event) {
}
public void beforePhase(PagePhaseEvent event) {
if (event.getPhaseId() == Lifecycle.PREPARE_MODEL_ID) {
if (!isPostback())
/*
System.out.println("i am here inside backing bean");
this.getApplicationModule().setJobCurrentRowIndex();
}
}
private boolean isPostback() {
return Boolean.TRUE.equals(resolveExpression("#{adfFacesContext.postback}"));
}
private Object resolveExpression(String expression) {
FacesContext ctx = FacesContext.getCurrentInstance();
Application app = ctx.getApplication();
ValueBinding bind = app.createValueBinding(expression);
return bind.getValue(ctx);
}
private AppModule getApplicationModule() {
return (AppModule)resolveExpression ("#data.AppModuleDataControl.dataProvider}");
}
}
9) Right click on your jspx page and go to your page definition. Where set the attribute ControllerClass inside your pageDefinition tag as the name of the managed bean.


Run your page to check the results.

Questions on ADF and Middleware fusion technologies Part-3

Q: To construct an oracle.jbo.domain.Date object for current JVM system time?
Answer:
oracle.jbo.domain.Date currentJvmDate = new oracle.jbo.domain.Date(System.currentTimeMillis());
Q: To construct an oracle.jbo.domain.Date object for current database system time?
Answer:
oracle.jbo.domain.Date currentDbDate =rootAM.getOADBTransaction().getCurrentDBDate();
Q: To determine if an oracle.jbo.domain.Date is the passedDate?
Answer:
public boolean isPassedDate(Date value)
{
// ensures that this mandatory attribute has a nonnull
value.
if (value != null)
{
OADBTransaction transaction = this.getOADBTransaction();
long sysdate = transaction.getCurrentDBDate().dateValue().getTime();
long startDate = value.dateValue().getTime();
if (startDate < sysdate)
{
return true;
}
}
return false;
}
Q: To round off the real number upto two digits?
Answer:
public String roundOffToTwoDigit(String number)
{
DecimalFormat formatter= new DecimalFormat("###.##");
double numberD = Double.parseDouble(number);
return formatter.format(numberD);
}
public double roundOffToTwoDigit(double number)
{
try
{
DecimalFormat formatter= new DecimalFormat("#.00");
formatter.setMaximumFractionDigits(2);
formatter.setMinimumFractionDigits(2);
return new Double(formatter.format(number)).doubleValue();
}
catch(java.lang.NumberFormatException e)
{
e.printStackTrace();
}
return 0.0;
}
Q: I have an entity object-based view object and I use vo.clearCache.However I am getting oracle.jbo.TooManyObjectsException?How to solve this?
Answer:
When you clear the view object cache with vo.clearCache(), it does NOT clear the entity cache nor change the states of entities. Thus, if you try to insert the row with a key value that already exists in the entity cache; you get TooManyObjectsException.The solution is to remove on all
the rows in the view object.
Q: When I am trying to insert a record through OAF page, I am getting oracle.jbo.TooManyObjectsException? How to solve this?
Answer:
Possible reason could be of inserting the record with duplicate primary key.
Q: How do I determine the transaction state -- that is, whether changes have been made to view objects or not?
Answer:
We can use
-->ApplicationModule.getTransaction().isDirty() - This method tells you whether the transaction contains any changes in the view objects. This works for transactions made by entity object-based view objects only.
-->OAViewObject.isDirty() - This method tells you whether a particular view object contains changes or not. This works for both entity object-based view objects and view objects
based on OAPlsqlViewObjectImpl
--> Or we can achieve it declarativaly by setting the Warn About changes property against the item for which we want the System to generate the Warn About change warning. But if your view Contains many transient variables which are getting defaulted at page load, then you can use the following method:-
/* @sourceVO: source VO contains the data in the UI
* @destVO: dest VO contains the data fetched from the
database, should not be
* based on EO
*/
private boolean isVODataDirty(ViewObjectImpl sourceVO,
ViewObjectImpl destVO)
{
boolean dirtyDataFlag=false;
if (sourceVO == null destVO == null)
{
return false;
}
else if(sourceVO.getRowCount()!=destVO.getRowCount())
{
return true;
}
AttributeDef[] attrDefs = sourceVO.getAttributeDefs();
int attrCount = (attrDefs == null)? 0 : attrDefs.length;
/*if no attributes are there in the VO*/
if (attrCount == 0)
{
return false;
}
/* Create a row set iterator on the source view object
to use for copy operation*/
RowSetIterator compareIter = sourceVO.findRowSetIterator("compareIter");
if (compareIter == null)
{
compareIter = sourceVO.createRowSetIterator("compareIter");
}
int count=0;
/*Sets the range size for the iterator,-1 for all
rows are to be included.*/
destVO.setRangeSize(-1);
/*loop for the VO rows*/
while (compareIter.hasNext())
{
Row sourceRow = compareIter.next();
Row destRow = destVO.getRowAtRangeIndex(count);
/*loop for the VO Attribute*/
for (int i = 0; i < attrCount; i++)
{
byte attrKind = attrDefs[i].getAttributeKind();
/*compare the data only if the attribute
is persistent*/
if(attrKind==AttributeDef.ATTR_PERSISTENT)
{
String attrName=attrDefs[i].getName();
if (destVO.lookupAttributeDef(attrName) != null)
{
Object sourceAttrVal = sourceRow.getAttribute(attrName);
Object destAttrVal = destRow.getAttribute(attrName);
if(destAttrVal!=null && sourceAttrVal!=null)
{
if(!sourceAttrVal.equals(destAttrVal))
{
dirtyDataFlag=true;
compareIter.closeRowSetIterator();
return dirtyDataFlag;
}
}
/*if values are not equal then it
means data is dirty*/
if((sourceAttrVal==null && destAttrVal!=null)
(sourceAttrVal!=null && destAttrVal==null))
{
dirtyDataFlag=true;
compareIter.closeRowSetIterator();
return dirtyDataFlag;
}
}
}
}
count++;
}
compareIter.closeRowSetIterator();
destVO.reset();
/*data is not dirty*/
return dirtyDataFlag;
}
Q: When I am executing the VO query and after that fetching the attribute value from the VO, getting the NullPointerExecption?How to handle it?
Answer:-When you execute the VO.executeQuery() method, and if your query is fetching the record, then row pointer is at position -1. Either call the vo.first() method or call vo.setCurrentRowRangeIndex(0);
Q: I have two radio buttons with are the part of the same group, when I am submitting the page, control is jumping in to the last radio button? How I can solve this problem?
Answer:-Just put your individual radio button under the flowlayout which intern should be put under the cell format.
Q: I have two advance tables in my page. And both of them have "Add Another Row" button, now How I can identify that which "Add Another button" is clicked?
Answer: By calling the pageContext.getParameter(SOURCE_PARAM) will return the name
of the Advance table against which the Add Another Radio button is clicked.
Q: I have two radio buttons in my page. When I am submitting the page, the control is jumping to last radio button in my page?
Answer:
Use messageRadioButtons and group them under same name and add each radio button under the separate cellformat region.
Q: I want to check the XML file which I have imported to the Server in MDS repository?
Answer: Execute following command in SQL exec JDR_UTILS.printDocument('');
example
exec
JDR_UTILS.printDocument('/who/oracle/apps/xxwrp/prt/whoreg/
webui/XXWRP_GoodsRegistrationPG');
And to list of the PG files in particular top, execute the
following command:-
exec JDR_UTILS.listDocuments('path');
example
exec
JDR_UTILS.listDocuments('/who/oracle/apps/xxwrp/prt/whoreg/
webui/');
Q: Is there a way to determine if someone has used the personalize links on a Self-Service Web Applications page?
Answer:
Here are several ways to identify if there are Personalization’s made to a page and what those
Personalization’s are:
1. The first and easiest way is to go to the page you want to check for Personalization’s, then click on the 'About this page' link at the bottom left of the page. Click on the Personalization tab. Then you should see a list of 'Effective Personalization’s', what elements have been customized and when they were customized/personalized.
2. Another way is to use the Functional Administrator. The first thing to do to use the Functional Administrator is to identify the Document Path. For example, go to the Notifications link from the Workflow User Web Applications responsibility, and then click on the Personalize Page link. Notice that the Document path for the Notifications page is: /oracle/apps/fnd/wf/worklist/webui/NotificationsPG. From the Functional Administrator responsibility Home page, click on the Personalization tab in the upper left hand corner. Insert the document path for the document you want to check - for example: Document Path = /oracle/apps/fnd/wf/worklist/webui/NotificationsPG and then click on the 'Go' button to get a list of Personalization’s for this page.
3. A third way to check to see if there are personalization’s on a page is to use sqlplus and run the
JDR_UTILS program. You will need the Document path to the page in question - again using the Document path for the Notifications page: /oracle/apps/fnd/wf/worklist/webui/NotificationsPG
Run the listDocuments function to drill down and find all documents that have been personalization’s under a certain Meta Data region:
Run from sqlplus:
set serveroutput on
exec
JDR_UTILS.listDocuments('/oracle/apps/fnd/wf/worklist/webui
/');
/oracle/apps/fnd/wf/worklist/webui/customizations/
Note, you do not include the Page ID (NotificationsPG) with this query. In my test case, notice that there are 'customizations' in this MDS region webui. The 'customizations' indicates that personalization’s have been made to the 'webui' region. Run the query again with the new path and notice that there are 'site' level customizations, although there could be other levels such as user, responsibility, ...:
exec
JDR_UTILS.listDocuments('/oracle/apps/fnd/wf/worklist/webui
/customizations/');
/oracle/apps/fnd/wf/worklist/webui/customizations/site/
Run the query again with the new path and notice that the customizations are at site level '0':
exec
JDR_UTILS.listDocuments('/oracle/apps/fnd/wf/worklist/webui
/customizations/site/');
/oracle/apps/fnd/wf/worklist/webui/customizations/site/0/
Run the query one more time with the new path and notice that the customizations are made to the 'NotificationsPG':
exec
JDR_UTILS.listDocuments('/oracle/apps/fnd/wf/worklist/webui
/customizations/site/0/');
/oracle/apps/fnd/wf/worklist/webui/customizations/site/0/No
tificationsPG
Once we have identified a particular page or pages that have customizations/personalization, then we can use the printDocument to see what personalization’s have been made
to the page:
exec
JDR_UTILS.printDocument('/oracle/apps/fnd/wf/worklist/webui
/customizations/site/0/NotificationsPG');
-------------


version="9.0.5.4.89_554"
xml:lang="en-US"
customizes="/oracle/apps/fnd/wf/worklist/webui/NotificationsPG">




-------------
As you can see, rendered has been set to "false" for "MainRegion.NtfView". You can then use the deletedocument function to remove this personalization exec jdr_utils.deletedocument('/oracle/apps/fnd/wf/worklist/webui/customizations/site/0/NotificationsPG');

Q: How to remove a bad personalization from an OA Framework page?
Answer:
) Login to Oracle Applications with the system administrator responsibility
2) Update the Profile Option: "Disable Self-Service Personal" = YES
- This disables the rendering of all personalization that have been created.
- You can set this at the site or user level.
3) Navigate to the page you personalized.
4) Enter the personalization UI in the same way you did to create the personalization initially
5) Click the Delete button at the bottom of the page.
- This will remove the personalization from the page.
6) Go back to Oracle Apps with the system administrator responsibility
7) Re-enable personalizations by setting the "Disable Self- Service Personal" profile option to NO
Q: How to pass a Date to a VO for executing the Query?
Answer:
Oracle.jbo.domain.date dateToPass=;
java.sql.Date javaSqlDate=dateToPass.dateValue();
dateToPass = new Date(javaSqlDate);
vo.setWhereClauseParam(1,dateToPass);
vo.executeQuery();
Q: How I can bind the property of a UI widget to a VO attribute at design time and at run time?
Answer:
At design time we have to use SPEL. Suppose to have to bind the disable property of a UI widget to the VO attribute. Then specify ${oa..} against the disabled property of the UI item in the property inspector. For run time, get the handle of the bean. say
OAMessageLovInputBean beanObj = (OAMessageLovInputBean)webBean.findIndexedChildRecursive("<>");
beanObj.setAttributeValue(DISABLED_ATTR,new
OADataBoundValueViewObject(beanObj, "", ""));
Q: How I can change the values of the Categories (Category drop down) in the standard OAF Attachment page?
Answer:
String []maps=;
OAAttachmentTableBean attchmentBean=(OAAttachmentTableBean)webBean.findIndexedChi
ldRecursive("AttachmentTable");
attchmentBean.setCategoryMap(,maps,pageContext);
Q: How I can set the Currency Code(Currency format) for a particular UI field?
Answer:
String formatter = "USD";
OAMessageStyledTextBean regUSDAmtBean=(OAMessageStyledTextBean)webBean.findIndexedChildRecursive("USDTotalAmt");
if (regUSDAmtBean != null)
{
regUSDAmtBean.setAttributeValue(CURRENCY_CODE,formatter);
}
Q: How to get the handle to a particular row of the Advance table?
Answer:
--------------Inside CO---------------------------------------------------------------------
String rowReference =
pageContext.getParameter(OAWebBeanConstants.EVENT_SOURCE_ROW_REFERENCE);
Serializable[] params = { rowReference };
am.invokeMethod("getHandleToRow",params);
---------------------------------------------------------------------------------------------
------------Inside AM------------------------------------------------------------------------
public void getHandleToRow()
{
OARow row = (OARow)findRowByRef(rowReference);
-------
}

Questions on ADF and Middleware fusion technologies part-2

Q: How do I find whether 'Next' or 'Previous' links are clicked or not? (Classic and Advanced)?
Answer:
/*Call the following logic in processFormRequest method of
the web bean's controller that contains the table bean.*/
String value = pageContext.getParameter("value");
if (value != null)
{
int newValue = Integer.parseInt(value);
if (tableBean.getValue() < newValue)
// next pressed.
else
// previous pressed.
}
Q: Is there a method for setting the length of the fields in a poplist? It seems to be sized to the length of the largest value in the list?
Answer:
This is the standard HTML behavior. The only method available to you is to truncate the values being passed to the poplist.
Q: Is there any way to check whether a field from the base page, that an LOV is dependent on, is blank?
Answer:
In OA Extension, set the Required property to yes for the field (region item). If the field is blank, the LOV will generate an exception.
Q: How do I handle raising an unexpected database error and passing that back to the instantiating page?
Answer:
To handle database errors that occur within a PL/SQL procedure called through Java, code a standard exception handler for 'when others' within the PL/SQL procedure. The 'when others' exception handler should call FND_MSG_PUB.ADD_EXEC_MSG (pkg_name, proc_name,
substr(sqlerrm, 1, 240)). This registers the database error in the standard FND error stack.
You can then catch and throw that exception in the insertRow and updateRow methods using the procedure OAExceptionHelper.checkErrors (Tx, messageCount, returnStatus, messageData).
Q: To convert oracle.jbo.domain.Date ==> java.util.Date?
Answer:
oracle.jbo.domain.Date oracleDate = ;
java.sql.Date javaSqlDate = oracleDate.dateValue();
long javaMilliSeconds = javaSqlDate.getTime();
java.util.Date javaUtilDate = new java.util.Date(javaMilliSeconds);
Q: To convert java.util.Date ==> oracle.jbo.domain.Date?
Answer:
java.util.Date javaDate = ;
long javaMilliseconds = javaUtilDate.getTime();
java.sql.Date javaSqlDate = new java.sql.Date(javaMilliseconds);
oracle.jbo.domain.Date oracleDate = new oracle.jbo.domain.Date(javaSqlDate);

Tuesday, April 21, 2009

Call Stoered Procedure /Stored Function with ARRAY Parameters

PL/SQL
create or replace type EMP_REC as object
(
employee_id number(6),
last_name varchar2(25),
job_id varchar2(10)
)
=============================
create or replace
TYPE EMP_TABLE AS TABLE OF EMP_REC
================================
create or replace
PACKAGE BODY PK_PROD AS

PROCEDURE INSERT_PROD(p_iorec IN EMP_TABLE) AS
BEGIN
/* TODO implementation required */
FOR i IN 1..p_iorec.count LOOP
--get p_iorec(i).EMP_NAME
insert into productmaster values(p_iorec(i).employee_id, p_iorec(i).last_name, p_iorec(i).job_id);
END LOOP;

END INSERT_PROD;

PROCEDURE INSERT_PROD1 AS
dt varchar2(20);
BEGIN
/* TODO implementation required */

--select sysdate into dt from dual;
insert into productmaster values(2,'as', 'asd');
END INSERT_PROD1;

END PK_PROD;
Java Code:
con = uow.getAccessor().getConnection();
//code to create the struct+array
oracle.sql.StructDescriptor structDesc = StructDescriptor.createDescriptor("EMP_REC", con);
oracle.sql.ArrayDescriptor arrayDesc = ArrayDescriptor.createDescriptor("EMP_TABLE", con);
...
oracle.sql.ARRAY newArray = new ARRAY(arrayDesc, con, arr.toArray());

//code to create and execute the query:
StoredProcedureCall call = new StoredProcedureCall();
call.setProcedureName("PK_PROD.INSERT_PROD");
call.addUnamedArgument("in_array");

DataModifyQuery query = new DataModifyQuery();
query.setShouldBindAllParameters(true);
query.setCall(call);
query.addArgument("in_array");
Vector args = new Vector(1);
args.addElement(newArray);

getSession().executeQuery(query, args);



If using TopLink 11, you can have TopLink create the Array and Struct objects for you - so you don't need to get the connection and build the objects yourself. The following code assumes that the EMP_REC struct is mapped to an Employee object using a TopLink Descriptor, see http://www.oracle.com/technology/products/ias/toplink/doc/10131/main/_html/prjdaun003.htm for details on how to do this.

//code to create the java objects representing the ARRAY and STRUCT
emptable= new Vector(); //represents the ARRAY
//build each employee and add it to the emptable
Employee emp = new Employee();
..
emptable.add(emp);

StoredProcedureCall call = new StoredProcedureCall();
call.setProcedureName("PK_PROD.INSERT_PROD");
//Tell TopLink what the ARRAY contains
ObjectRelationalDatabaseField ordf = new ObjectRelationalDatabaseField("");
ordf.setSqlType(Types.STRUCT);
ordf.setSqlTypeName("EMP_REC");
ordf.setType(Employee.class);
call.addUnamedArgument("in_array", Types.ARRAY, "EMP_TABLE", ordf);
//build the reusable query
DataModifyQuery query = new DataModifyQuery();
query.setShouldBindAllParameters(true);
query.setCall(call);
query.addArgument("in_array");

Vector args = new Vector(1);
args.addElement(emptable);

getSession().executeQuery(query, args);

Wednesday, April 15, 2009

ADF Faces: Building a search form showing the results in a taskflow using an af:popup component

One of the areas that really rocks in JDeveloper 11 is taskflows. To program usecases that involve taskflows can keep you busy for weeks if the goal is to provide a library of code examples.
A JSF page has a textfiled and a search button. The user enters a department number and hits the "search" button. The result of this search, which uses ExecuteWithParams in ADF Business Components, shows in a popup dialog on the same page. To enforce reuse - one of the big themes in JDeveloper 11 - the popup content is a taskflow that shows in a region.
The challenges solved in this usecase are:
1) The input argument is of type String - as everything on the web starts as a string before it gets converted - whereas the bind variable used within the ExecuteWithParams operation is of type oracle.jbo.domain.Number. Because of this, the result oage cannot be called directly and instead a method needs to be called first to prepare the model before the result page is called


2) The search string needs to be passed to the region as an input parameter. Further, the region needs to be updated whenever a new parameter is passed.
3) The popup needs to be closed programmatically. This part is easy and I am reusing the code from another blog entry of mine
At runtime, the application works as shown below


A tiny bit that I haven't yet got working using the af:showPopupBehavior, which works if launching the popup using the af:clientListener with JavaScript, is to proper adjust the position of the popup. However, JDeveloper 11 is not production yet, so no need to worry too much about this yet.
Pressing the close button on the popup will dismiss the popup window. Pressing the search button again will re-open it with the query result of the new search input.
The query is performed within the method activity, which is the default activity in the taskflow and that routes the request to the page fragment that displays the result table once finished.

CODE:
public void executeQuery(){

FacesContext fctx = FacesContext.getCurrentInstance();
ELContext elctx = fctx.getELContext();
Application jsfapp = fctx.getApplication();
ExpressionFactory exprfct = jsfapp.getExpressionFactory();

ValueExpression adfDataVexpr = exprfct.createValueExpression(elctx,"#{data}",BindingContext.class);
BindingContext adfdata = (BindingContext) adfDataVexpr.getValue(elctx);
ValueExpression deptIdDataVexpr = exprfct.createValueExpression(elctx,"#{pageFlowScope.deptIdTaskFlowParam}",Object.class);
if (deptIdDataVexpr.getValue(elctx) != null){

String deptIdStr = (String) deptIdDataVexpr.getValue(elctx);
try {

Integer deptIdInt = Integer.parseInt(deptIdStr);
BindingContainer bindings = adfdata.findBindingContainer("BrowseEmployeesPageDef");
bindings.getOperationBinding("ExecuteWithParams").getParamsMap().put("deptId",new Number(deptIdInt.intValue()));
bindings.getOperationBinding("ExecuteWithParams").execute();

} catch (NumberFormatException ex) {
ex.printStackTrace();
}


}
return;
}
The initial code lines are there to get a hold of the ExecuteWithParams method that is contained in the pagedef file associated with the page fragment. Theinteresting bits start with line 10. In here, the parameter that is passed from the calling page to the region (taskflow) is accessed and then converted to oracle.jbo.domain.Number before it is used to execute the ExecuteWithParams operation.
When you drag a taskflow as a region onto a page, then - if the taskflow requires an input parameter, the pagedef file of the page on which the region is added, is updated with the region definition and input parameter binding


In the image above, you see that the input parameter that is defined on the taskflow, reads its value from #{pageFlowScope.deptIdSearch}, an attribute added to the pageFlowScope of the calling page. The attribute is updated by the search field on the page

XML:
value="#{pageFlowScope.deptIdSearch}"/>
So anything that the user types into the search field, gets written to the pageFlowScope attribute when pressing the search button, which performs the form submit. Important to note is that if you want to launch a popup dialog from a button, you must ensure that the button uses a partial submit instead of performing a full page refresh

XML:
partialSubmit="true">


So what do we have until here, and what is missing still ? We have a task flow that starts with a method call to prepare the query for the table. The method takes an input argument that is passed to the taskflow from the region. The region accesses the parameter value from an attribute in the pageFlowScope of the calling page. The remaining job is to make sure the taskflow input parameter writes the input parameter to its own pageFlowScope so the Java method can access it using EL.

XML:
1. adfc-config xmlns="http://xmlns.oracle.com/adf/controller" version="1.2">

ExecuteEmployeesQuery

deptIdTaskFlowParam
#{pageFlowScope.deptIdTaskFlowParam}



EmployeesBean
adf.sample.EmployeesBean
pageFlow


/BrowseEmployees.jsff


#{pageFlowScope.EmployeesBean.executeQuery}

showEmployees



ExecuteEmployeesQuery

showEmployees
BrowseEmployees





The taskflow source shows the following
The default activity - and thus the first action performed when entering the taskflow - is the method call to a managed bean. ExecuteEmployeesQuery
The input parameter is defined as "deptIdTaskFlowParam", which is the same name used in the region binding, and writes the obtained value to #{pageFlowScope.deptIdTaskFlowParam} from where it is accessed by the managed bean method

XML:

deptIdTaskFlowParam
#{pageFlowScope.deptIdTaskFlowParam}


The remaining information to give is that I set the "Refresh" property on the region binding in the pagedef file of the calling page to "ifNeeded", which makes sure that the region binding is updated whenever the input parameter changes.

Thursday, April 9, 2009

Some handy code for backing beans ( ADF & JSF )

Here some code which you can use in your backing beans, I use this code all the time. With this you can retrieve the data or actions from the ADF page definition or create new uicomponents with ADF definitions and some JSF methods.

I'll keep this page up to date. Let me know if you have some code.

// print the roles of the current user
for ( String role : ADFContext.getCurrent().getSecurityContext().getUserRoles() ) {
System.out.println("role "+role);
}


// get the ADF security context and test if the user has the role users
SecurityContext sec = ADFContext.getCurrent().getSecurityContext();
if ( sec.isUserInRole("users") ) {
}
// is the user valid
public boolean isAuthenticated() {
return ADFContext.getCurrent().getSecurityContext().isAuthenticated();
}
// return the user
public String getCurrentUser() {
return ADFContext.getCurrent().getSecurityContext().getUserName();
}


// get the binding container
BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry();

// get an ADF attributevalue from the ADF page definitions
AttributeBinding attr = (AttributeBinding)bindings.getControlBinding("test");
attr.setInputValue("test");

// get an Action or MethodAction
OperationBinding method = bindings.getOperationBinding("methodAction");
method.execute();
List errors = method.getErrors();

method = bindings.getOperationBinding("methodAction");
Map paramsMap = method.getParamsMap();
paramsMap.put("param","value") ;
method.execute();


// Get the data from an ADF tree or table
DCBindingContainer dcBindings = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();

FacesCtrlHierBinding treeData = (FacesCtrlHierBinding)bc.getControlBinding("tree");
Row[] rows = treeData.getAllRowsInRange();

// Get a attribute value of the current row of iterator
DCIteratorBinding iterBind= (DCIteratorBinding)dcBindings.get("testIterator");
String attribute = (String)iterBind.getCurrentRow().getAttribute("field1");

// Get the error
String error = iterBind.getError().getMessage();


// refresh the iterator
bindings.refreshControl();
iterBind.executeQuery();
iterBind.refresh(DCIteratorBinding.RANGESIZE_UNLIMITED);

// Get all the rows of a iterator
Row[] rows = iterBind.getAllRowsInRange();
TestData dataRow = null;
for (Row row : rows) {
dataRow = (TestData)((DCDataRow)row).getDataProvider();
}

// Get the current row of a iterator , a different way
FacesContext ctx = FacesContext.getCurrentInstance();
ExpressionFactory ef = ctx.getApplication().getExpressionFactory();
ValueExpression ve = ef.createValueExpression(ctx.getELContext(), "#{bindings.testIter.currentRow.dataProvider}", TestHead.class);
TestHead test = (TestHead)ve.getValue(ctx.getELContext());

// Get a session bean
FacesContext ctx = FacesContext.getCurrentInstance();
ExpressionFactory ef = ctx.getApplication().getExpressionFactory();
ValueExpression ve = ef.createValueExpression(ctx.getELContext(), "#{testSessionBean}", TestSession.class);
TestSession test = (TestSession)ve.getValue(ctx.getELContext());

// main jsf page
DCBindingContainer dc = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
// taskflow binding
DCTaskFlowBinding tf = (DCTaskFlowBinding)dc.findExecutableBinding("dynamicRegion1");
// pagedef of a page fragment
JUFormBinding form = (JUFormBinding) tf.findExecutableBinding("regions_employee_regionPageDef");
// handle to binding container of the region.
DCBindingContainer dcRegion = form;



// return a methodexpression like a control flow case action or ADF pagedef action
private MethodExpression getMethodExpression(String name) {
Class [] argtypes = new Class[1];
argtypes[0] = ActionEvent.class;
FacesContext facesCtx = FacesContext.getCurrentInstance();
Application app = facesCtx.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesCtx.getELContext();
return elFactory.createMethodExpression(elContext,name,null,argtypes);
}

//
RichCommandMenuItem menuPage1 = new RichCommandMenuItem();
menuPage1.setId("page1");
menuPage1.setText("Page 1");
menuPage1.setActionExpression(getMethodExpression("page1"));

RichCommandButton button = new RichCommandButton();
button.setValueExpression("disabled",getValueExpression("#{!bindings."+item+".enabled}"));
button.setId(item);
button.setText(item);
MethodExpression me = getMethodExpression("#{bindings."+item+".execute}");
button.addActionListener(new MethodExpressionActionListener(me));
footer.getChildren().add(button);


// get a value
private ValueExpression getValueExpression(String name) {
FacesContext facesCtx = FacesContext.getCurrentInstance();
Application app = facesCtx.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesCtx.getELContext();
return elFactory.createValueExpression(elContext, name, Object.class);
}
// an example how to use this
RichInputText input = new RichInputText();
input.setValueExpression("value",getValueExpression("#{bindings."+item+".inputValue}"));
input.setValueExpression("label",getValueExpression("#{bindings."+item+".hints.label}"));
input.setId(item);
panelForm.getChildren().add(input);



// catch an exception and show it in the jsf page
catch(Exception e) {
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), "");
FacesContext.getCurrentInstance().addMessage(null, msg);
}


FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_WARN, msgHead , msgDetail);
facesContext.addMessage(uiComponent.getClientId(facesContext), msg);


// reset all the child uicomponents
private void resetValueInputItems(AdfFacesContext adfFacesContext,
UIComponent component){
List items = component.getChildren();
for ( UIComponent item : items ) {

resetValueInputItems(adfFacesContext,item);

if ( item instanceof RichInputText ) {
RichInputText input = (RichInputText)item;
if ( !input.isDisabled() ) {
input.resetValue() ;
adfFacesContext.addPartialTarget(input);
};
} else if ( item instanceof RichInputDate ) {
RichInputDate input = (RichInputDate)item;
if ( !input.isDisabled() ) {
input.resetValue() ;
adfFacesContext.addPartialTarget(input);
};
}
}
}

// redirect to a other url
ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
HttpServletResponse response = (HttpServletResponse)ectx.getResponse();
String url = ectx.getRequestContextPath()+"/adfAuthentication?logout=true&end_url=/faces/start.jspx";

try {
response.sendRedirect(url);
} catch (Exception ex) {
ex.printStackTrace();
}

// PPR refresh a jsf component
AdfFacesContext.getCurrentInstance().addPartialTarget(UIComponent);


// find a jsf component
private UIComponent getUIComponent(String name) {
FacesContext facesCtx = FacesContext.getCurrentInstance();
return facesCtx.getViewRoot().findComponent(name) ;
}


// get the adf bc application module
private OEServiceImpl getAm(){
FacesContext fc = FacesContext.getCurrentInstance();
Application app = fc.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = fc.getELContext();
ValueExpression valueExp =
elFactory.createValueExpression(elContext, "#{data.OEServiceDataControl.dataProvider}",
Object.class);
return (OEServiceImpl)valueExp.getValue(elContext);
}


// change the locale
Locale newLocale = new Locale(this.language);
FacesContext context = FacesContext.getCurrentInstance();
context.getViewRoot().setLocale(newLocale);


// get the stacktrace of a not handled exception
private ControllerContext cc = ControllerContext.getInstance();

public String getStacktrace() {
if ( cc.getCurrentViewPort().getExceptionData()!=null ) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
cc.getCurrentViewPort().getExceptionData().printStackTrace(pw);
return sw.toString();
}
return null;
}


// get the selected rows from a table component
RowKeySet selection = resultTable.getSelectedRowKeys();
Object[] keys = selection.toArray();
List receivers = new ArrayList(keys.length);
for ( Object key : keys ) {
User user = modelFriends.get((Integer)key);
}

// get selected Rows of a table 2
for (Object facesRowKey : table.getSelectedRowKeys()) {
table.setRowKey(facesRowKey);
Object o = table.getRowData();
JUCtrlHierNodeBinding rowData = (JUCtrlHierNodeBinding)o;
Row row = rowData.getRow();
Test testRow = (Test)((DCDataRow)row).getDataProvider() ;
}