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:

How to create a web service client

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.

Step 1

Create a new generic application in JDeveloper, call the project RpcWebServiceProject:



Step 2

On the project choose New – Web Service Proxy (under Business Tier – Web Services).


Choose:
  • Client Style: JAX-RPC Web Logic Style
  • Copy the URL or the location of the WSDL file
    • For this example we use: http://localhost:7101/HrWebServices-HrWebServicesProject-context-root/EmployeesWebPort?WSDL
  • Specify a package name:
    • For example: nl.hr.demo.webservice.client.employees
  • Leave all other settings to their default
A lot of files have been created in the project. The EmployeesWebPortClient class contains the entry point of calling the web service.

To make maintenance easier create a new project where a new entry point for each web service is created. If the web service ever changes then the sources in the RpcWebServiceProject project can be regenerated (right click on the EmployeesWebServiceProxy – Regenerate web service) and know custom code get lost.

Step 3

Create a new project HrWebServiceProject containing two java classes:
  • EmployeeClient (package nl.hr.demo.webservices.client)
  • HrWebServiceClient (package nl.hr.demo.webservices)
Set the dependencies of the HrWebServiceProject, add RpcWebServiceProject.

The HrWebServiceClient class is a generic class that creates the WSDL URL for given server location and contains methods to convert data types:

package nl.hr.demo.webservices;



import java.math.BigInteger;

import java.net.MalformedURLException;

import java.net.URL;

import java.util.ArrayList;

import java.util.List;



public class HrWebServiceClient {

private String webserviceBaseURL;



public HrWebServiceClient() {

super();

}

public HrWebServiceClient(String webserviceBaseURL) {

this.webserviceBaseURL = webserviceBaseURL;

}



protected String getWebserviceUrlAsString(String webservice) {

return webserviceBaseURL + "/" + webservice;

}

protected URL getWebserviceUrl(String webservice) {

URL wsdlLocationURL = null;

try {

wsdlLocationURL = new URL(getWebserviceUrlAsString(webservice));

} catch (MalformedURLException e) {

return null;

}

return wsdlLocationURL;

}



protected List convertToList(Object[] input) {

List list = new ArrayList();

for (int i = 0; i < input.length; i++) {

list.add(input[i]);

}

return list;

}

}

The EmployeeClient extends the HrWebServiceClient:

package nl.hr.demo.webservices.client;



import java.util.List;



import nl.hr.demo.webserivce.client.employees.EmployeesWebPortClient;

import nl.hr.demo.webservices.HrWebServiceClient;

import nl.hr.demo.webservices.Employee;



public class EmployeeClient extends HrWebServiceClient {

private static final String WSDL_NAME = "HrWebServices-HrWebServicesProject-context-root/EmployeesWebPort?WSDL";



public EmployeeClient() {

super();

}

public EmployeeClient(String webserviceBaseURL) {

super(webserviceBaseURL);

}



private EmployeesWebPortClient getClient() throws Exception {

EmployeesWebPortClient client = new EmployeesWebPortClient();

client.setPortCredentialProviderList();

client.setEndpoint(getWebserviceUrlAsString(WSDL_NAME));

return client;

}



public Employee getEmployeeById(int id) throws Exception {

EmployeesWebPortClient client = getClient();

return client.getEmployeeById(id);

}



public List getAllEmployees() throws Exception {

EmployeesWebPortClient client = getClient();

Employee[] result = client.getAllEmployees(null).getReturn();

return convertToList(result);

}

}

For each method in the web service a method is created in the java class. For test purposes some code can be added so the web service client can be executed from JDeveloper:

public static void main(String[] args) {

String LOCALHOST = "http://localhost:7101";

try {

System.err.println("Search employee ID 100");

Employee emp = new EmployeeClient(LOCALHOST).getEmployeeById(100);

print(emp);

System.err.println("Search employee ID 101");

emp = new EmployeeClient(LOCALHOST).getEmployeeById(101);

print(emp);

System.err.println("Search employee ID 102");

emp = new EmployeeClient(LOCALHOST).getEmployeeById(102);

print(emp);

System.err.println("Search all employees");

List result = new EmployeeClient(LOCALHOST).getAllEmployees();

for (int i = 0; i < result.size(); i++) {

print(result.get(i));

}

if (result.size() == 0) {

System.err.println("niets terug");

}

} catch (Exception e) {

e.printStackTrace();

}

}



private static void print(Employee employee) {

System.err.println(employee.getEmployeeId() + ": " +

employee.getFirstName() + " " +

employee.getLastName());

}

The result of this is:

Search employee ID 100

100: Steven King

Search employee ID 101

101: Neena Kochhar

Search employee ID 102

102: Lex De Haan

Search all employees

100: Steven King

101: Neena Kochhar

102: Lex De Haan


Step 4

Create a deployment profile (JAR file) for the HrWebServiceProject and create the jar file. This file will be needed in the next blog ‘How to create web service based ADF pages’.

dinsdag 1 maart 2011

How to create a RESTful web service that returns objects

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 RESTful web service that returns objects. One web service will be created with 2 methods to return an Employee instance and a list of Employee instances.

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

Step 1

Create a new generic application in JDeveloper:



Step 2

Download the 'zip of Jersey' of the page:

http://jersey.java.net/nonav/documentation/latest/chapter_deps.html

Step 3

Extract the zip and copy the following jar files to the new created application (in a lib folder):
  • Asm-3.1.jar
  • Jersey-core-1.5.jar
  • Jersey-server-1.5.jar
  • Jersey-json-1.5.jar

Step 4

Open the project properties of the project in the new application and add these jar files (not the JAX-WS Web Services library will be added automatically later on):



Step 5

Create an Employee class which represents one employee (of the HR schema). Create accessors for all class variables. A second constructor is added so an employee can be created and initialized in one call.

Add above the class name the annotation XmlRootElement of class javax.xml.bind.annotation.XmlRootElement.

package nl.hr.demo.dataObjects;



import java.util.Date;

import javax.xml.bind.annotation.XmlRootElement;



@XmlRootElement

public class Employee {

private int employeeId;

private String firstName;

private String lastName;

private String email;

private String phoneNumber;

private Date hireDate;

private String jobId;

private double salary;

private double commissionPct;

private int managerId;

private int departmentId;



public Employee() {

super();

}

public Employee(int employeeId, String firstName, String lastName, String email, String phoneNumber, Date hireDate, String jobId, double salary, double commissionPct, int managerId, int departmentId) {

super();

setEmployeeId(employeeId);

setFirstName(firstName);

setLastName(lastName);

setEmail(email);

setPhoneNumber(phoneNumber);

setHireDate(hireDate);

setJobId(jobId);

setSalary(salary);

setCommissionPct(commissionPct);

setManagerId(managerId);

setDepartmentId(departmentId);

}



// For all class variables create accessors

public void setXXX (XXX xxx) {

this.xxx = xxx;

}

public XXX getXXX () {

return xxx;

}

}


Step 6

Create the web service class that returns one or a list of employees. If a web service contains several (GET) methods each method should have its own path.

package nl.hr.demo.webservices;



import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.List;

import javax.ws.rs.GET;

import javax.ws.rs.Path;

import javax.ws.rs.Produces;

import javax.ws.rs.QueryParam;

import nl.hr.demo.dataObjects.Employee;



@Path("EmployeesService")

public class EmployeesServices {

public EmployeesServices() {

super();

}



@GET

@Path("getEmployeeById")

@Produces("application/json")

public Employee getEmployeeById(@QueryParam("id")int id) {

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");

try {

if (id == 100) {

return new Employee(id, "Steven", "King", "SKING", "515.123.4567", sdf.parse("17-06-1987"), "AD_PRES", 24000, -1, -1, 90);

} else if (id == 101) {

return new Employee(id, "Neena", "Kochhar", "NKOCHHAR", "515.123.4568", sdf.parse("21-09-1989"), "AD_VP", 17000, -1, 100, 90);

}

return new Employee(id, "Lex", "De Haan", "LDEHAAN", "515.123.4569", sdf.parse("13-01-1993"), "AD_VP", 17000, -1, 100, 90);

} catch (Exception e) {

return null;

}

}



@GET

@Path("getAllEmployees")

@Produces("application/json")

public List<Employee> getAllEmployees() {

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

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");

try {

result.add(new Employee(100, "Steven", "King", "SKING", "515.123.4567", sdf.parse("17-06-1987"), "AD_PRES", 24000, -1, -1, 90));

result.add(new Employee(101, "Neena", "Kochhar", "NKOCHHAR", "515.123.4568", sdf.parse("21-09-1989"), "AD_VP", 17000, -1, 100, 90));

result.add(new Employee(102, "Lex", "De Haan", "LDEHAAN", "515.123.4569", sdf.parse("13-01-1993"), "AD_VP", 17000, -1, 100, 90));

} catch (Exception e) {

return new ArrayList<Employee> ();

}

return result;

}

}

For this blog the result of the web service is hard coded.

The @Path annotation above the class definition contains a warning:



If you click on this warning a jersey servlet is added to the web.xml:

<servlet>

<servlet-name>jersey</servlet-name>

<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>jersey</servlet-name>

<url-pattern>/jersey/*</url-pattern>

</servlet-mapping>


Step 7

Now the EmployeeService can be created so it can be deployed.

Right click in the Application Navigator on the EmployeeService java class and choose Create Web Service:
  • Give the web service a name for example EmployeeWebService
  • Choose SOAP 1.1 Binding
  • Leave all other options to their default value
Between the @Path annotation and the class definition a new line is added:

@WebService(name = "EmployeesWeb", serviceName = "EmployeesWebService", portName = "EmployeesWebPort")

And in the web.xml is added:

<servlet>

<servlet-name>EmployeesWebPort</servlet-name>

<servlet-class>nl.hr.demo.webservices.EmployeesServices</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>EmployeesWebPort</servlet-name>

<url-pattern>/EmployeesWebPort</url-pattern>

</servlet-mapping>


Step 8

Deploy the application as a EAR file to the weblogic server:



If you click on the Service and go to the testing tab you can test the webservice:



If we test getEmployeeById and query id 101 we get:



With result:



And test getAllEmployees results in:

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: