Posts tonen met het label ADF. Alle posts tonen
Posts tonen met het label ADF. Alle posts tonen

maandag 5 september 2011

How to create a linking analysis overview

Technology: ADF11g
Developed in: JDeveloper 11.1.1.3.0
Browsers tested: Firefox 6.0.1 and Internet explorer 8 (8.0.6001.18702 64 bit edition)


Summary



I received a question is it possible to create a representation like shown below in ADF? In this blog a description how to solve this.



Database



In a database a table tst_cases is created:
Column name Datatype Mandatory Constraint(s)
ID Number(10,0) Yes Primary key
Name Varchar2(100) Yes Unique key
PARENT_CSE_ID Number(10,0) No Foreign key to ID


It's filled with content:
ID NAME PARENT_CSE_ID
1 Case 1
10 Case 10 1
20 Case 20 1
30 Case 30 1
101 Case 101 10
102 Case 102 10
201 Case 201 20
202 Case 202 20
203 Case 203 20



Model layer



Create with the Business Components for Tables an entity for the table (name Case), a view object for the entity (name CasesView) and an application module (name TestAppModule). An association and view link will be created as well.

Create another view object with name RootCasesView that uses the Case enity object but with where clause PARENT_CSE_ID IS NULL. Create a view link from the RootCasesView to the CasesViwe (using the Case_ParentCase_FK association):



View controller



  1. Create a page (HierachyViewer.jspx) and add it to the adfc-config.
  2. Drag and drop from the data controls palette the RootCasesView as hierarchy viewer:


  3. Choose radial:


  4. Select in hierarchy all 3 levels (and accept all other default values):


If this created page is run the page opens like this:



You can click on the + sign underneath the Case 10 box and then the page looks like this:



I would like to display all children on page opening. To achieve this you can just set the displayLevelsChildren property on the dvt:hierarchyViewer tag to 100 then it will display 100 children (if they exist). However I choose to set this property to the max number of levels that are currently present in the database table.

Determine the max number of levels



To determine the max number of levels 2 functions are created (implementation of the functions are found at the end of the blog):
  1. Get_levels_to_root (i_n_cse_id IN tst_cases.id%TYPE); this function returns the number of levels between i_n_cse_id and the root tst_cases (with parent_cse_id null)
  2. Get_max_number_of_children; this functions loops over all tst_cases and executes get_levels_to_root for the current id, the max number found is returned.
A view object (read only) is created that executes this function (and is added to the application module):



A managed bean (request scope) is created to execute this view object and return the MaxNumber attribute as int:



The implementation of this bean:

package nl.capgemini.marianneHorsch.view;



import javax.faces.context.FacesContext;

import nl.capgemini.marianneHorsch.model.services.TestAppModuleImpl;

import nl.capgemini.marianneHorsch.model.views.MaxNumberOfChildrenViewImpl;

import nl.capgemini.marianneHorsch.model.views.MaxNumberOfChildrenViewRowImpl;



import oracle.adf.model.binding.DCBindingContainer;

import oracle.adf.model.binding.DCDataControl;

import oracle.binding.BindingContainer;



public class TestHierarchyViewBean {

public TestHierarchyViewBean() {

super();

}



public int getMaxNumberOfChildren() {

TestAppModuleImpl service = getService();

MaxNumberOfChildrenViewImpl view = service.getMaxNumberOfChildrenView();

view.executeQuery();

MaxNumberOfChildrenViewRowImpl row =

(MaxNumberOfChildrenViewRowImpl)view.first();

return (row == null ? 1 : (row.getMaxNumber() == null ? 1 :

row.getMaxNumber().intValue()));

}



public TestAppModuleImpl getService() {

DCBindingContainer bc = (DCBindingContainer)FacesContext

.getCurrentInstance().getApplication().evaluateExpressionGet

(FacesContext.getCurrentInstance(), "#{bindings}",

BindingContainer.class);

if (bc == null) {

return null;

}

DCDataControl dc = bc.findDataControl("TestAppModuleDataControl");

if (dc == null) {

return null;

}

return (TestAppModuleImpl)dc.getDataProvider();

}

}

Add to the <dvt:hierarchyViewer> tag the property displayLevelsChildren set the value to #{hierarchyViewerBean.maxNumberOfChildren}.

If we now run the page it opens like:



Function: get_levels_to_root



CREATE OR REPLACE FUNCTION get_levels_to_root

( i_n_cse_id IN tst_cases.id%TYPE)

RETURN NUMBER

AS

--

CURSOR c_cse (b_parent_id tst_cases.parent_cse_id%TYPE)

IS

SELECT id, name, parent_cse_id

FROM tst_cases

WHERE id = b_parent_id;

r_cse c_cse%ROWTYPE;

l_b_found BOOLEAN;

--

l_n_id tst_cases.id%TYPE;

l_n_levels NUMBER(10,0) := 0;

--

BEGIN

--

l_n_id := i_n_cse_id;

--

WHILE (l_n_id IS NOT NULL)

LOOP

--

OPEN c_cse (b_parent_id => l_n_id);

FETCH c_cse

INTO r_cse;

l_b_found := c_cse%FOUND;

CLOSE c_cse;

--

IF (l_b_found)

THEN

l_n_levels := l_n_levels + 1;

l_n_id := r_cse.parent_cse_id;

ELSE

l_n_id := NULL;

END IF;

--

END LOOP;

--

RETURN l_n_levels;

--

END get_levels_to_root;


Function: get_max_number_of_children



CREATE OR REPLACE FUNCTION get_max_number_of_children

RETURN NUMBER

AS

--

l_n_number NUMBER(10,0);

l_n_max_number NUMBER(10,0) := 0;

--

BEGIN
--

FOR r IN (SELECT id

FROM tst_cases)

LOOP

--

l_n_number := get_levels_to_root(i_n_cse_id =>r.id);

IF (l_n_number > l_n_max_number)

THEN

l_n_max_number := l_n_number;

END IF;

--

END LOOP;

--

RETURN l_n_max_number;

--

END get_max_number_of_children;

vrijdag 4 maart 2011

How to create a custom LOV

Technology: ADF11g
Developed in: JDeveloper 11.1.1.3.0
Browsers tested: Firefox 3.6.13 and Internet explorer 7 (7.0.6002.18005)
Used database schema: HR
Used tables: EMPLOYEES, DEPARTMENTS, LOCATIONS


Summary

In this blog we create ‘standard’ LOVs and a custom LOV. A custom LOV is in the end created because of some disadvantages I see in the standard LOVs like:
  • Possibility to resize LOV popup
  • All columns in the LOV table have the same width

Standard LOV

First we’ll create a standard LOV. With a standard LOV I mean a LOV defined in the view object as a List of Values on the ID column.

For this example the EMPLOYEES table is used with LOVs on the ManagerId attribute and DepartmentId attribute (the DepartmentId LOV is created in the next paragraph).

Model layer

Create the following entities:

Entity name Based on table of HR schema Customizations made
Employee EMPLOYEES None


Create the following view objects:

View object name Based on entities Customizations made
EmployeesLovView Employee None
ManagersView Employee None


Open the EmployeesLovView and go to the ManagerId attribute. Add a List of Values:



The ManagersView is the view accessor (renamed to ManagersAccessor), the view attribute is the ManagerId and the list attribute the EmployeeId. On the UI Hints tab set the following properties:

Property Value
Default List Type Input Text with List of Values
Display Attributes Select all
List Search <No Search>
"Include No Selection" Item Deselect all


Create an application module HrAppModule which exposes the EmployeesView.

Page

A form page is created by drag and drop from the Data Controls. The form is dropped as ADF Form only the EmployeeId, FirstName, LastName, JobId and ManagerId items are displayed. All items except ManagerId are displayed as Output text with label. ManagerId is displayed as input list of values:





Select Include Navigation Controls and Include Submit Button.

If we run this page it looks like this:



The opened popup contains scrollbars and is not resizable. When a row is selected (by double click or by using the OK button) the ID of the employee is copied to the ManagerId attribute.

Extended standard LOV

The first thing I thing needs to be changed is that the ManagerId is displayed. I think the managers name is a more desirable field to see (of course in the database the manager ID should be filled).

To create an example to show how this can be achieved another LOV is created for the department. In the screen we’ll display the department name and the LOV is on this name but the department ID is filled as well (to prove this the department ID will be made visible but read only in the page).

Model layer

Create the following entities:

Entity name Based on table of HR schema Customizations made
Department DEPARTMENTS None
Location LOCATIONS None


A FK association will be created at the same time between Department and Location.

Create the following view objects:

View object name Based on entities Customizations made
DepartmentsLocationView Department

Location
None


Change the EmployeesLovView:
  • Add a transient attribute DepartmentLovName of type String
  • Make the attribute always updatable
  • Check the Mapped to Column or SQL checkbox
  • Fill the expression of the Query Column:
    • (SELECT department_name FROM departments WHERE department_id = Employee.department_id)
  • Set the type of the Query Column to VARCHAR2(30)


The last 3 steps are necessary to display the current department name when the page is opened.
  • Add a List of Values to the DepartmentLovName attribute:


The DepartmentsLocationView is the view accessor (renamed to DepartmentsLocationAccessor), the view attribute is the DepartmenLovName and the list attribute the DepartmentName.

Add a second return value from DepartmentId to DepartmentId:



On the UI Hints tab set the following properties:

Property Value
Default List Type Input Text with List of Values
Display Attributes Select all
List Search <No Search>
"Include No Selection" Item Deselect all



Page

Drop the DepartmentId and DepartmentLovName attribute from the Data Controll palette onto the page created for the Manager LOV. The DepartmentId is displayed as Output text with label, the DepartmentLovName as Input list of values.

If we run this page it looks like this:



When a row is selected (by double click or by using the OK button) the Name and the ID of the department is copied to the page. That is an improvement compared to the Manager ID. But the opened popup still contains scrollbars and is not resizable.

Create a custom (resizable) LOV

Finally we’ll create a resizable LOV. This is also done for the department.

Model layer

Change the EmployeesLovView (make a copy of DepartmentLovName):
  • Add a transient attribute DepartmentLovName2 of type String
  • Make the attribute always updatable
  • Check the Mapped to Column or SQL checkbox
  • Fill the expression of the Query Column:
    • (SELECT department_name FROM departments WHERE department_id = Employee.department_id)
  • Set the type of the Query Column to VARCHAR2(30)

Page

Drop the DepartmentId (same as used for the department LOV) and DepartmentLovName2 attribute from the Data Controll palette onto the page underneath a seperator. The DepartmentId is displayed as Output text with label, the DepartmentLovName2 as Input text with label.

Surround the DepartmentLovName2 input text in a panelGroup with layout style horizontal. After the input text add a command image link with the LOV icon. The command link triggers a popup:

<af:panelGroupLayout id="lovGroup"

layout="horizontal">

<af:inputText value="#{bindings.DepartmentLovName21.inputValue}"

label="#{bindings.DepartmentLovName21.hints.label}"

required="#{bindings.DepartmentLovName21.hints.mandatory}"

columns="#{bindings.DepartmentLovName21.hints.displayWidth}"

maximumLength="#{bindings.DepartmentLovName21.hints.precision}"

shortDesc="#{bindings.DepartmentLovName21.hints.tooltip}"

id="departmentLovNameInputText">

<f:validator binding="#{bindings.DepartmentLovName21.validator}"/>

</af:inputText>

<af:commandImageLink id="departmentLovNameCommandLink"

icon="/common/images/lov.png">

<af:showPopupBehavior popupId="departmentLovPopup"

triggerType="action"/>

</af:commandImageLink>

</af:panelGroupLayout>

The picture (lov_ena.png) can be copied from:
  • Run your application, in the IntegratedWebLogicServer log you see a destination where the EAR is copied to. On my computer is that:
    • [03:25:38 PM] Wrote Web Application Module to C:\Users\mhorsch\AppData\Roaming\JDeveloper\system11.1.1.3.37.56.60\o.j2ee\drs\HR_demo_app\ViewControllerWebApp.war
  • Go to the o.j2ee folder and in that folder go to: \.wlLibs\jsp
  • Open the ADF-Faces-Components11.war
  • Go to \WEB-INF\lib and open the adf-richclient-impl-11.jar jar file
  • Go to adf\images
The popup only contains the DepartmentsLocationView as read only table. First create the popup:

<af:popup id="departmentLovPopup">

<af:dialog id="lovDialog"

title="LOV"

type="okCancel"

dialogListener="#{employeeBean.lovDialogListeners}"

resize="on"

contentWidth="600"

stretchChildren="first">

</af:dialog>

</af:popup>

This popup is 600 pixels width by default and resizable. If the dialog is closed lovDialogListeners of the employeeBean is called.

This bean class is defined in the unbound task flow:

Managed bean property Value
Name employeeBean
Class nl.hr.demo.view.beans.EmployeeBean
Scope request


The DepartmentsLocationView table is inserted in the dialog by drag and drop from the data control palette:





The Row Selection property must be checked, this causes the following properties to be set in the table:

Property Value
selectedRowKeys #{bindings. DepartmentsLocationView.collectionModel.selectedRow}
selectionListener #{bindings. DepartmentsLocationView.collectionModel.makeCurrent}
rowSelection single


Although in the JSPX page the selectedRowKeys and selectionListener statements contains warnings that the references methods cannot be found they can be found runtime.

In the EmployeeBean we have to implement the lovDialogListeners method. The method is only executed when the LOV is closed by the OK button. In the method the department ID and name of the selected row are copied to the EmployeesLovView row:

package nl.hr.demo.view.beans;



import javax.faces.context.FacesContext;

import nl.hr.demo.model.services.HrAppModuleImpl;

import oracle.adf.model.binding.DCBindingContainer;

import oracle.adf.model.binding.DCDataControl;

import oracle.adf.view.rich.event.DialogEvent;

import oracle.binding.BindingContainer;

import oracle.jbo.domain.Number;

import oracle.jbo.server.ViewRowImpl;



public class EmployeeBean {

public EmployeeBean() {

super();

}



private static HrAppModuleImpl getService() {

DCBindingContainer bc = (DCBindingContainer)FacesContext.getCurrentInstance().getApplication().evaluateExpressionGet(FacesContext.getCurrentInstance(), "#{bindings}", BindingContainer.class);

DCDataControl dc = bc.findDataControl("HrAppModuleDataControl");

return (HrAppModuleImpl) dc.getDataProvider();

}



public void lovDialogListeners(DialogEvent dialogEvent) {

ViewRowImpl row = (ViewRowImpl)getService().getDepartmentsLocationView().getCurrentRow();

if (row != null) {

Number departmentId = (Number) row.getAttribute("DepartmentId");

String departmentName = (String)row.getAttribute("DepartmentName");

ViewRowImpl employeeRow = (ViewRowImpl)getService().getEmployeesLovView().getCurrentRow();

employeeRow.setAttribute("DepartmentId", departmentId);

employeeRow.setAttribute("DepartmentLovName2", departmentName);

}

}

}

If we run this page it looks like this:



The popup is resizable, the name and id are copied and refreshed and the width of each column can be modified individually (by setting the width property of the af:column).

donderdag 3 maart 2011

How to convert input to uppercase

Technology: ADF11g
Developed in: JDeveloper 11.1.1.3.0
Browsers tested: Firefox 3.6.13 and Internet explorer 7 (7.0.6002.18005)
Used database schema: HR
Used tables: EMPLOYEES


Summary

In this blog four different solutions are provided to convert text to uppercase:
  • Convert to uppercase in the model layer
  • Convert to uppercase with java script
  • Convert to uppercase in a java bean
  • Convert to uppercase using a converter
The first and last two solutions only change the complete text to uppercase when the user leaves the input field. The second solution immediately changes each letter the user types to uppercase.

The third and fourth solution is created for the scenario that the input field is not bound to the model layer. But they can also be used if they are bound to the model.

Setup example application

For this blog the EMPLOYEES table of the HR schema is used. An input form containing a few input fields of this table is created.

Model layer

Create the following entities:

Entity name Based on table of HR schema Customizations made
Employee EMPLOYEES None


Create the following view objects:

View object name Based on entities Customizations made
EmployeesView Employee None


Create an application module HrAppModule which exposes the EmployeesView.


Form page

The form page is created by drag and drop from the Data Controls. The form is dropped as ADF Form only the FirstName, LastName, Email, PhoneNumber and JobId items are displayed (the text items).



Employee bean

In the form page we will make references to a java bean class. This bean class is defined in the unbound task flow:

Managed bean property Value
Name employeeBean
Class nl.hr.demo.view.beans.EmployeeBean
Scope Request

Solution 1: Convert to uppercase in the model layer

This solution will be applied to the first and last name attributes. To create a generic solution a new java class is created in a Common project. The Model and ViewController projects contain dependencies to this Common project.

The java class created is called HrEntityObjectImpl and it extends EntityImpl. The Employee entity object extends HrEntityObjectImpl.

HrEntityObjectImpl

The implementation of this class:

package nl.hr.demo.model.common;



import oracle.jbo.AttributeDef;

import oracle.jbo.server.EntityImpl;



public class HrEntityObjectImpl extends EntityImpl {

public HrEntityObjectImpl() {

super();

}



@Override

protected void setAttributeInternal(int i, Object object) {

AttributeDef attrDef = getEntityDef().getAttributeDef(i);

if (attrDef != null && attrDef.getJavaType().getName().equals("java.lang.String")) {

String caseProperty = getEntityDef().getAttributeDef(i).getProperty("CASE").toString();

if (caseProperty != null && !caseProperty.equals("")) {

String value = (String)object;

if (caseProperty.equals("UPPER")) {

value = value.toUpperCase();

} else if (caseProperty.equals("LOWER")) {

value = value.toLowerCase();

}

object = value;

}

}

super.setAttributeInternal(i, object);

}

}

The overridden method looks for each attribute if it contains a CASE property. If it contains this property and the value is UPPER then the value is set to uppercase, if it is LOWER than the value is set to lower case.

Employee entity

Let the Employee entity extend the created HrEntityObjectImpl class. This can be done in the Java tab, click edit and then Classes Extend:



For the FirstName and LastName attributes create a custom property CASE with value UPPER, this can be done in the Attribute tab, double click on the attribute and add a Custom Property:



Form page

In the form page adjust the FirstName and LastName attributes, set the autoSubmit and partialTrigger property. When the user leaves the field the attribute will be submit to the model layer and refreshed.

Set the autoSubmit property to true and the partialTrigger to its own id. Example of LastName:

<af:inputText value="#{bindings.LastName.inputValue}"

label="#{bindings.LastName.hints.label}"

required="#{bindings.LastName.hints.mandatory}"

columns="#{bindings.LastName.hints.displayWidth}"

maximumLength="#{bindings.LastName.hints.precision}"

shortDesc="#{bindings.LastName.hints.tooltip}"

id="it6"

autoSubmit="true"

partialTriggers="it6">

<f:validator binding="#{bindings.LastName.validator}"/>

</af:inputText>

The result when the user is typing:


And after leaving the field:


Solution 2: Convert to uppercase with java script

This solution will be applied to the email attribute. To create a generic solution a java script file is created instead of defining the java code in the page.

Because using the af:resource tag in a page template resulted in not finding the java script method the Trinidad tag is used instead to include the java script:

<trh:script source="../../common/javaScript/hrScript.js" id="hrScript"></trh:script>

Note: to include the Trinidad tag library open the project properties of the ViewController, go to the JSP Tag Library tab and includeTrinidad Components 1.2 (prefix tr) and Trinidad HTML Components 1.2 (prefix trh) in the jsp root of the page (template) add:

xmlns:trh=http://myfaces.apache.org/trinidad/html

The java script method will be executed for each keyboard button. Convert the input the uppercase is only necessary when the button is a letter. The java script method:

function isLetter(keyCode) {

if ( keyCode == "A" || keyCode == "B" || keyCode == "C" || keyCode == "D"

|| keyCode == "E" || keyCode == "F" || keyCode == "G" || keyCode == "H"

|| keyCode == "I" || keyCode == "J" || keyCode == "K" || keyCode == "L"

|| keyCode == "M" || keyCode == "N" || keyCode == "O" || keyCode == "P"

|| keyCode == "Q" || keyCode == "R" || keyCode == "S" || keyCode == "T"

|| keyCode == "U" || keyCode == "V" || keyCode == "W" || keyCode == "X"

|| keyCode == "Y" || keyCode == "Z") {

return true;

}

return false;

}



function convertCase(event) {

var keyChar = AdfKeyStroke.getKeyStroke(event.getKeyCode()).toMarshalledString();

if (isLetter(keyChar)) {

var field = event.getCurrentTarget();

var value = field.getSubmittedValue();

field.setValue(value.toUpperCase());

return true;

}

}

In the page we have to trigger this java script method. This is done by adding a clientListener to the email attribute that triggers the java script everytime the user releases a key:

<af:inputText value="#{bindings.Email.inputValue}"

label="#{bindings.Email.hints.label}"

required="#{bindings.Email.hints.mandatory}"

columns="#{bindings.Email.hints.displayWidth}"

maximumLength="#{bindings.Email.hints.precision}"

shortDesc="#{bindings.Email.hints.tooltip}"

id="it1">

<af:clientListener type="keyUp"

method="convertCase"/>

</af:inputText>

Now it’s impossible to make a screen shot of lower case letters:


Solution 3: Convert to uppercase in a java bean

For this solution the model is not used. In new inputText is added to the page instead:

<af:inputText value="#{employeeBean.transientField}"

autoSubmit="true"

partialTriggers="transientField"

label="Transient field"

id="transientField"/>

This item is bound to the employeeBean. A class variable transientField (String) is added and its accessors.

The result when the user is typing:


And after leaving the field:


Solution 4: Convert to uppercase using a converter

This solution will be applied to the job ID attribute.

A custom converter class is created which implements the Converter interface. This class converts given string to uppercase:

package nl.hr.demo.view.converters;



import javax.faces.component.UIComponent;

import javax.faces.context.FacesContext;

import javax.faces.convert.Converter;



public class UpperCaseConverter implements Converter {

public UpperCaseConverter() {

super();

}



public String getAsString(FacesContext fc, UIComponent uIComponent, Object object) {

return object.toString();

}

public Object getAsObject(FacesContext fc, UIComponent uIComponent, String string) {

return string.toUpperCase();

}

}

The converter is added to the faces-config.xml so it can be used in the pages:



In the form page adjust the JobId attribute, set the converter, autoSubmit and partialTrigger property. When the user leaves the field the attribute will be submit to the model layer and refreshed.

Set the converter to the created converter (id), autoSubmit property to true and the partialTrigger to its own id:

<af:inputText value="#{bindings.JobId.inputValue}"

label="#{bindings.JobId.hints.label}"

required="#{bindings.JobId.hints.mandatory}"

columns="#{bindings.JobId.hints.displayWidth}"

maximumLength="#{bindings.JobId.hints.precision}"

shortDesc="#{bindings.JobId.hints.tooltip}"

id="it2"

partialTriggers="it2"

autoSubmit="true"

converter="upperCaseConverter">


</af:inputText>

The result when the user is typing:


And after leaving the field:

woensdag 2 maart 2011

How to create web service based ADF pages

Technology: ADF11g
Developed in: JDeveloper 11.1.1.3.0
Used database schema: none


Summary

In this blog a solution is provided how to create a web service client. This blog is part of a sequence of 3 blogs:
  • How to create a RESTful web service that returns objects
  • How to create a web service client
  • How to create web service based ADF pages
I choose for a solution that:
  • Works for SOAP and RESTful web services
  • The location of the web service host can be changed while running the web service
Especially changing the host was an important criteria for me. For development I would like to use a development webservice and for production of course a production server.

The solution is build into my existing demo ADF application.

Step 1

Create a Common (generic) project in the demo ADF application add the following libraries:
  • BC4J Oracle Domains
  • Oracle JDBC
  • JSF 1.2
  • Commons Logging 1.0.4
And add the HrWebServiceClient.jar created in the ‘How to create a web service client’ blog.

Open the project properties of the Model project and set the dependency to the Common project:



Open the project properties of the ViewController project and also set the dependency to the Common project.

Step 2

In the Common project a basic view object implementation is created that will be used for all web service based view objects.

The class contains converters that converts Oracle data types to Java data types, it sets the end point based on the information of the web.xml (in the ViewController project) and has methods to execute the webservice.

Create a abstract java class WsViewObjectImpl which extends ViewObjectImpl. The implementation:

package nl.hr.demo.model.common;



import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Timestamp;

import java.util.Iterator;

import java.util.List;

import javax.faces.context.FacesContext;

import oracle.jbo.server.ViewObjectImpl;

import oracle.jbo.server.ViewRowImpl;

import oracle.jbo.server.ViewRowSetImpl;



public abstract class WsViewObjectImpl extends ViewObjectImpl {

public WsViewObjectImpl() {

super();

}



protected String getWSBaseURL() {

return FacesContext.getCurrentInstance().getExternalContext().getInitParameter("wsBaseURL");

}



protected oracle.jbo.domain.Date toOracleDate(java.util.Calendar calendar) {

oracle.jbo.domain.Date jboDate = new oracle.jbo.domain.Date();

Timestamp t = jboDate.timestampValue();

t.setTime(calendar.getTime().getTime());

return new oracle.jbo.domain.Date(t);

}

protected oracle.jbo.domain.Number toOracleNumber(int i) {

return new oracle.jbo.domain.Number(i);

}

protected oracle.jbo.domain.Number toOracleNumber(double d) {

try {

return new oracle.jbo.domain.Number(d);

} catch (SQLException e) {

return null;

}

}



protected abstract List retrieveArrayFromWebService(Object qc, Object[] params);

private void storeNewIterator(Object qc, List rs) {

setUserDataForCollection(qc, rs.iterator());

hasNextForCollection(qc);

}

protected void executeQueryForCollection(Object qc, Object[] params, int noUserParams) {

storeNewIterator(qc, retrieveArrayFromWebService(qc, params));

super.executeQueryForCollection(qc, params, noUserParams);

}



private Iterator getArrayIterator(Object qc) {

return (Iterator)getUserDataForCollection(qc);

}

protected boolean hasNextForCollection(Object qc) {

boolean hasNext = getArrayIterator(qc).hasNext();

if (!hasNext) {

setFetchCompleteForCollection(qc, true);

}

return hasNext;

}



protected abstract void fillRow(Object data, ViewRowImpl row);

protected ViewRowImpl createRowFromResultSet(Object qc, ResultSet resultSet) {

Iterator iterator = getArrayIterator(qc);

ViewRowImpl row = createNewRowForCollection(qc);

fillRow(iterator.next(), row);

return row;

}



public long getQueryHitCount(ViewRowSetImpl viewRowSet) {

return super.getQueryHitCount(viewRowSet);

}

}


Step 3

Create a new programmatic view object in the Model project. The new view object:
  • Is programmatically
  • Extends the WsViewObjectImpl class
  • Contains a RowImpl class
  • Has a bind variable b_id data type Number
  • All attributes (of the EmployeeClient) are updatable
  • The EmployeeId attribute is Key Attribute.




Open the view object impl class (EmployeesWsImpl) and implement it (only added / changed methods are described below):

package nl.hr.demo.model.views.ws;



import java.util.ArrayList;

import java.util.List;

import nl.hr.demo.webservices.Employee;

import nl.hr.demo.webservices.client.EmployeeClient;

import oracle.jbo.server.ViewRowImpl;



public class EmployeesWsImpl extends WsViewObjectImpl {

protected List retrieveArrayFromWebService(Object qc, Object[] params) {

try {

EmployeeClient client = new EmployeeClient(getWSBaseURL());

if (getb_id() == null) {

return client.getAllEmployees();

} else {

List<Employee> result = new ArrayList<Employee>();

result.add(client.getEmployeeById(getb_id().intValue()));

return result;

}

} catch (Exception e) {

e.printStackTrace();

return null;

}

}



protected void fillRow(Object data, ViewRowImpl row) {

Employee empe = (Employee) data;

populateAttributeForRow(row, EmployeesWsRowImpl.EMPLOYEEID, toOracleNumber(emp.getEmployeeId()));

populateAttributeForRow(row, EmployeesWsRowImpl.FIRSTNAME, emp.getFirstName());

populateAttributeForRow(row, EmployeesWsRowImpl.LASTNAME, emp.getLastName());

populateAttributeForRow(row, EmployeesWsRowImpl.HIREDATE, toOracleDate(emp.getHireDate()));

populateAttributeForRow(row, EmployeesWsRowImpl.EMAIL, emp.getEmail());

populateAttributeForRow(row, EmployeesWsRowImpl.PHONENUMBER, emp.getPhoneNumber());

populateAttributeForRow(row, EmployeesWsRowImpl.JOBID, emp.getJobId());

populateAttributeForRow(row, EmployeesWsRowImpl.SALARY, toOracleNumber(emp.getSalary()));

populateAttributeForRow(row, EmployeesWsRowImpl.COMMISSIONPCT, toOracleNumber(emp.getCommissionPct()));

populateAttributeForRow(row, EmployeesWsRowImpl.MANAGERID, toOracleNumber(emp.getManagerId()));

populateAttributeForRow(row, EmployeesWsRowImpl.DEPARTMENTID, toOracleNumber(emp.getDepartmentId()));

}

}


Step 4

Add the view object to the application module.

Step 5

Create a new page: EmployeesWebServiceTable

Drag and drop the EmployeesWs onto it as read only table:



Add above the table a panelFormLayout containing:

<af:panelFormLayout id="pfl1">

<af:inputText binding="#{employeeBean.id}"

label="ID"

id="idFilter">

<af:convertNumber groupingUsed="false"

integerOnly="true"/>

</af:inputText>

<f:facet name="footer">

<af:commandButton text="Filter"

id="filter"

actionListener="#{employeeBean.filterWs}"/>

</f:facet>

</af:panelFormLayout>

Add to the af:table tag:

partialTriggers="::filter"

styleClass="AFStretchWidth"


Step 6

Create a java class EmployeeBean for the page. This bean class holds the ID input text and queries the view object when the filter button is used.

package nl.hr.demo.view.beans;



import javax.faces.context.FacesContext;

import nl.hr.demo.model.services.HrAppModuleImpl;

import nl.hr.demo.model.views.ws.EmployeesWsImpl;

import oracle.adf.model.binding.DCBindingContainer;

import oracle.adf.model.binding.DCDataControl;

import oracle.adf.view.rich.component.rich.input.RichInputText;

import oracle.binding.BindingContainer;

import oracle.jbo.domain.Number;



public class EmployeeBean {



private RichInputText id;



public EmployeeBean() {

super();

}



public void filterWs (ActionEvent actionEvent) {

EmployeesWsImpl view = getService().getEmployeesWs();

view.setb_id(getValue(id));

view.executeQuery();

}

private Number getValue(RichInputText item) {

if (item == null || item.getValue() == null) {

return null;

}

return new Number(((Long)item.getValue()).intValue());

}



private static HrAppModuleImpl getService() {

DCBindingContainer bc = (DCBindingContainer)FacesContext.getCurrentInstance().getApplication().evaluateExpressionGet(FacesContext.getCurrentInstance(), "#{bindings}", BindingContainer.class);

DCDataControl dc = bc.findDataControl("HrAppModuleDataControl");

return (HrAppModuleImpl) dc.getDataProvider();

}



public void setId(RichInputText id) {

this.id = id;

}

public RichInputText getId() {

return id;

}

}


Step 7

Add the page and the bean to the unbounded task flow:



Managed bean property Value
Name employeeBean
Class nl.hr.demo.view.beans.EmployeeBean
Scope Request

Step 8

Start the page it opens getAllEmployees is executed of the web service:



And if you fill an ID and click filter the web service is called again:

maandag 28 februari 2011

How to add a context menu in a table

Technology: ADF11g
Developed in: JDeveloper 11.1.1.3.0
Browsers tested: Firefox 3.6.13 and Internet explorer 7 (7.0.6002.18005)
Used database schema: HR
Used tables: EMPLOYEES


Summary



In ADF11 it is possible to create context menus in a table. This is a menu that can be opened by right clicking on a table row.

In this blog is described how to add a context menu in a table.

Overview of the context menu:



Setup example application



For this blog an example application is created based on the HR schema. The example application contains an employees table with 2 detail forms, one to insert and edit an employee without department) and 1 to change the department of the employee. The detail forms are created in separate pages. For the employees table and forms a bounded task flow is created this bounded task flow is started from the menu.


Model layer



Create the following entities:
Entity name Based on table of HR schema Customizations made
Employee EMPLOYEES None


Create the following view objects:
View object name Based on entities Customizations made
EmployeesView Employee None


Create an application module HrAppModule which exposes the EmployeesView.



Task flow




Unbounded task flow



The unbounded task flow form where we start with the solution looks like this:



There are no customizations made, the task flow is created by drag and drop.

Bounded task flow



The employees task flow is a bounded task flows:



The next properties are set:
Property Value
usePageFragments false

Share data controls with calling task flow true




Table page



The table pages are created by drag and drop from the Data Controls. The table is dropped as ADF Read-only table with Row Selection and Sorting checked, all columns are displayed.





The Row Selection property must be checked, this causes the following properties to be set in the table:
Property Value
selectedRowKeys #{bindings.EmployeesView.collectionModel.selectedRow}
selectionListener #{bindings.EmployeesView.collectionModel.makeCurrent}
rowSelection single


Although in the JSPX page the selectedRowKeys and selectionListener statements contains warnings that the references methods cannot be found they can be found runtime.

Form pages



The form pages are created by drag and drop from the Data Controls. The form is dropped as ADF Form.



To navigate back from the form to the table a rollback button (af:commandButton) is added by drag and drop the Rollback operation from the datacontrol palette as a button.



The submit button is created in the same way but then from the Commit operation.

The edit and insert employee page contains all fields but with department ID readOnly. The change department page contains the employee ID, first name, last name and department ID. All fields except department ID are read only.

Add the context menu



An ADF table contains a facet named contextMenu. With this facet a menu popup can be created that pops up when the user right clicks on a table row. If the table contains no rows the context menu does not popup on right click.

Insert in the table the contextMenu facet. This facet should contain a popup and in this popup a menu can be defined. Submenu entries can be created by inserting another menu tag in the menu:

<f:facet name="contextMenu">

<af:popup id="popup">

<af:menu id="menu">

<af:menu id="employeeMenu"

text="Employee">

<af:commandMenuItem text="Edit"

id="editEmployeeMenu"

action="edit"/>

<af:commandMenuItem text="Insert"

id="insertEmployeeMenu"

action="edit"

actionListener="#{bindings.CreateInsert.execute}"/>

</af:menu>

<af:menu id="departmentMenu"

text="Department">

<af:commandMenuItem text="Change department for employee"

id="changeMenu"

action="change"/>

</af:menu>

<af:commandMenuItem text="Cancel"

id="cancelMenu"

action="cancel"/>

</af:menu>

</af:popup>

</f:facet>

The insert menu option is created by drag and drop the CreateInsert operation of the EmployeesView, the action is overridden so it navigates to the same page as edit employee:



When the user for example choses Change department for employee:



This results in: