X

Recent Posts

Webservices

Consuming Async SOA in a WebService Proxy

Considera scenario where an application is built using SOA Async processes and needs tobe consumed in a WebService Proxy. In this blog, we will be demonstrating howto implement this use case. To achieve this, we will follow a two step process: Create an Async SOA BPEL process. Consume it in a WebService Proxy. Pre-requisite: Jdeveloper with SOA extension installed. Steps: To begin with step 1, create a SOA Applicationand name it SOA_AsyncApp. Thisinvokes Create SOA Application wizard. In the wizard, choose composite withBPEL process in Step 3. As weare going to build an async processes, in Create BPEL Process dialog, chooseAsynchronous BPEL Process from Template drop-down. We will be using BPEL 1.1Specification for our process. Also, make sure the process is exposed as a SOAPservice. We cansee the two one-way operations listed in the process wsdl as it is an asyncprocess: Drag anddrop assign activity from Components onto the SOA Composite. Edit theassign activity to insert a new rule from input variable payload to outputvariable payload. Click on the Plus symbol to add the rule. Now,the Async service setup is complete and the project containing Async processcan be deployed to a SOA server. With this, we are done with Step 1 of our use case. Tocreate a proxy for this service, create a custom Application SOA_AsyncProxy.Invoke Create Web Service Proxy wizard and in Step 2 of wizard, give WSDL ofthe service developed in Part1 of this blog.  In Step 3, check ‘Generate As Async ’ checkboxand give Callback Package name CallBackPackage. Instep 5, make sure generate async method radio button is selected and finish thewizard. After proxyis generated, run the Callback Service from under the package CallBackPackage. Thisservice will listen to the response from the asynchronous service. Give targetURL of Callback Service in proxy class and call the process with appropriateinput value. Run the proxy.Following sequence of actions will take place after proxy is run: 1) Theproxy will invoke the SOA process asynchronously and continue with other tasks. 2) SOAasync service will store the request and send receipt confirmation (202) to theproxy. 3) Theservice processes the request and acting as a proxy for Callback Service, sendsthe response back to the Callback Service.       4) Callbackservice, deployed on the proxy side receives the response and sends aconfirmation to the async SOA service (202). Afterthe callback service receives the response, it has to map the response to therequest. This is achieved using WS-Addressing Headers. The proxy must set twofields to establish the correlation: 1) ReplyTo address (address of theCallback Service) and 2) A unique Id to identify the request. Asyncbehavior can be verified by logging in to EM console and examining the flowinstance of BPEL Process. Thecorrect payload in the callbackProxy confirms that async operation has beenexecuted successfully.

Consider a scenario where an application is built using SOA Async processes and needs to be consumed in a WebService Proxy. In this blog, we will be demonstrating howto implement this use case. To...

Webservices

HTTP Basic Auth in REST Client

When a web service is secured using basic authentication, the client can access the web service only after providing the appropriate credentials. In this blog, I take you through the code which will enable the client to access such a service. Pre-requisites: Use JDeveloper 12c  version or above. Creating the Service: Let us start by creating a REST service and securing it with basic authentication.  For creating the service, please refer the section "Creating the service" in blog. Basic Authentication setup: Once the REST service has been created, in order to secure it using basic authentication, follow the below steps: Open the web.xml file. At the end of the file, add the lines: <login-config> <auth-method>BASIC</auth-method> <realm-name>myrealm</realm-name> </login-config> <security-constraint> <web-resource-collection> <web-resource-name>MyResource</web-resource-name> <url-pattern>/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>MyRole</role-name> </auth-constraint> </security-constraint> <security-role> <role-name>MyRole</role-name> </security-role> </web-app> Next, you need to create a weblogic.xml file. For this, go to New Gallery -> General -> Weblogic Deployment Descriptor. On clicking Ok, another popup appears. Under Select Descriptor, select weblogic.xml and click Next. Select the deployment descriptor version in accordance with your weblogic version and then click Finish. This will generate a weblogic.xml file under WEB-INF. Open weblogic.xml file and select 'Security' from LHS. Under 'Security Role Assignments', add the Role Name 'MyRole', and add the Principals 'Administrators' as shown. At this point, your web service has been secured using basic authentication mechanism. Run the service and copy the generated WADL URL. This will be used to create the proxy for the service. Accessing the service through REST Client: First, to create the REST Client, create a new Custom Project.Let us name it ClientProj. Right click on the Project and invoke the New Gallery window. Under Business Tier -> Web services category, select REST Client and Proxy. Provide the generated WADL URL and click Next. A prompt will appear asking for username/password. Provide the Administrator username and password that you would use to log into the WLS Console.On providing the correct credentials and clicking on Finish, the client class gets generated with some in-built code. Within the class 'Localhost_EmployeeServiceEmployeeProjContextRootResourcesClient.java' auto generated for you, write the following lines: public class Localhost_EmployeeServiceEmployeeProjContextRootResourcesClient { public static void main(String[] args) { Client client = Localhost_EmployeeServiceEmployeeProjContextRootResources.createClient(); Localhost_EmployeeServiceEmployeeProjContextRootResources.Employeeproj localhost_employeeserviceemployeeprojcontextrootresourcesemployeeproj = Localhost_EmployeeServiceEmployeeProjContextRootResources.employeeproj(client); // add your code here client.addFilter(new HTTPBasicAuthFilter("weblogic","weblogic1")); System.out.println(localhost_employeeserviceemployeeprojcontextrootresourcesemployeeproj.getAsXml(String.class)); } }  Use the import as below: import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; We use the HTTPBasicAuthFilter provided by Jersey to pass the basic auth credentials. Refer link for more details. Alternate method: Alternately, within the public class Localhost_EmployeeServiceEmployeeProjContextRootResourcesClient.java auto generated for you, write the following lines: public class Localhost_EmployeeServiceEmployeeProjContextRootResourcesClient { public static void main(String[] args) { Client client = Localhost_EmployeeServiceEmployeeProjContextRootResources.createClient(); Localhost_EmployeeServiceEmployeeProjContextRootResources.Employeeproj localhost_employeeserviceemployeeprojcontextrootresourcesemployeeproj = Localhost_EmployeeServiceEmployeeProjContextRootResources.employeeproj(client); // add your code here Authenticator.setDefault(new MyAuthenticator()); System.out.println(localhost_employeeserviceemployeeprojcontextrootresourcesemployeeproj.getAsXml(String.class)); } static class MyAuthenticator extends Authenticator { public PasswordAuthentication getPasswordAuthentication() { return (new PasswordAuthentication("weblogic", "weblogic1".toCharArray())); } } }  Use the imports: import java.net.Authenticator;import java.net.PasswordAuthentication; Here, in the code block above, we basically extend the Authenticator class, and override the getPasswordAuthentication method, in which we pass the username and password. (Replace username and password above with the credentials you provided to create the client class) In the main method, we then invoke the setDefault method of the Authenticator class and pass our Authenticator class name. This method will set the credentials whenever a proxy or HTTP server asks for authentication. The next two lines are for invoking a method of the service. If you run the client code by supplying incorrect credentials, you will get a 401 Unauthorized error.

When a web service is secured using basic authentication, the client can access the web service only after providing the appropriate credentials. In this blog, I take you through the code which will...

Webservices

Consuming Query and Path Parameter in REST DC

Use Case: In this blog I will explain on how to configure the REST DC when there are Query and Path Parameters present in the Service that is to be consumed.The Query and Path parameters in the DC are exposed as method Input Parameters in the DC palette allowing the user for easy Drag and Drop. JDeveloper Version : 12.1.2 Implementation: Configuring Query Parameters Service API Uri: http://<Server>/SampleApp/resources/rest-deleteservice?name=’Abby’ Scenario Details:In this Uri ‘name’ is a Query Parameter which will be used to delete a specific record, to expose this follow the below steps 1.    Invoke the Rest DC  and create the connection 2. In the Resources tab, enter the  remaining resource uri without providing the ‘?name=’  as shown below 3. In the Method Details tab select the delete method, and in the URL Parameters panel click on ‘+’ and enter the parameter details. Provide an Default value which will be invoked whenever the service is loaded NOTE: Providing a Valid Default Value becomes crucial when there is a GET with Query Param for which you would like the XSD to be generated by the Jdeveloper itself.  Configuring Path Parameters Service Uri: http://<ServerDetails>/sqlrest/CUSTOMER/7/ Scenario Details:In the above case ‘7’ is an customer id value based on which the specific customer record will be fetched, so this customer id is dynamic so we will be discussing on how to expose this as an dynamic field in the REST DC 1.    Invoke the Rest DC and create the Connection with Server details as mentioned in the  Step 1 for the Query Parameter2.    In the Resources Tab, enter the resource url  and select the Method type , provide an valid name for the method Here we can observe that Instead of the Value 7 we have provided that field as ##CustomerId##, now click on Next. 3. In the Method Details page, the ##CustomerId## is exposed in the URL Attributes panel, provide the default value of the Customer Id  , Click Next  4. Now In this case , I have not provided the Response XSD which will be auto generated by the Jdeveloper and the DC palette will look as shown below after completing the wizard

Use Case: In this blog I will explain on how to configure the REST DC when there are Query and Path Parameters present in the Service that is to be consumed.The Query and Path parameters in the DC are...

Webservices

Client Proxy Generation for REST style services

This blog mainly talks about generating a client for REST style web services. It begins by creating a REST style service and then consuming that service using some client code. Pre-requisites: Use JDeveloper 12c  version. Creating the Service: To start with, invoke the New Application wizard, and create a Custom application. Let us call the application EmployeeService and the Project, EmployeeProj. Next invoke the New Gallery window and create a Java class. Lets name the class Employee.java. [Refer Employee.java ]. Similarly, create another Java class and name it EmpService.java. [Refer EmpService.java] Right click on EmpService.java and select Create RESTful Service. Under Configure HTTP methods, set the following: Name Type Consumes Produces getEmpList GET Application/xml addEmployee PUT Application/xml Application/xml deleteEmployee DELETE Under Configure Parameter: For name, select  Annotation - PathParam; Parameter - name updateEmployee POST Application/json Under Configure Parameter: For name, select  Annotation - PathParam; Parameter - name Leave getEmp and addEmp methods. They will not be exposed. Click on Finish. EmpService.java should now look like [FinalEmpService.java]. Now the web service is ready to use. Run the web service and test the methods in HTTP Analyzer. Copy the generated WADL URL. Creating the REST Proxy: Next, to create the REST proxy, follow the steps mentioned below: Create a new Custom Project. Let us name it ClientProj.  Right click on the Project and invoke the New Gallery window. Under Business Tier -> Web services category, select RESTful Client and Proxy. In the Create REST Proxy Client dialog that appears, enter the WADL URL generated on running the service and click on Finish.  The generated client will consist of some in-built code. The auto generated code consists of 2 important public classes - Localhost_EmployeeServiceEmployeeProjContextRootResourcesClient.java and  Localhost_EmployeeServiceEmployeeProjContextRootResources.java. The former class basically consists of a main() method using which we can readily invoke the REST service methods. The latter, i.e., Localhost_EmployeeServiceEmployeeProjContextRootResources.java consists of all the internal logic involved in invoking the methods and handling data. This class has various methods which allow access to the web service methods.  For example, to access the getEmpList() method of the service, normally, the code would look like: Client client = Client.create(); WebResource service = client.resource(UriBuilder.fromUri("http://localhost:7101/REST_Sanity-Project1-context-root/resources/employeeproj").build()); System.out.println(service.accept(MediaType.APPLICATION_XML).get(String.class)); But, now we can use the auto generated class and methods to invoke the GET method as follows: Open Localhost_EmployeeServiceEmployeeProjContextRootResourcesClient.java and add the following lines where it is written "//add your code here". System.out.println(localhost_employeeserviceemployeeprojcontextrootresourcesemployeeproj.getAsXml(String.class)); The put method invocation would look like: localhost_employeeserviceemployeeprojcontextrootresourcesemployeeproj.putXml("<?xml version = '1.0' encoding = 'UTF-8'?> <employee><id>2</id><name>Simon</name></employee>",String.class); The delete method uses @PathParam in the service. So its invocation would be: localhost_employeeserviceemployeeprojcontextrootresourcesemployeeproj.name("Simon").deleteAs(String.class); Here localhost_employeeserviceemployeeprojcontextrootresourcesemployeeproj.name(..) returns an instance of the static Name class present within the Localhost_EmployeeServiceEmployeeProjContextRootResources class. Using that, you can then access the methods within the Name class. Similarly, the post method can be invoked as: localhost_employeeserviceemployeeprojcontextrootresourcesemployeeproj.name("Test").postAsJson(String.class); Below is the complete main method: public class Localhost_EmployeeServiceEmployeeProjContextRootResourcesClient { public static void main(String[] args) { Client client = Localhost_EmployeeServiceEmployeeProjContextRootResources.createClient();   Localhost_EmployeeServiceEmployeeProjContextRootResources.Employeeproj localhost_employeeserviceemployeeprojcontextrootresourcesemployeeproj = Localhost_EmployeeServiceEmployeeProjContextRootResources.employeeproj(client); // add your code here System.out.println("Put a new employee:" + localhost_employeeserviceemployeeprojcontextrootresourcesemployeeproj.putXml("<?xml version = '1.0' encoding = 'UTF-8'?> <employee><id>2</id><name>Simon</name></employee>", String.class)); localhost_employeeserviceemployeeprojcontextrootresourcesemployeeproj.name("Simon").deleteAs(String.class); System.out.println("Delete new employee:"+localhost_employeeserviceemployeeprojcontextrootresourcesemployeeproj.getAsXml(String.class)); System.out.println("After Post:" + localhost_employeeserviceemployeeprojcontextrootresourcesemployeeproj.name("Test").postAsJson(String.class)); } }  [Refer Localhost_EmployeeServiceEmployeeProjContextRootResourcesClient.java ]. On running the client, the following output will be seen in the log: The first line of the output corresponds to Put operation. In the put operation, we enter a new employee, Simon's details and the XML data after this operation is shown in the output. The next line shows the result of delete operation after deleting the employee with name "Simon". This is followed by the result of post operation which is displayed in Json format. 

This blog mainly talks about generating a client for REST style web services. It begins by creating a REST style service and then consuming that service using some client code. Pre-requisites: Use...

Webservices

XSLT Transformation in REST DC

Use Case:This blog explains about applying XSLT transformation on a REST Service while creating the Rest DataControl.Here I will be explaining on how the data is getting manipulated and is rendered by the REST DC when XSL is applied on it. JDeveloper Version used : 12.1.2 Steps: 1. Consider an Scenario where an REST Service API is retuning an XML response as mentioned below<?xml version = '1.0' encoding = 'UTF-8' standalone = 'yes'?><departments>   <department>      <deptId>1001</deptId>      <deptName>HumanResource</deptName>   </department>   <department>      <deptId>2002</deptId>      <deptName>Finance</deptName>   </department>   <department>      <deptId>3003</deptId>      <deptName>Research</deptName>   </department>   <department>      <deptId>5005</deptId>      <deptName>Sales</deptName>   </department></departments> 2. Lets create an XSD structure to contain two more new attributes e.g CUSTOMNAME of type String and UNIQUEID of type integer<?xml version="1.0" encoding="windows-1252" ?><xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">  <xsd:element name="departments">    <xsd:complexType>      <xsd:sequence>        <xsd:element name="department" maxOccurs="unbounded">          <xsd:complexType>            <xsd:sequence>              <xsd:element name="deptId" type="xsd:integer"/>              <xsd:element name="deptName" type="xsd:string"/>              <xsd:element name="customUniqueId" type="xsd:integer"/>              <xsd:element name="customName" type="xsd:string"/>            </xsd:sequence>          </xsd:complexType>        </xsd:element>      </xsd:sequence>    </xsd:complexType>  </xsd:element></xsd:schema>3. Now we have to create an XSL File to transform data , so that the values can be populated for the new attributes.<?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:ns2="http://project1/">    <xsl:template match="departments">        <departments>          <xsl:for-each select="department">              <department>                  <deptName><xsl:value-of select="deptName"/></deptName>                  <deptId><xsl:value-of select="deptId"/></deptId>                  <customName><xsl:value-of select="concat('CUST_',deptName)"/></customName>                  <customUniqueId><xsl:value-of select="deptId * 2"/></customUniqueId>              </department>                 </xsl:for-each>          </departments>    </xsl:template></xsl:stylesheet>4. In Jdeveloper, invoke the WSDC wizard, select the type as REST, in the wizard provide the name for the DC and create the connection.5. In the Next Step of the wizard, provide the resource path and the method name for the operation6. In the Method Details Step of the wizard provide the Cutsom XSD and  XSL file for the method as shown below7.  Click Next and Complete the Wizard, then Expand the DC palette to find the Structure as shown below8. Drag and Drop the departmentNode onto the page as an ADF table and Run the page9. Here we can observe the value being populated for the customUniqueId and customName as per the definition given in the XSL file

Use Case: This blog explains about applying XSLT transformation on a REST Service while creating the Rest DataControl.Here I will be explaining on how the data is getting manipulated and is rendered...

ADF

Simple GET operation with JSON data in ADF Mobile

Usecase: This sample uses a RESTful service which contains a GETmethod that fetches employee details for an employee with given employee IDalong with other methods. The data is fetched in JSON format. This RESTful service is then invoked via ADF Mobile and theJSON data thus obtained is parsed and rendered in mobile in a table. Prerequisite: Download JDev build JDEVADF_11.1.2.4.0_GENERIC_130421.1600.6436.1or higher with mobile support.  Steps: Create a REST service using three classes, Employee.java, EmployeeList.java and EmployeeService.java (as shown below). EmployeeService.java will function as the main RESTful service class.This is asimple service with a method, getEmpById(id) that takes employee ID asparameter and produces employee details in JSON format.  package project1;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElementpublic class Employee { String name; int id; String desig; int salary; public void setDesig(String desig) { this.desig = desig; } public String getDesig() { return desig; } public void setSalary(int salary) { this.salary = salary; } public int getSalary() { return salary; } public void setDept(String dept) { this.dept = dept; } public String getDept() { return dept; } String dept; public Employee() { super(); } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setId(int id) { this.id = id; } public int getId() { return id; }} package project1;import java.net.URI;import java.net.URL;import java.util.ArrayList;import java.util.List;import javax.xml.bind.annotation.XmlRootElement;import javax.xml.bind.annotation.XmlElement;@XmlRootElementpublic class EmployeeList { private List list = new ArrayList(); public EmployeeList() { } public EmployeeList(List list) { super(); this.list = list; }@XmlElement public List getList() { return list; }} package project1;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.concurrent.CopyOnWriteArrayList;import javax.ws.rs.Consumes;import javax.ws.rs.DELETE;import javax.ws.rs.GET;import javax.ws.rs.POST;import javax.ws.rs.PUT;import javax.ws.rs.Path;import javax.ws.rs.PathParam;import javax.ws.rs.Produces;import javax.ws.rs.QueryParam;@Path("project1")public class EmployeeService { private static List employeeList = new CopyOnWriteArrayList(); public EmployeeService() { addEmp(); } @GET @Produces("application/json") public EmployeeList getEmpList() { return new EmployeeList(employeeList); } @PUT @Consumes("application/json") @Produces("application/json") public EmployeeList addEmployee(Employee emp) { employeeList.add(emp); return new EmployeeList(employeeList); } @DELETE @Produces("application/json") public EmployeeList deleteEmployee(@QueryParam("name") String name) { employeeList.remove(getEmp(name)); return new EmployeeList(employeeList); } @POST @Produces("application/json") public EmployeeList updateEmployee(@QueryParam("id") int id,@QueryParam("name") String name) { Employee emp1 = new Employee(); emp1 = getEmpById(id); if(emp1 != null) emp1.setName(name); return new EmployeeList(employeeList); } public Employee getEmp(String name) { Iterator i = employeeList.iterator(); while (i.hasNext()) { Employee e = (Employee)i.next(); if (e.getName().equalsIgnoreCase(name)) return e; } return null; } @GET @Produces("application/json") @Path("/getById/{id}") public Employee getEmpById(@PathParam("id") int id) { Iterator i = employeeList.iterator(); while (i.hasNext()) { Employee e = (Employee)i.next(); if (e.getId() == id) return e; } return null; } public void addEmp() { if (employeeList.isEmpty()) { Employee emp1 = new Employee(); emp1.setId(1); emp1.setName("Arnold"); emp1.setDept("IT"); emp1.setDesig("Director"); emp1.setSalary(80000); employeeList.add(emp1); Employee emp2 = new Employee(); emp2.setId(2); emp2.setName("Myra"); emp2.setDept("HR"); emp2.setDesig("Officer"); emp2.setSalary(5000); employeeList.add(emp2); } }} Copy the target URL generated on running this service. Thetarget URL will be as shown below: http://127.0.0.1:7101/JSONService-Project1-context-root/jersey/project1 Now, let us invoke this service in our mobile application.For this, create an ADF Mobile application.  Name the application JSON_SearchByEmpIDand finish the wizard. Now, let us create a connection to our service. To do this,we create a URL Connection. Invoke new gallery wizard on ApplicationControllerproject.  Select URL Connection option. In the Create URL Connection window, enter connection nameas ‘conn’. For URL endpoint, supplythe URL you copied earlier on running the service. Remember to use your systemIP instead of localhost. Test the connection and click OK. At this point, a connection to the REST service has beencreated. Since JSON data is not supported directly in WSDC wizard, weneed to invoke the operation through Java code using RestServiceAdapter. Forthis, in the ApplicationController project, create a Java class called ‘EmployeeDC’.We will be creating DC from this class. Addthe following code to the newly created class to invoke the getEmpById method. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public Employee fetchEmpDetails(){ RestServiceAdapter restServiceAdapter = Model.createRestServiceAdapter(); restServiceAdapter.clearRequestProperties(); restServiceAdapter.setConnectionName("conn"); //URL connection created with this name restServiceAdapter.setRequestType(RestServiceAdapter.REQUEST_TYPE_GET); restServiceAdapter.addRequestProperty("Content-Type", "application/json"); restServiceAdapter.addRequestProperty("Accept", "application/json; charset=UTF-8"); restServiceAdapter.setRetryLimit(0); restServiceAdapter.setRequestURI("/getById/"+inputEmpID); String response = ""; JSONBeanSerializationHelper jsonHelper = new JSONBeanSerializationHelper(); try { response = restServiceAdapter.send(""); //Invoke the GET operation System.out.println("Response received!"); Employee responseObject = (Employee) jsonHelper.fromJSON(Employee.class, response); return responseObject; } catch (Exception e) { } return null; } Here, in lines2 to 9, we create the RestServiceAdapter and set various properties required toinvoke the web service. At line 4, we are pointing to the connection ‘conn’ created previously. Since we want to invoke getEmpById method of the service,which is defined by the URL http://IP:7101/REST_Sanity_JSON-Project1-context-root/resources/project1/getById/{id} we areupdating the request URI to point to this URI at line 9. inputEmpID isa variable that will hold the value input by the user for employee ID. This wewill be creating in a while. As themethod we are invoking is a GET operation and consumes json data, theseproperties are being set in lines 5 through 7. Finally, we are sending therequest in line 13. In line 15, we use jsonHelper.fromJSON toconvert received JSON data to a Java object. The required Java objects' structureis defined in class Employee.java whose structure is provided later. Since theresponse from our service is a simple response consisting of attributes likeemployee Id, name, design etc, we will just return this parsed response (line 16)and use it to create DC. As mentionedpreviously, we would like the user to input the employee ID for which he/shewants to perform search. So, in the same class, define a variable inputEmpID which will hold the valueinput by the user. Generate accessors for this variable. Lastly, weneed to create Employee class. Employee class will define how we want tostructure the JSON object received from the service. To design the Employeeclass, run the services’ method in the browser or via analyzer using pathparameter as 1. This will give you the output JSON structure. Ours is asimple service that returns a JSONObject with a set of data. Hence, Employeeclass will just contain this set of data defined with the proper data types. Create Employee.javain the same project as EmployeeDC.java and write the below code: package application; import oracle.adfmf.java.beans.PropertyChangeListener; import oracle.adfmf.java.beans.PropertyChangeSupport; public class Employee { private String dept; private String desig; private int id; private String name; private int salary; private PropertyChangeSupportpropertyChangeSupport = new PropertyChangeSupport(this); public void setDept(Stringdept) {         String oldDept = this.dept; this.dept = dept; propertyChangeSupport.firePropertyChange("dept", oldDept,dept); } public String getDept() { return dept; } public void setDesig(Stringdesig) { String oldDesig =this.desig; this.desig = desig; propertyChangeSupport.firePropertyChange("desig", oldDesig,desig); } public String getDesig() { return desig; } public void setId(int id) { int oldId = this.id; this.id = id; propertyChangeSupport.firePropertyChange("id",oldId, id); } public int getId() { return id; } public void setName(String name) { String oldName = this.name; this.name = name; propertyChangeSupport.firePropertyChange("name",oldName, name); } public String getName() { return name; } public void setSalary(intsalary) { int oldSalary =this.salary; this.salary = salary; propertyChangeSupport.firePropertyChange("salary", oldSalary,salary); } public int getSalary() { return salary; } public voidaddPropertyChangeListener(PropertyChangeListener l) { propertyChangeSupport.addPropertyChangeListener(l); } public voidremovePropertyChangeListener(PropertyChangeListener l) { propertyChangeSupport.removePropertyChangeListener(l);     } } Now, let us create a DC out of EmployeeDC.java.  DC as shown below is created. Now, you candesign the mobile page as usual and invoke the operation of the service. Todesign the page, go to ViewController project and locate adfmf-feature.xml.Create a new feature called ‘SearchFeature’by clicking the plus icon. Go the content tab and add an amx page. Call it SearchPage.amx. Call it SearchPage.amx. Remove primary and secondary buttons as we don’t need them and rename the header. Drag and drop inputEmpID from the DC palette onto Panel Page in the structure pane asinput text with label. Next, dropfetchEmpDetails method as an ADF button. For a change,let us display the output in a table component instead of the usual form.However, you will notice that if you drag and drop Employee onto the structurepane, there is no option for ADF Mobile Table. Hence, we will need to createthe table on our own. To do this, let us first drop Employee as an ADF Read -Only form. This step is needed toget the required bindings. We will be deleting this form in a while. Now, fromthe Component palette, search for ‘Table Layout’. Drag and drop this below thecommand button.  Within thetablelayout, insert ‘Row Layout’ and ‘Cell Format’ components. Final table structureshould be as shown below. Here, we have also defined some inline styling torender the UI in a nice manner. <amx:tableLayout id="tl1" borderWidth="2"halign="center" inlineStyle="vertical-align:middle;" width="100%" cellPadding="10"> <amx:rowLayoutid="rl1" > <amx:cellFormatid="cf1" width="30%"> <amx:outputTextvalue="#{bindings.dept.hints.label}" id="ot7"inlineStyle="color:rgb(0,148,231);"/> </amx:cellFormat> <amx:cellFormatid="cf2"> <amx:outputTextvalue="#{bindings.dept.inputValue}" id="ot8" /> </amx:cellFormat> </amx:rowLayout> <amx:rowLayoutid="rl2"> <amx:cellFormatid="cf3" width="30%"> <amx:outputTextvalue="#{bindings.desig.hints.label}" id="ot9"inlineStyle="color:rgb(0,148,231);"/> </amx:cellFormat> <amx:cellFormat id="cf4"> <amx:outputTextvalue="#{bindings.desig.inputValue}" id="ot10"/> </amx:cellFormat> </amx:rowLayout> <amx:rowLayoutid="rl3"> <amx:cellFormatid="cf5" width="30%"> <amx:outputTextvalue="#{bindings.id.hints.label}" id="ot11"inlineStyle="color:rgb(0,148,231);"/> </amx:cellFormat> <amx:cellFormatid="cf6" > <amx:outputTextvalue="#{bindings.id.inputValue}" id="ot12"/> </amx:cellFormat> </amx:rowLayout> <amx:rowLayoutid="rl4"> <amx:cellFormatid="cf7" width="30%"> <amx:outputTextvalue="#{bindings.name.hints.label}" id="ot13"inlineStyle="color:rgb(0,148,231);"/> </amx:cellFormat> <amx:cellFormatid="cf8"> <amx:outputTextvalue="#{bindings.name.inputValue}" id="ot14"/> </amx:cellFormat> </amx:rowLayout> <amx:rowLayoutid="rl5"> <amx:cellFormatid="cf9" width="30%"> <amx:outputTextvalue="#{bindings.salary.hints.label}" id="ot15"inlineStyle="color:rgb(0,148,231);"/> </amx:cellFormat> <amx:cellFormatid="cf10"> <amx:outputTextvalue="#{bindings.salary.inputValue}" id="ot16"/> </amx:cellFormat> </amx:rowLayout>     </amx:tableLayout> The valuesused in the output text of the table come from the bindings obtained from theADF Form created earlier. As we have used the bindings and don’t need the formanymore, let us delete the form.  One last thing before we deploy. When user changes employee ID, we want to clear thetable contents. For this we associate a value change listener with the inputtext box. Click New in the resulting dialog to create a managed bean. Next, we create a method within the managed bean. For this, click on the New buttonassociated with method. Call the method ‘empIDChange’. OpenmyClass.java and write the below code in empIDChange(). public void empIDChange(ValueChangeEvent valueChangeEvent) { // Add event code here... //Resetting the values toblank values when employee id changes AdfELContext adfELContext =AdfmfJavaUtilities.getAdfELContext(); ValueExpression ve =AdfmfJavaUtilities.getValueExpression("#{bindings.dept.inputValue}",String.class); ve.setValue(adfELContext,""); ve =AdfmfJavaUtilities.getValueExpression("#{bindings.desig.inputValue}",String.class); ve.setValue(adfELContext,""); ve =AdfmfJavaUtilities.getValueExpression("#{bindings.id.inputValue}",int.class); ve.setValue(adfELContext,""); ve =AdfmfJavaUtilities.getValueExpression("#{bindings.name.inputValue}",String.class); ve.setValue(adfELContext,""); ve =AdfmfJavaUtilities.getValueExpression("#{bindings.salary.inputValue}",int.class); ve.setValue(adfELContext,""); } That’s it. Deploy the application to android emulator or device. Some snippets from the app.

Usecase: This sample uses a RESTful service which contains a GET method that fetches employee details for an employee with given employee IDalong with other methods. The data is fetched in JSON...

ADF

XML Parsing in ADF Mobile

Usecase: In this usecase, we have a web service that returns employee details(like name, designation, salary etc.) for an employee with given ID. In the mobile app, we will be calculating tax onthe returned salary and displaying it to the user in a pop-up. To do this, we will be parsing the returned XML to fetch thecurrent salary and add a tax of 5% on it. Here, we are assuming that tax is 5% of the current salary. Pre-requisites:  Create a RESTful service as shown. We will be using this service at the mobile end to create the DC. To create the service, first create a java class called Employee.java as shown below: package project1;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElementpublic class Employee { String name; int id; String desig; int salary; public void setDesig(String desig) { this.desig = desig; } public String getDesig() { return desig; } public void setSalary(int salary) { this.salary = salary; } public int getSalary() { return salary; } public void setDept(String dept) { this.dept = dept; } public String getDept() { return dept; } String dept; public Employee() { super(); } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setId(int id) { this.id = id; } public int getId() { return id; }} Next, create a wrapper class 'EmployeeList.java' as shown:package project1;import java.net.URI;import java.net.URL;import java.util.ArrayList;import java.util.List;import javax.xml.bind.annotation.XmlRootElement;import javax.xml.bind.annotation.XmlElement;@XmlRootElementpublic class EmployeeList { private List list = new ArrayList(); public EmployeeList() { } public EmployeeList(List list) { super(); this.list = list; }@XmlElement public List getList() { return list; }}Finally, create the service class called EmployeeService.java.package project1;import java.util.Iterator;import java.util.List;import java.util.concurrent.CopyOnWriteArrayList;import javax.ws.rs.Consumes;import javax.ws.rs.DELETE;import javax.ws.rs.GET;import javax.ws.rs.POST;import javax.ws.rs.PUT;import javax.ws.rs.Path;import javax.ws.rs.Produces;import javax.ws.rs.QueryParam;@Path("project1")public class EmployeeService { private static List employeeList = new CopyOnWriteArrayList(); public EmployeeService() { addEmp(); } @GET @Produces("application/xml") public EmployeeList getEmpList() { return new EmployeeList(employeeList); } @PUT @Consumes("application/xml") @Produces("application/xml") public EmployeeList addEmployee(Employee emp) { employeeList.add(emp); return new EmployeeList(employeeList); } @DELETE @Produces("application/xml") public EmployeeList deleteEmployee(@QueryParam("name") String name) { employeeList.remove(getEmp(name)); return new EmployeeList(employeeList); } @POST @Produces("application/xml") public EmployeeList updateEmployee(@QueryParam("id") int id,@QueryParam("name") String name) { Employee emp1 = new Employee(); emp1 = getEmpById(id); if(emp1 != null) emp1.setName(name); return new EmployeeList(employeeList); } public Employee getEmp(String name) { Iterator i = employeeList.iterator(); while (i.hasNext()) { Employee e = (Employee)i.next(); if (e.getName().equalsIgnoreCase(name)) return e; } return null; } @GET @Path("byID") public Employee getEmpById(@QueryParam("id") int id) { Iterator i = employeeList.iterator(); while (i.hasNext()) { Employee e = (Employee)i.next(); if (e.getId() == id) return e; } return null; } public void addEmp() { if (employeeList.isEmpty()) { Employee emp1 = new Employee(); emp1.setId(1); emp1.setName("Arnold"); emp1.setDept("IT"); emp1.setDesig("Director"); emp1.setSalary(80000); employeeList.add(emp1); Employee emp2 = new Employee(); emp2.setId(2); emp2.setName("Myra"); emp2.setDept("HR"); emp2.setDesig("Officer"); emp2.setSalary(70000); employeeList.add(emp2); } }} Run the service class and copy the target URL. Steps: Create a new ADF Mobile application.  Name the application ‘XmlParsingSample’and finish the wizard. Create a URL Connection in the ApplicationControllerproject. Name the connection ‘conn’and suppy the target URL copied earlier. Remember to use IP instead oflocalhost. Test the connection and click OK to close the wizard. Since the service returns XML data, also create a Datacontrol. This will be useful for designing the UI page. To create DC, invokeURL Service data control wizard in the ApplicationController project. Test the URL connection in the last step and finish thewizard. Now, let us create the AMX pages. Open adfmf-feature.xmlpresent in ViewController project. Add a new feature ‘EmpFeature’ by clicking the plus icon as shown. Go to the content tab and add an AMX page. Call it EmpPage.amx. Wedon’t need the primary and secondary actions. So, uncheck them. Drag and drop ‘id’parameter from the DC palette onto the Panel Page of the Structure pane forthis page. Drag and drop a button from the component palette onto thepage. Change the text of the button to ‘Get salary’. As we want to invoke the service on click of this button,let us associate an ActionListener with this. Focus on the button and from thePI, select the arrow button for ActionListener propery and click Editto bring up the below dialog. Click New to create a new managed bean. Name the manged bean as myBean and class as myClass. Next, create a new method called calculateTax. Go to myClass.java. In calculateTax method, write the code provided in the below table. Use the imports: import oracle.adfmf.amx.event.ActionEvent; import oracle.adfmf.dc.ws.rest.RestServiceAdapter; import oracle.adfmf.framework.api.AdfmfContainerUtilities; import oracle.adfmf.framework.api.Model; import org.xmlpull.v1.XmlPullParser; import org.kxml2.io.KXmlParser; import java.io.Reader; import java.io.StringReader; 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. public void calculateTax(ActionEvent actionEvent) { // Add event code here... RestServiceAdapter restServiceAdapter = Model.createRestServiceAdapter(); restServiceAdapter.clearRequestProperties(); restServiceAdapter.setConnectionName("conn"); restServiceAdapter.setRequestType(RestServiceAdapter.REQUEST_TYPE_GET); restServiceAdapter.addRequestProperty("Content-Type", "application/xml"); restServiceAdapter.addRequestProperty("Accept", "application/xml; charset=UTF-8"); restServiceAdapter.setRetryLimit(0); Object emppIDObj = AdfmfJavaUtilities.evaluateELExpression("#{bindings.id.inputValue}"); String empIDString = emppIDObj.toString(); restServiceAdapter.setRequestURI("/byID?id="+empIDString); String response = ""; try { response = restServiceAdapter.send(""); System.out.println("Response received!"); String name = ""; int sal = 0; int salAfterTax = 0; KXmlParser parser = new KXmlParser(); //create a parser instance Reader stream = new StringReader(response); parser.setInput(stream); parser.nextTag(); parser.require(XmlPullParser.START_TAG, null, "employee"); while (parser.nextTag() != XmlPullParser.END_TAG) { //loop through until you encounter an end tag parser.require(XmlPullParser.START_TAG, null, null); //go to start tag String tagName = parser.getName(); //get the name of the current tag String tagValue = parser.nextText(); //get the value within the current tag if (tagName.equals("name")) { //if current tag is ‘name’, assign its value to variable ‘name’ name = tagValue; } if (tagName.equals("salary")) { //if current tag is ‘salary’, calculate salary after tax System.out.println("Salary:" + tagValue); sal = Integer.parseInt(tagValue); salAfterTax = (int)(sal - sal * 0.05); } parser.require(XmlPullParser.END_TAG, null, tagName); //go to end tag of current tag //parse through all the tags } parser.require(XmlPullParser.END_TAG, null, "employee"); parser.next(); parser.require(XmlPullParser.END_DOCUMENT, null, null); AdfmfContainerUtilities.invokeContainerJavaScriptFunction("EmpFeature", "navigator.notification.alert", new Object[] { "Salary for employee " + name + " is " + sal + ". After tax deduction, salary is:" + salAfterTax, "", "Note", "OK!" }); } catch (Exception e) { System.out.println("Exception is:" + e); } } }  Lines 3 to 15 set various properties required to invoke theweb service. In lines 10 and 11, we are getting the value input by the user andconverting that to String inorder to pass the parameter to the service. In line 20,we are creating a kXml parser instance. kXML is one of the core ADF Mobile librariesthat provides API that you can use to parse XML. As the parser needs a Readerobject, we are converting our services’ response into Reader in line 21 andpassing it in line 22.  The response returned by our service is of the form <?xmlversion="1.0" encoding="UTF-8"?><employee> <dept>HR</dept> <desig>Officer</desig> <id>2</id> <name>Myra</name> <salary>70000</salary></employee> To parse this response, we are setting the parser to the first tag‘employee’ in line 24. In lines 25 through 42, we are going through the XMLelements. The comments are in-line for these lines. Finally, lines 43 through 47are for displaying the pop-up. To display the pop-up, we are utilizing AdfmfContainerUtilities.invokeContainerJavaScriptFunction. For moreinformation, see link. As mentioned in the article, we make use of the javascriptfunction which comes from phonegap-1.0.0.js. Hence, we need to include an entryto this javascript file in our AMX page. Put the below entry in EmpPage.amxabove the panelPage. <script type ="text/javascript" charset="utf-8"src="../../../www/js/phonegap-1.0.0.js"></script> That’s it. Deploy the app to a device or an emulator. Somesnippets from the final app.  Enjoy coding! 

Usecase: In this usecase, we have a web service that returns employee details(like name, designation, salary etc.) for an employee with given ID. In the mobile app, we will be calculating tax onthe...

ADF Desktop Integration

ADF Desktop Integration Client Logging

About In general, when we encounter errors, weoften tend to look at logs to get detailed information. Users ofADF Desktop Integration can also enable logging in both client-sideand server-side. In this blog we will have a look on how to enableclient-side logging. Assumption Let us assume an ADF application iscreated with Employees table using simple HR schema and ADFdiworkbook is created and configured to use EmployeesView1 as ADFTable. How to enable logging for all workbooks opened with installedclient: For Design time client, copy 'adfdi-excel-addin.dll.config' from"<JDEV_HOME>\jdeveloper\adfdi\bin\excel\samples to thedirectory mentioned under About ADF Desktop Integration dialog inOracle ADF tab -> Properties tab -> Configurationproperty. For Runtime client, copy 'adfdi-excel-addin.dll.config' from"<JDEV_HOME>\jdeveloper\adfdi\bin\excel\samples to thedirectory mentioned under About ADF Desktop Integration dialog inMyWorkbook tab -> Properties tab -> Configurationproperty and rename it as'adfdi-excel-addin-runtime.dll.config'. We will continue with the assumption that we have installedDesign time client and hence will use adfdi-excel-addin.dll.configfile. In adfdi-excel-addin.dll.config file, we have an <add> taginside <listeners> tag where we can set type, name, locationand trace options of log file. <add type="System.Diagnostics.DelimitedListTraceListener"name="adfdi-common-text-listener"initializeData="C:\temp\adfdi-common-excel.txt" delimiter="|"traceOutputOptions="ThreadId, ProcessId, DateTime"/> type - determines type of logs. Logs can be obtained in 3different formats: System.Diagnostics.DelimitedListTraceListener - Default format.Logs will be obtained with the specified delimiter. System.Diagnostics.XmlWriterTraceListener - Logs will beobtained in xml format. System.Diagnostics.TextWriterTraceListener - Logs will beobtained in Text format. name - name of the trace listener. Can be set to any value initializeData - determines the path where the log file has tobe generated. Valid path has to be mentioned. delimiter - specified character is used as a delimiter when typeis set to 'System.Diagnostics.DelimitedListTraceListener'. It isnot required to be set for other types. traceOutputOptions - determines the optional content of traceoutput. If no extra details are required, it can be set to"None" Different levels of logging can be set by chaning theswitchValue property inside <source> tag. By default it isset to Information and logging can be turned off by settingswitchValue = Off Once after setting switchValue save the config file. Open theadfdi workbook and click on Refresh Config button in Loggingsection of Oracle ADF ribbbon tab. With switchValue = Information - Information,warning and error messages will be logged in the log file. Eg: In excel workbook, add an ADF Input Text into cell J5. Selectthe same cell (J5) and insert ADF Button Component. A warning willbe displayed. In C:\temp\adfdi-commom-excel.txt log file, logs similar to belowwill be seen: ~~~~~~~~~~~~~~~~~~~~~~ "adfdi-common"|Warning|3|"A component already exists at originJ5."||7284||"1"|"2013-08-23T10:28:15.2851735Z"|| ~~~~~~~~~~~~~~~~~~~~~~ With switchValue = Warning - Warning and errormessages will be logged into log file. Eg: Edit ADF Table properties by double-clicking any cell in tablerange, and open Edit Columns by clicking on button on RHS ofColumns property. Select FirstName column and set the value ofDynaminColumn property to True. Close all dialogs by giving OK andrun the workbook. In C:\temp\adfdi-commom-excel.txt log file, logs similar to belowwill be seen: ~~~~~~~~~~~~~~~~~~~~~~ "adfdi-common"|Warning|3|"ADFDI-07520: Unable to evaluate theexpression '#{bindings.EmployeesView1.hints.FirstName.label}' in'Sheet1.TAB429819356.FirstName.HeaderLabel'. Detail:"||6352||"1"|"2013-08-23T10:40:16.0642489Z"|| ~~~~~~~~~~~~~~~~~~~~~~ With switchValue = Error - onlyerror/exception messages will be logged into log file. Eg: Run the workbook. Click on Edit Options in MyWorkbook tab andenter an invalid webapproot (say add 1 at end). Click on OK andclick Yes in Web App Root confirmation dialog.ConnectionFailedException will be seen. In C:\temp\adfdi-commom-excel.txt log file, logs similar to belowwill be seen: ~~~~~~~~~~~~~~~~~~~~~~ "adfdi-common"|Error|2|"ADFDI-05530: unable to initializeworksheet: Sheet1 ADFDI-00134: An attempt to connect to the web application hasfailed. ADFDI-00501: An unexpected status: 404 (NotFound) was returnedfrom the server while requesting the URL:http://127.0.0.1:7101/BlogApplication-ViewController-context-root1/adfdiRemoteServlet ~~~~~~~~~~ ConnectionFailedException: ADFDI-00134: An attempt to connect tothe web application has failed. Source: adfdi-datamanager Stack: atoracle.adf.client.windows.datamanager.LoginHandler.GetAuthenticationMode() atoracle.adf.client.windows.datamanager.LoginHandler.Login() atoracle.adf.client.windows.datamanager.ADFBindingContext.LoginHandlerProxy.Login() atoracle.adf.client.windows.datamanager.ADFBindingContext.AttemptLogin(BooleanmaybeHadSession) atoracle.adf.client.windows.datamanager.ADFBindingContext.SyncModel(BindingContainerbc, String contentType) atoracle.adf.client.windows.datamanager.BindingContainer.ReloadMetadata() atoracle.adf.client.windows.excel.runtime.DIWorksheet.InitializeComponents(BooleanisFirstLoad) atoracle.adf.client.windows.excel.runtime.DIWorksheet.Initialize(BooleaninitializeUI) Inner: UnexpectedHttpStatusException: ADFDI-00501: An unexpected status:404 (NotFound) was returned from the server while requesting theURL:http://127.0.0.1:7101/BlogApplication-ViewController-context-root1/adfdiRemoteServlet Source: adfdi-datamanager Stack: atoracle.adf.client.windows.datamanager.LoginHandler.GetAuthenticationMode() ~~~~~~~~~~~~~~~~~~~~~~ With switchValue = Verbose - detailedinformation about the workbook events including warning,information and errors will be seen with delimiter in logfile. Eg: Run the workbook and perform Download by clicking on Downloadribbon command. Enter an invalid value for FirstName(say'aaaaaaaaaaaaaaaaaaaaaaaaaaaa') and perform Upload by clicking onUpload ribbon command. Upload will fail as FirstName has invalidprecision/scale. In C:\temp\adfdi-commom-excel.txt log file, all details in Aboutdialog will be logged similar to below : ~~~~~~~~~~~~~~~~~~~~~~ "adfdi-common"|Verbose|5|"oacw.datamanager.BindingContainer.AppendExceptionToList:Exception received from server: localized message: JBO-27023:Failed to validate all rows in a transaction.; display message:null; java class name: oracle.jbo.TxnValException; cause:null product code: JBO; error code: 27023; severity: Error; row key:null; attribute id: null; Detail: localized message: JBO-27024: Failed to validate a rowwith key oracle.jbo.Key[100 ] in AppModule.EmployeesView1; displaymessage: null; java class name: oracle.jbo.RowValException; cause:null product code: JBO; error code: 27024; severity: Error; row key:00010000000AACED0005770400000064; attribute id: null; Detail: localized message: JBO-27010: Attribute set with valueaaaaaaaaaaaaaaaaaaaaaaaaaaaa for FirstName inAppModule.EmployeesView1 has invalid precision/scale; displaymessage: Attribute set with value aaaaaaaaaaaaaaaaaaaaaaaaaaaa forFirstName in AppModule.EmployeesView1 has invalid precision/scale;java class name: oracle.jbo.PrecisionScaleValidationException;cause: null product code: JBO; error code: 27010; severity: Error; row key:null; attribute id: FirstName; Details:null"||12780||"1"|"2013-08-23T13:10:38.8164715Z"|| ~~~~~~~~~~~~~~~~~~~~~~ How to enable logging for a particular session: This type of logging can be used only for DT/TST mode and cannotbe used for RT mode. This logging is of major help when we wantdetailed log messages for a specific usecase/error. On opening ADFdi enabled excel workbook, under Oracle ADF ribbontab, there will be Logging section with buttons for Console, SetOutput Level, Add Log Output File and Refresh Config Clicking on Console button, opens up Logging Console non-modaldialog. By default the logging level is set to Off and hence nologs will be seen. Logging levels can be set either by clicking Set Output Level inLogging section of Oracle ADF tab or by clicking Set Level inLogging Console dialog. Logs can also be saved in a file by specifying file name andlocation in 'Add New Temporary Logging Output File' dialog byclicking on 'Add Log Output File' button in Logging sectionof Oracle ADF tab. The format of log can also be changed by selecting Text/XML fromOutput Type as seen in above image. Through these ways we can enable client-side logging for ADFDesktop Integration to trace down the error /exception we getduring development / testing / debugging the workbook.

About In general, when we encounter errors, we often tend to look at logs to get detailed information. Users of ADF Desktop Integration can also enable logging in both client-sideand server-side. In...

EJB

EJB DC - Using JPQL constructor expressions

In JPA 2.0, a new feature is provided - "Constructor Expressions in the SELECT Clause". This feature is mainly useful for queries with multiple Select expressions, where custom result objects is necessary. This feature works with Oracle JDeveloper 12.1.2.0.0 Implementation Steps Create Fusion Web Application with entities based on Departments and Employees, then create a session bean. Create a Java class "DeptAndEmp" and add the below code. public class DeptAndEmp implements Serializable {    private String departmentName;   private String email;    private String firstName;    private String lastName;    public DeptAndEmp() {        super();    }    public DeptAndEmp(String departmentName, String email, String firstName, String lastName) { this.setDepartmentName(departmentName); this.setEmail(email); this.setFirstName(firstName); this.setLastName(lastName); }    public void setDepartmentName(String departmentName) {        this.departmentName = departmentName;    }    public String getDepartmentName() {        return departmentName;    }    public void setEmail(String email) {        this.email = email;    }    public String getEmail() {        return email;    }    public void setFirstName(String firstName) {        this.firstName = firstName;    }    public String getFirstName() {        return firstName;    }    public void setLastName(String lastName) { this.lastName = lastName;    }    public String getLastName() {        return lastName;    }}Open the session bean and paste the below method code and expose the method filterDeptEmpResult() method in local/remote interface.public List<DeptAndEmp> filterDeptEmpResult() {String qlString ="SELECT NEW model.util.DeptAndEmp(dept.departmentName, emp.email,emp.firstName, emp.lastName) FROM Employees emp, Departments deptwhere emp.departments.departmentId = dept.departmentId";TypedQuery<DeptAndEmp> query = em.createQuery(qlString, DeptAndEmp.class);return query.getResultList();} Note:- In the Query "model is a package name and TypedQuery is a JPA query that returns a specific type of Object. TypedQuery eliminates the need to cast the query result to a specific type or having to add a SuppressWarnings annotation to eliminate compiler warnings about unchecked conversions. TypedQuery is well explained in Java Persistence Architecture 2.0 - Using The New TypedQuery InterfaceCreate a Sample Java Client and add the below code in main method.SessionEJB sessionEJB = (SessionEJB) context.lookup("JPAConstructorApp-Model-SessionEJB#model.SessionEJB");for (DeptAndEmp deptAndEmp : (List<DeptAndEmp>) sessionEJB.filterDeptEmpResult()) { System.out.println("departmentName = " + deptAndEmp.getDepartmentName()); System.out.println("email = " + deptAndEmp.getEmail()); System.out.println("firstName = " + deptAndEmp.getFirstName()); System.out.println("lastName = " + deptAndEmp.getLastName()); System.out.println("=======================================");}Deploy the sessionFacade and run the java client. In the console employees details will be displayed as below.

In JPA 2.0, a new feature is provided - "Constructor Expressions in the SELECT Clause". This feature is mainly useful for queries with multiple Select expressions, where custom result objects...

EJB

Add-Edit multiple rows using EJB DC

Let us take a scenario where in users wants to add/edit multiple records in the ADF table,  earlier with stateless session bean we need have work around to achieve this scenario. This scenario can be achieved using stateful session bean, the application-managed transaction model for EJB/POJO data controls which additionally maintains a cache of managed entities and using commit operations user will be able to add/edit multiple records.Implementation Steps Create Java EE Web Application with entity based on Dept(sequences enabled on deptId), then create a stateful session bean with Transaction Type as "CMT with Explicit Commit" and data control for the session bean.  "CMT with Explicit Commit" supported in Oracle JDeveloper 12.1.2.0.0In View controller project, create jspx page. Drop deptFindAll->Table/List View as ADF Table with  multi-selection option enabled. Run the jspx page (i.e the web page look something like the image shown below). Notice here the commit button will be disabled. Once user click on the create button, commit button will get enabled. Here we will create two records, so clicking the create button twice. Enter the dept details and click on commit button to save the records. You can also configure @SequenceGenerator/@TableGenerator to auto generate the DeptNo. Result page should contains newly added records.

Let us take a scenario where in users wants to add/edit multiple records in the ADF table,  earlier with stateless session bean we need have work around to achieve this scenario. This scenario can be...

Faces

How to create cascading (depending) auto suggest behavior using BC4J

In continuation to my previous blog on "How to create multilevel cascading (dependent) list of values using BC4J", i am tryingto leverage a similar usecase using af:autoSuggestBehavior inthis article. Though the usecase looks same, the implementation isslightly different for this. Let us assume a usecase where we have some text fields with autosuggest feature enabled, and their suggested items could bedependent on one other. For ex : Country, State and City. This could be modeled by having an EO and VO created based onPerson table and read-only look-up VOs created based on Country,State and City tables. Implementing the dependency between LOVs is pretty straightforward. However, implementing the dependency between the autosuggest items is not. In order to achieve the dependency, first wewould need couple of methods returning current row's CountryId andStateId. We could add them up in the AMImpl class. public NumbergetCurrentCountryId(){ return (Number)this.getPersonView1().getCurrentRow().getAttribute("CountryId"); } public Number getCurrentStateId(){ return (Number)this.getPersonView1().getCurrentRow().getAttribute("StateId"); } As we need to filter out the States based on the Country and theCity based on the Country & State, we would need to modify thequery of these two VOs to include a bind variable in the whereclause. For having the auto suggest, we need to have a view criteriadefined for all the three look-up VOs (CountryView, StateView andCityView). Generate VOImpl classes for Country, State and City VOs (withInclude bind variable accessors option checked), and then exposesetBindCountryName (in Country VO), setBindStateName (in State VO)and setBindCityName (in City VO) methods as client interfaces. And the last part on the model is to pass the current row'sCountryId and StateId to the Bind Variables defined in the Stateand City VOs. Also, we need to get the VCs created above to beexecuted by default (By editing the VO instance in the AM's datamodel), so that the auto suggest list would be filtered as and whenthe users type. Here, we specify groovy expression for the CountryId and StateIdas adf.object.applicationModule.<methodName>. For moreinformation about using groovy expressions, check out this :http://www.oracle.com/technetwork/developer-tools/jdev/introduction-to-groovy-128837.pdf. With this, we are done with setting up the model layer for theauto suggest dependency. In the View layer, we would create an ADF Form based on thePerson VO, with all the navigation buttons. In order to construct the onSuggest items, we would create TreeBindings for Country VO, State VO and City VO, along with methodaction bindings for the setBindCountryName, setBindStateName andsetBindCityName methods. Now, we could add af:autoSuggestBehavior for CountryId, StateIdand CityId fields. Then, add onSuggest methods in backing bean forpopulating the on suggest items for each fields. onSuggest method for Country field : public List onCountrySuggest(StringsearchCountryName) {ArrayList<SelectItem> selectItems = newArrayList<SelectItem>(); System.out.println(searchCountryName); //get access to thebinding context and binding container at runtime BindingContext bctx =BindingContext.getCurrent(); BindingContainerbindings = bctx.getCurrentBindingsEntry(); //set the bind variablevalue that is used to filter the View Object //query of the suggestlist. The View Object instance has a View //Criteriaassigned OperationBindingsetVariable = (OperationBinding)bindings.get("setBind_CountryName");setVariable.getParamsMap().put("value", searchCountryName);setVariable.execute(); //the data in thesuggest list is queried by a tree binding. JUCtrlHierBindinghierBinding = (JUCtrlHierBinding)bindings.get("CountryView1"); //re-query the listbased on the new bind variable valueshierBinding.executeQuery(); //The rangeSet, thelist of queries entries, is of type//JUCtrlValueBndingRef.List<JUCtrlValueBindingRef> displayDataList =hierBinding.getRangeSet(); for(JUCtrlValueBindingRef displayData : displayDataList){Row rw = displayData.getRow();//populate the SelectItem listselectItems.add(new SelectItem((Integer)rw.getAttribute("Id"),(String)rw.getAttribute("Name")));} returnselectItems; } onSuggest method for State field : public List onStateSuggest(StringsearchStateName) {ArrayList<SelectItem> selectItems = newArrayList<SelectItem>(); System.out.println(searchStateName); //get access to thebinding context and binding container at runtime BindingContext bctx =BindingContext.getCurrent(); BindingContainerbindings = bctx.getCurrentBindingsEntry(); //set the bind variablevalue that is used to filter the View Object //query of the suggestlist. The View Object instance has a View //Criteriaassigned OperationBindingsetVariable = (OperationBinding)bindings.get("setBind_StateName");setVariable.getParamsMap().put("value", searchStateName);setVariable.execute(); //the data in thesuggest list is queried by a tree binding. JUCtrlHierBindinghierBinding = (JUCtrlHierBinding) bindings.get("StateView1"); //re-query the listbased on the new bind variable valueshierBinding.executeQuery(); //The rangeSet, thelist of queries entries, is of type//JUCtrlValueBndingRef.List<JUCtrlValueBindingRef> displayDataList =hierBinding.getRangeSet(); for(JUCtrlValueBindingRef displayData : displayDataList){Row rw = displayData.getRow();//populate the SelectItem listselectItems.add(new SelectItem((Integer)rw.getAttribute("Id"),(String)rw.getAttribute("Name")));} returnselectItems; } onSuggest method for City field : public List onCitySuggest(StringsearchCityName) {ArrayList<SelectItem> selectItems = newArrayList<SelectItem>(); System.out.println(searchCityName); //get access to thebinding context and binding container at runtime BindingContext bctx =BindingContext.getCurrent(); BindingContainerbindings = bctx.getCurrentBindingsEntry(); //set the bind variablevalue that is used to filter the View Object //query of the suggestlist. The View Object instance has a View //Criteriaassigned OperationBindingsetVariable = (OperationBinding)bindings.get("setBind_CityName");setVariable.getParamsMap().put("value", searchCityName);setVariable.execute(); //the data in thesuggest list is queried by a tree binding. JUCtrlHierBindinghierBinding = (JUCtrlHierBinding) bindings.get("CityView1"); //re-query the listbased on the new bind variable valueshierBinding.executeQuery(); //The rangeSet, thelist of queries entries, is of type//JUCtrlValueBndingRef.List<JUCtrlValueBindingRef> displayDataList =hierBinding.getRangeSet(); for(JUCtrlValueBindingRef displayData : displayDataList){Row rw = displayData.getRow();//populate the SelectItem listselectItems.add(new SelectItem((Integer)rw.getAttribute("Id"),(String)rw.getAttribute("Name")));} returnselectItems; } Once after this, we could bind this to theaf:autoSuggestBehavior's suggestedItems property <af:inputText value="#{bindings.CountryId.inputValue}"label="#{bindings.CountryId.hints.label}"columns="#{bindings.CountryId.hints.displayWidth}"autoSubmit="true" shortDesc="#{bindings.CountryId.hints.tooltip}" id="it3"><af:autoSuggestBehaviorsuggestedItems="#{viewScope.AutoSuggestBean.onCountrySuggest}"/></af:inputText><af:inputText value="#{bindings.StateId.inputValue}"label="#{bindings.StateId.hints.label}"columns="#{bindings.StateId.hints.displayWidth}"autoSubmit="true" partialTriggers="it3"shortDesc="#{bindings.StateId.hints.tooltip}" id="it4"><af:autoSuggestBehaviorsuggestedItems="#{viewScope.AutoSuggestBean.onStateSuggest}"/></af:inputText><af:inputText value="#{bindings.CityId.inputValue}"label="#{bindings.CityId.hints.label}"columns="#{bindings.CityId.hints.displayWidth}"autoSubmit="true" partialTriggers="it4"shortDesc="#{bindings.CityId.hints.tooltip}" id="it5"><af:autoSuggestBehaviorsuggestedItems="#{viewScope.AutoSuggestBean.onCitySuggest}"/></af:inputText> Finally, our output would be

In continuation to my previous blog on "How to create multi level cascading (dependent) list of values using BC4J", i am trying to leverage a similar usecase using af:autoSuggestBehavior inthis...

Faces

Display Holiday Name in af:calendar

When using af:calendarcomponent in the realtime applications, there is a frequentrequirement to display the holdays in it. In this article, we willsee how to achieve that. After setting the environment, we would be expecting the outputas shown in the below image. Assuming we already have a page with calendar, the individualdate level customizations can be done by using DateCustomizer. For this, we would create a custom class that extendsDateCustomizer class. public class MyDateCustomizer extends DateCustomizer{ public String format(Date date, String key, Locale locale,TimeZone tz) { // For illustrative purpose // Hashmap holding the holiday list HashMap holidays = new HashMap(); holidays.put(new Date("25-Dec-2012"),"Christmas"); holidays.put(new Date("01-Jan-2013"), "NewYear"); if("af|calendar::month-grid-cell-header-misc".equals(key)) { returnholidays.get(date)!=null?holidays.get(date).toString():null; } return null; } } As per the tag doc, following keys are passed to the formatmethod. "af|calendar::day-header-row" "af|calendar::list-day-of-month-link"Year's Day". "af|calendar::list-day-of-week-column" "af|calendar::month-grid-cell-header-day-link" "af|calendar::month-grid-cell-header-misc" "af|calendar::week-header-day-link" So, in the above code, we return the actual holiday name for the"af|calendar::month-grid-cell-header-misc" key. In order to use the new DateCustomizer in our calendar, wecreate an instance of it in the backing bean and bind it to thecalendar's dateCustomizer property. Bean Code : public class CalendarBean { private MyDateCustomizer holidays = newMyDateCustomizer(); ; public CalendarBean() { } public void setHolidays(MyDateCustomizerholidays) { this.holidays =holidays; } public MyDateCustomizer getHolidays() { return holidays; } } Page Source : <af:calendar id="c1"dateCustomizer="#{viewScope.CalendarBean.holidays}"/> If needed, the text can be styled to be displayed in differentcolor (as shown in the image at the top). For this, we can have astyleclass in the css af|calendar::month-grid-cell-header-misc { background-color: Yellow; }

When using af:calendar component in the realtime applications, there is a frequent requirement to display the holdays in it. In this article, we will see how to achieve that. After setting the...

Webservices

Exposing Multiple Methods under One Resource In a Single URL Data Control

Previously, a URL Data Control could be associated with only one HTTP Method. So  if the developer had to expose multiple operations under  a single Resource, he/she had to create one DC for each operation.  Now since Jdeveloper  supports such a functionality from 11.1.2.2.0 version, multiple operations can be included in a single DC. This blog explains how to include all the operations exposed by a REST Service Resource in a single Data Control. We will use following REST Service to create URL Data Control. import java.util.ArrayList;import java.util.Iterator;import javax.ws.rs.Consumes;import javax.ws.rs.DELETE;import javax.ws.rs.GET;import javax.ws.rs.POST;import javax.ws.rs.Path;import javax.ws.rs.Produces;import javax.ws.rs.QueryParam;@Path("project1")public class EmployeeService { private ArrayList<Employee> EmpList = new ArrayList<Employee>(); public EmployeeService() { EmpList.add(new Employee("Adam", 1001, 35, "ADF")); EmpList.add(new Employee("Bob", 1002, 42, "HR")); EmpList.add(new Employee("George", 1003, 54, "Apps")); } @GET @Produces("application/xml") public ArrayList<Employee> getEmpList() { return EmpList; } @POST @Consumes("application/xml") @Produces("application/xml") public ArrayList<Employee> addEmployee(Employee emp) { EmpList.add(emp); return EmpList; } @DELETE @Consumes("text/plain") public ArrayList<Employee> deleteEmployee(@QueryParam("name") String name) { Iterator it = EmpList.iterator(); while (it.hasNext()) { Employee tmp = (Employee) it.next(); if (tmp.getName().equalsIgnoreCase(name)) EmpList.remove(tmp); } return EmpList; }} import javax.xml.bind.annotation.XmlRootElement;@XmlRootElementpublic class Employee { String name; int id; int age; String dept; public Employee() { super(); } Employee(String name, int id, int age, String dept) { this.name= name; this.id=id; this.age=age; this.dept=dept; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setId(int id) { this.id = id; } public int getId() { return id; } public void setAge(int age) { this.age = age; } public int getAge() { return age; } public void setDept(String dept) { this.dept = dept; } public String getDept() { return dept; }} Run the REST Service before commencing with Data Control.  To begin with, create ADF Fusion Application. In Model project invoke create DC Wizard. Name your Data Control RESTDC and click on Next to create URL Connection. In the next step, give a name to the URL connection, for example URLConn and specify localhost address in the URL Endpoint field. Also, choose GET as HTTP Method and supply remaining part of REST Service URL in the source field. In Step 4, choose XML as the data format from the drop down menu. Click Next. XSD will be auto generated by the jdeveloper. In step 5, click on Test URL Connection to check if the connection has been successfully generated. Click on finish to complete the wizard. The Data Control for GET method in the REST Service has been created successfully and can be viewed under Data Controls Panel. Now, we will add remaining HTTP Methods in the service to RESTDC. Invoke Create URL DC Wizard in the Model project. Give RESTDC (same name as the previous DC) in the Name field and choose URLConn from the drop- down. Select POST as the HTTP Method and supply the path to POST Operation in source field. In the next step, specify the XSD which specifies the structure of the request content. Click Next.Choose XML Data format from the drop-down and complete the wizard. You can see another operation added to the same Data Control in the DC Panel. Similarly invoke Create URL DC Wizard to add DELETE Method to RESTDC. In step 3, you will be asked to enter a value to test whether URL and source are valid. Enter  "abc" in the values field against param. Choose XML as Data format and complete the wizard. Now the Data Controls Panel has all three operations GET, POST and DELETE which are in the resource under a single URL DC. The names of these methods (loadData, loadData1 etc) can be changed from DataControls.dcx file.

Previously, a URL Data Control could be associated with only one HTTP Method. So  if the developer had to expose multiple operations under  a single Resource, he/she had to create one DC for each...

ADF Desktop Integration

How to access published ADFdi enabled excel workbook from ADF Library jar

We generally tend to create multiple applications and re-use them in one main application by adding them as ADF Library jars.Applications with ADF Desktop Integration support added to ViewController can also be re-used.This blog is about how to access workbooks in ADF Library jar from a different application(which consumes ADF Library Jar).Assumption : Let's assume that a simple ADF application(TestApp) is created with Dept and Emp as entities and added as Master Form Detail Table in jspx.Also an ADFdi enabled excel workbook is created to simulate DeptView and EmpView as Master Form Detail Table.Publish the workbook(PBook1.xlsx) and store it in ViewController/public_html/excel/ folder and check for the working of published workbook by re-deploying the application.Now,let's proceed to the steps to be done before deploying ViewController as ADF Library jar.Open web.xml in ViewController->Web Content->WEB-INF of TestApp, in Filters tab, check for adfBindings and adfdiExcelDownload filters. If not present add by referring this ADFdi guide. Create a new deployment profile for ViewController by right-click ViewController and Deploy->New Deployment profile. Select ADF Library Jar File as Profile Type and give a profile name like TestAppLibJar Create a new custom application(ClientApp) with ADF ViewController as project.Create a FileSystemConnection to import the deployed library jar of TestApp as below:In Resource Pallete, open New File System Connection, give Connection Name as TestAppConn and for DirectoryPath browse and select the deploy folder inside ViewController of TestApp application. Select ViewController of ClientApp, expand the TestAppConn(File System Connection) created, select TestAppLibJar, right-click and Add to Project. In Confirmation dialog, click on Add Library, In ViewController add ADF Desktop Integration support by right-click ViewController->Project Properties->Features, click on + sign and move ADF Desktop Integration from Available to Selected. Add ADF Library Web Application Support into ViewController of ClientApp by right-click ViewController->Project Properties->ADF View, select Enable ADF Library WebApp Support checkbox. Open web.xml and check for the correct ordering of ADFLibraryFilter and adfdiExcelDownload filter. Make sure adfdiExcelDownload filter is above ADFLibraryFilter. Add Initialization Parameter for ADFLibraryFilter with Name 'include-extension-list' and Value 'png,jpg,jpeg,gif,js,css,htm,html,xlsx' as shown in above pic.Now we will create a jspx page and add Go link with Text 'Download Excel' and Destination '/excel/PBook1.xlsx' Run the jspx page and click on Download Excel link. Click on Open, and give yes in Login dialog. There we go, here is our published workbook.

We generally tend to create multiple applications and re-use them in one main application by adding them as ADF Library jars.Applications withADF Desktop Integration support added to ViewController...

Faces

Interpret af:query's queryEvent and display popup to end user using QueryListener

Found an interesting question on OTN. Based on the question, wired a usecase to try out.Usecase : Show a warning to user when they try to search the records (af:query component), without specifying a criteria / a wild card "%". I.e, when the user tries to query the entire table, show a warning that querying all the records would take some time. There are three phases in implementing this usecase.1. Interpret the query event and get the query criteria.2. Show the popup.3. Process the interpreted query based on the outcome of the popup.Before proceeding with the implementation, we'll create a page for assumption.a. Page contains a af:query component with a resultant table / read-only table.b. Has a popup to be shown to the end user.c. Bound to a bean.We'll now implement it phase by phase.First of all, we'll create couple of attributes in the bean and generate accessors to them.     private RichTable empTable;    private boolean warnUser=true;   // Set the default queryListener property value of the af:query component   // for mexpr.   private String mexpr = "#{bindings.ImplicitViewCriteriaQuery.processQuery}";     private QueryEvent qEvt;    public void setEmpTable(RichTable empTable) {        this.empTable = empTable;    }    public RichTable getEmpTable() {        return empTable;    } Now, we need to trap the query event of the af:query component to perform the desired task. We can add a queryListener and bind it to the af:query component   public void processQuery(QueryEvent queryEvent) {        // store the queryEvent in a bean attribute, to be used in another method.        qEvt = queryEvent;        // Reset the flag. This flag would be used to check if the system has to         //raise the popup or not        warnUser=false;        DCBindingContainer bc =           (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();            // Get the view criteria that would be applied.         // findExecutableBinding method takes two parameters.         // id of the searchRegion executable binding         // criteria for the searchRegion executable binding         // Ex : <searchRegion Criteria="__ImplicitViewCriteria__"               // Customizer="oracle.jbo.uicli.binding.JUSearchBindingCustomizer"         //         Binds="EmpView1Iterator" id="ImplicitViewCriteriaQuery"/>        ViewCriteria vc = JUSearchBindingCustomizer.getViewCriteria((DCBindingContainer)bc.findExecutableBinding("ImplicitViewCriteriaQuery"),"__ImplicitViewCriteria__");        ViewCriteriaRow vcr = (ViewCriteriaRow)vc.get(0);        // Some logic to set the flag. Here, checking if the Ename attribute has        // no value specified / used a wildcard expression ("%").        for(int i=0;i<vcr.getAttributeNames().length;i++) {            if(vcr.getAttributeNames()[i] == "Ename" &&  ("%".equals(vcr.getAttributeValues()[i]) || vcr.getAttributeValues()[i]==null))                 warnUser=true;        }        if(warnUser)             showPopup();        else             executeQuery();    } showPopup and executeQuery are custom methods to show the popup and to process the query respectively.     public void showPopup(){        UIViewRoot root = FacesContext.getCurrentInstance().getViewRoot();        RichPopup popup = (RichPopup) root.findComponent("p1");        RichPopup.PopupHints hints = new RichPopup.PopupHints();        popup.show(hints);    } // This method invokes the method expression used by af:query component programatically    public void executeQuery(){        processMethodExpression(mexpr, new Object[] {qEvt}, new Class[] {QueryEvent.class});         AdfFacesContext adfFacesContext = AdfFacesContext.getCurrentInstance();         adfFacesContext.addPartialTarget(empTable);     }    private Object processMethodExpression(String methodExpression, Object[] parameters, Class[] expectedParamTypes) {         FacesContext fctx = FacesContext.getCurrentInstance();         ELContext elctx = fctx.getELContext();         Application app = fctx.getApplication();         ExpressionFactory exprFactory = app.getExpressionFactory();         MethodExpression methodExpr = exprFactory.createMethodExpression(elctx, methodExpression, Object.class, expectedParamTypes);         return methodExpr.invoke(elctx, parameters);         } Now, we need to bind the custom querListener created above to the af:query component <af:query id="qryId2" headerText="Search" disclosed="true"   value="#{bindings.ImplicitViewCriteriaQuery.queryDescriptor}"   model="#{bindings.ImplicitViewCriteriaQuery.queryModel}"   queryListener="#{viewScope.QueryBean.processQuery}"..... We are almost there. Now, when we run the page and query for the records by keeping Ename as null (in the query panel), we would get the popup. Final step is to handle the user action on the popup and then proceed executing the query / to stop it.For this, we'll create a dialog listener and bind it to popup. public void onDialog(DialogEvent dialogEvent) {        Outcome o = dialogEvent.getOutcome();        if(o == Outcome.yes)             executeQuery();    }                 <af:popup childCreation="deferred" autoCancel="disabled" id="p1">                    <af:dialog id="d2" type="yesNo" title="Are you sure?"                               dialogListener="#{viewScope.QueryBean.onDialog}">                        <af:outputText value="It would be time consuming to query for all records. Are you sure you want to continue?" id="ot9"/>                        <f:facet name="buttonBar"/>                    </af:dialog>                </af:popup> Here is how the runtime would be. Enter % for Ename and hit the Search button " class="mt-enclosure mt-enclosure-image"> Popup with a warning message displayed Clicking on Yes / No on the popup performs respective task (perform query / cancel query).

Found an interesting question on OTN. Based on the question, wired a usecase to try out.Usecase : Show a warning to user when they try to search the records (af:querycomponent), without specifying a...

ADF

An Epic Question "How to call a method when the page loads"

Quite often, there comes a question in OTN, with different subjects, all meaning "How to call a method when my ADF page loads?". More often, people tend to take the approach of ADF Phase Listener by overriding before/afterPhase methods.In this blog, we will go through different options in achieving it.1. Method Call Activity as default activity in Taskflow :If the application is built with taskflows, then this is the best suited approach to take. 1.a. Calling a Data Control Method :To call a Data Control method (ex: A method in AMImpl exposed as client interface), simply Drag and Drop the method as Default Method Call Activity, then draw a control flow case from the method to your page. Once after this, drop the taskflow as region in main page. When we run the main page, the Method Call Activity would be called first, and then the page will be rendered.1.b. Calling a Method in Backing Bean:To call a method in the backing bean before pageload, we can follow the similar approach as above. Instead of binding the Method Call Activity to an action/method binding in pagedef, we bind to the method. Insert a Method Call Activity (and make it as default) from the Component Palette. Double click on to select a method to bind. This approach can also be used, to perform some action in backing bean along with calling a method Data Control (just need to add bindings code in backing bean to execute DC method). 2. Using invokeAction Executable :If the application is built with pages and no taskflows are involved, then this option can be taken into consideration.In the page definition of the page, add an invokeAction Executable and bind it to the method needed to be executed. 3. Using combination of Server and Client Listeners : If the page does not have any page definition, then to call a method in backing bean, this approach can be taken. In this, a serverListener would be added at the document level, which would be calling the method in backing bean. Along with this, a clientListener would be added with "load" type (i.e will be triggered when the page loads), which would queue a serverEvent to trigger the method. 4. Using Page Phase Listener :This should be the last resort. Care should be taken when using this approach since the Phase Listener would be called for each request sent by the client.Zeeshan Baig's blog covers this scenario.

Quite often, there comes a question in OTN, with different subjects, all meaning "How to call a method when my ADF page loads?". More often, people tend to take the approach of ADF Phase Listener by...

Webservices

Executing Put operation of REST service programatically from ADF App

In quite some cases, we would like to call the PUT method on a REST service by constructing the parameters during runtime and pass it on. In this article, we would go through how to deal with such cases when building an ADF Application. Refer this tutorial for introduction to REST service in where, GET and DELETE methods are explained. In this sample, we'll see how to implement PUT operation using a HashMap. In fact, as like in the above tutorial, we can directly execute the PUT method as well. This article is mainly concentrated on how to construct the parameters dynamically at runtime. First let us create a simple POJO to hold employee records. package project1;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElementpublic class Emp { public Emp() { super(); } private String name; private int id; private int exp; private int salary; public Emp(String name, int id, int exp, int salary) { super(); this.name = name; this.id = id; this.exp = exp; this.salary = salary; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setId(int id) { this.id = id; } public int getId() { return id; } public void setExp(int exp) { this.exp = exp; } public int getExp() { return exp; } public void setSalary(int salary) { this.salary = salary; } public int getSalary() { return salary; } public String toString() { String empXml = "<name>"+getName()+"</name>"+"\n"+ "<id>"+getId()+"</id>"+"\n"+ "<experience>"+getExp()+"</experience>"+"\n"+ "<salary>"+getSalary()+"</salary>"; return empXml; }}Then, create a REST service using the for the Employee. package project1;import javax.ws.rs.Path;import java.util.*;import javax.ws.rs.Consumes;import javax.ws.rs.DELETE;import javax.ws.rs.GET;import javax.ws.rs.POST;import javax.ws.rs.PUT;import javax.ws.rs.PathParam;import javax.ws.rs.Produces;import javax.ws.rs.QueryParam;import javax.ws.rs.core.Response;@Path("/test")public class Service { static ArrayList<Emp> emp = new ArrayList<Emp>(); public Service() { super(); } @GET @Produces("application/xml") public ArrayList<Emp> getEmps() { return emp; } @DELETE public void deleteEmp(@QueryParam("id") int id) { emp.remove(getObj(id)); } @PUT @Consumes("application/xml") public void addEmp( Emp e) { emp.add(e); } @PUT @Path("defaultEmp") public Response addEmp() { emp.add(new Emp("abc",1,5,10000)); emp.add(new Emp("xyz",2,7,15000)); emp.add(new Emp("lmn",3,5,8000)); return Response.ok().build(); } @POST public void upadteEmp(@QueryParam("id")int id,Emp e) { deleteEmp(id); addEmp(e); } public Emp getObj(int id) { Iterator i = emp.iterator(); while(i.hasNext()){ Emp emp = (Emp)i.next(); if((emp.getId())==id) { System.out.println(emp.getName()); return emp; } } return null; }}We'll come to the UI part now.After creating a Fusion Web Application from JDeveloper, create a new URL Data Control for the REST service created above (for GET and PUT Operations).DataControls.dcx looks like below Now, our aim is to have a UI, from where we can enter the employee details. Once after having the data, construct parameter object and execute loadData (PUT) method.This is done by having 4 input texts and bind them to attributes in the backing bean. Drag and Drop the loadData method from RestPut DataControl (and do not specify a value for the parameter).And the code snippet of the jspx page <af:panelFormLayout id="pfl1"> <f:facet name="footer"> <af:commandButton text="Put" disabled="#{!bindings.loadData.enabled}" id="cb1" actionListener="#{pageFlowScope.RestBean.performPut}"/> </f:facet> <af:inputText label="Id" id="it1" value="#{pageFlowScope.RestBean.id}" autoSubmit="true"/> <af:inputText label="Name" id="it2" autoSubmit="true" value="#{pageFlowScope.RestBean.name}"/> <af:inputText label="Exp" id="it3" value="#{pageFlowScope.RestBean.exp}" autoSubmit="true"/> <af:inputText label="Sal" id="it4" autoSubmit="true" value="#{pageFlowScope.RestBean.sal}"/></af:panelFormLayout> In the backing bean (RestBean), we have 4 attributes with accessors that are mapped to the Text Items. private Number id,sal,exp; private String name; public void setId(Number id) { this.id = id; } public Number getId() { return id; } public void setSal(Number sal) { this.sal = sal; } public Number getSal() { return sal; } public void setExp(Number exp) { this.exp = exp; } public Number getExp() { return exp; } public void setName(String name) { this.name = name; } public String getName() { return name; } Now, we'll add an actionListener code in the backing bean, in that, we can construct a Map with the required values and then execute the method by passing Map to it. public void performPut(ActionEvent actionEvent) { BindingContainer bindings = getBindings(); Map putParamMap = new HashMap(); putParamMap.put("id", getId()); putParamMap.put("name", getName()); putParamMap.put("exp", getExp()); putParamMap.put("sal", getSal()); OperationBinding operationBinding = bindings.getOperationBinding("loadData"); operationBinding.getParamsMap().put("emp",putParamMap); Object result = operationBinding.execute(); if (!operationBinding.getErrors().isEmpty()) { System.out.println("Error processing put operation.."); } } public BindingContainer getBindings() { return BindingContext.getCurrent().getCurrentBindingsEntry(); }In the above code, we find the loadData method from the DataBindings entry, create a Map with all the required attributes to create an Employee record, get the Parameter list for the method and pass the Map to method as parameter to execute it.

In quite some cases, we would like to call the PUT method on a REST service by constructing the parameters during runtime and pass it on. Inthis article, we would go through how to deal with such...

ADF

Construct ADF Master Detail Tree using EJB Datacontrol Objects programatically

This article describes the creation of master detail Treeusing EJB Datacontrol Objects.Use Case DescriptionConstructADF Tree using Employees & Departments objects.It is straightforward to build a tree when foreign key relationship exists betweenthe objects. For cases where no foreign key relationships exist, we canuse this technique to programatically construct the tree in the viewlayer. Implementation stepsLet us suppose that we have created Java EE Web Application with Entities from Employees & Departments table .Also add 'ADF Faces Components 11' under ViewController->project properties-> JSP Tag Libraries.Then we will create Stateless Session Bean and and generate data control for the Stateless Session Bean.Create Tree.jspx page .Goto its page definition overview editor & create table Binding for departmentsFindAll Similarly create table binding for employeesFindAll.Now we will create 2 Beans: TreeItem.java  - Defines Tree structure DisplayTree.java Managed bean - Programatically construct tree node items Copy this code in Tree.jspx source page:<af:tree var="node" value="#{DisplayTree.model}">   <f:facet name="nodeStamp">    <af:outputText id="l1" value="#{node.text}"/>    </f:facet></af:tree>Run the page & it displays Departments->Employees Tree .

This article describes the creation of master detail Tree using EJB Datacontrol Objects.Use Case Description Construct ADF Tree using Employees & Departments objects.It is straightforward to build a...

EJB

EJB DataControl - programmatically construct Master-Detail hierarchy

Sometimes, in EJB data control it is necessary to construct Master-Detail relationships across different levels pro-grammatically. One of the most common use cases is construct the master-detail relation based on database tables where tables doesn't have foreign key relationship. So in this article, I'm trying to construct master-detail hierarchy pro-grammatically by taking simple custom_dept, custom_emp tables. You can download the sample workspace from here[Runs with Oracle JDeveloper 11.1.2.0.0 (11g R2) + HR Schema]Note:- In Bean Data Control, Master-Detail hierarchy can be constructed as a same way but  java bean classes to be created first and then pro-grammatically populate the data in session facade.Model Diagram: Note:- Here entities doesn't have any foreign key relationship. DB script for creating the tables and inserting the data required for this application is in application/etc folder. Implementation StepsCreate Java EE Web Application with entities based on custom_dept and custom_emp tables, then create a session bean and data control for the session bean. Open cusotm_dept entity and create a transient variable called "empCollection" and add the below code. @Transientprivate Collection<CustomEmp> empCollection = new ArrayList();public void setEmpCollection(Collection<CustomEmp> empCollection) {this.empCollection = empCollection;}public Collection<CustomEmp> getEmpCollection() {return empCollection;} Open session facade, add the below code to the session facade and expose the masterDetailFindAll() method in local/remote interface and generate a data control for that.Note:- Here in the below code "em" is a EntityManager. public List<CustomDept> masterDetailFindAll() {String deptQueryString = "select * from custom_dept";System.out.println(deptQueryString);Query deptSearchQuery = em.createNativeQuery(deptQueryString, "deptQuery");List deptResultList = deptSearchQuery.getResultList();Iterator deptListIterator = deptResultList.iterator();List<CustomDept> deptList = new ArrayList();while (deptListIterator.hasNext()) {Object deptCol[] = (Object[])deptListIterator.next();CustomDept dept = new CustomDept();BigDecimal departmentId = (BigDecimal)deptCol[0];dept.setDepartmentId(departmentId);dept.setDepartmentName((String)deptCol[1]);dept.setLocationId((BigDecimal)deptCol[2]);String empQueryString ="select * from custom_emp emp, custom_dept dept where emp.department_id = dept.department_id and dept.department_id = " +departmentId;Query empSearchQuery = em.createNativeQuery(empQueryString, "empQuery");List empResultList = empSearchQuery.getResultList();Iterator empListIterator = empResultList.iterator();List<CustomEmp> empList = new ArrayList();while (empListIterator.hasNext()) {Object empCol[] = (Object[])empListIterator.next();CustomEmp emp = new CustomEmp();emp.setEmployeeId((BigDecimal)empCol[0]);emp.setFirstName((String)empCol[1]);emp.setLastName((String)empCol[2]);emp.setEmail((String)empCol[3]);emp.setJobId((String)empCol[4]);emp.setDepartmentId((BigDecimal)empCol[5]);empList.add(emp);}dept.setEmpCollection(empList);deptList.add(dept); } return deptList;} In the ViewController create index.jspx page, from data control palettedrag and drop masterDetailFindAll()->CustomDept->empCollection->Master-Detail as ADF Master Form, Detail Table. Run the index.jspx page, now we can traverse through Master-Detail records.

Sometimes, in EJB data control it is necessary to construct Master-Detail relationships across different levels pro-grammatically. One of the most common use casesis construct the master-detail...

EJB

Display Lookup values from related ejb entities using JOIN FETCH

JOIN FETCH - The purpose of JOIN FETCH is to fetch the related objects from the database in a single query. So in this article, I'm trying to explain how can we use jpql JOIN FETCH and expose those attributes to EJB data control layer.Take a scenario, where we need to build ADF tree based on departments,employees and location tables. While displaying the tree, root node should display departmentName along with city attribute which is stored in related object Location table.Model Diagram: In BC4J, this scenario can be implemented using Entity Objects facility provided in View Object layer. These entity objects are used by the view object for accessing the related objects attributes and will be exposed in data control layer automatically.Same behavior can be implemented in EJB using JOIN FETCH. Using this query improves the efficiency of iteration over the result Departments objects because it eliminates the need for retrieving the associated Location objects separately.So in single query related objects attributes is also fetched from the database.You can download the sample workspace from here[Runs with Oracle JDeveloper 11.1.2.0.0 (11g R2) + HR Schema]Implementation StepsCreate Java EE Web Application with entities based on Departments, Employees and Location table, then create a session bean and data control for the session bean.Open the departments entity and alter the named query as below. @NamedQuery(name = "Departments.findAll", query = "select o from Departments o join fetch o.locations") Note:- The query above returns Departments instances and guarantees that the locations attributes will already be fetched in the returned instances. Now we need to expose the location attribute values to data control, create a Transient variable called "city" and add the below code in department entity. @Transient private String city;public String getCity() { return this.locations.getCity();} Note: Can create sample java client to check whether the city attribute value is coming in departments instance before proceeding to data control. In the ViewController create index.jspx page, from data control palette drop departmentsFindAll->Tree as ADF Tree and in edit tree bindings select the attributes as shown in below image. Run the index.jspx page. Now notice root node will display departmentName along with city attribute value also.

JOIN FETCH - The purpose of JOIN FETCH is to fetch the related objects from the database in a single query. So in this article, I'm trying to explain how can we use jpql JOIN FETCH and expose...

EJB

EJB Named Criteria - Apply bind variable in Backingbean

EJB Named criteria are predefined and reusable where-clause definitions that are dynamically applied to a ViewObject query. Here we often use to filter the ViewObject SQL statement query based on Where Clause conditions.Take a scenario where we need to filter the SQL statements query based on Where Clause conditions, instead of playing with SQL statements use the EJB Named Criteria which is supported by default in ADF and set the Bind Variable parameter at run time.You can download the sample workspace from here[Runs with Oracle JDeveloper 11.1.2.0.0 (11g R2) + HR Schema] Implementation StepsCreate Java EE Web Application with entity based on Employees table, then create a session bean and data control for the session bean.Open the DataControls.dcx file and create sparse xml for as shown below. In sparse xml navigate to Named criteria tab -> Bind Variable section, create binding variable deptId. Now create a named criteria and map the query attributes to the bind variable. In the ViewController create index.jspx page, from data control palette drop employeesFindAll->Named Criteria->EmployeesCriteria->Table as ADF Read-Only Filtered Table and create the backingBean as "IndexBean".Open the index.jspx page and remove the "filterModel" binding from the table, add <af:inputText />, command button and bind them to backingBean. For command button create the actionListener as "applyEmpCriteria" and add below code to the file. public void applyEmpCriteria(ActionEvent actionEvent) { DCIteratorBinding dc = (DCIteratorBinding)evaluteEL("#{bindings.employeesFindAllIterator}"); ViewObject vo = dc.getViewObject(); vo.applyViewCriteria(vo.getViewCriteriaManager().getViewCriteria("EmployeesCriteria")); vo.ensureVariableManager().setVariableValue("deptId", this.getDeptId().getValue()); vo.executeQuery();}/** * Programmtic evaluation of EL * * @param el EL to evalaute * @return Result of the evalutaion */public Object evaluteEL(String el) {FacesContext fctx = FacesContext.getCurrentInstance();ELContext elContext = fctx.getELContext();Application app = fctx.getApplication();ExpressionFactory expFactory = app.getExpressionFactory();ValueExpression valExp = expFactory.createValueExpression(elContext, el, Object.class);return valExp.getValue(elContext);}Run the index.jspx page, enter departmentId value as 90 and click in ApplyEmpCriteria button. Now the bind variable for the Named criteria will be applied at runtime in the backing bean and it will re-execute ViewObject query to filter based on where clause condition.

EJB Named criteria are predefined and reusable where-clause definitions that are dynamically applied to a ViewObject query. Here we often use to filter the ViewObject SQLstatement query based on Where...

ADF

Implement Tree/Details With Taskflow Regions Using EJB

This article describes on Display Tree/Details using taskflow regions.Use Case DescriptionLet us take scenario where we need to display Tree/Details, left region contains category hierarchy with items listed in a tree structure (ex:- Region-Countries-Locations-Departments in tree format) and right region contains the Employees list.In detail, Here User may drills down through categories using a tree until Employees are listed. Clicking the tree node name displays Employee list in the adjacent pane related to particular tree node. Implementation StepsThe script for creating the tables and inserting the data required for this application CreateSchema.sql Lets create a Java EE Web Application with Entities based on Regions, Countries, Locations, Departments and Employees table. Create a Stateless Session Bean and data control for the Stateless Session Bean. Add the below code to the session bean and expose the method in local/remote interface and generate a data control for that.Note:- Here in the below code "em" is a EntityManager. public List<Employees> empFilteredByTreeNode(String treeNodeType, String paramValue) { String queryString = null; try { if (treeNodeType == "null") { queryString = "select * from Employees emp ORDER BY emp.employee_id ASC"; } else if (Pattern.matches("[a-zA-Z]+[_]+[a-zA-Z]+[_]+[[0-9]+]+", treeNodeType)) { queryString = "select * from employees emp INNER JOIN departments dept\n" + "ON emp.department_id = dept.department_id JOIN locations loc\n" + "ON dept.location_id = loc.location_id JOIN countries cont\n" + "ON loc.country_id = cont.country_id JOIN regions reg\n" + "ON cont.region_id = reg.region_id and reg.region_name = '" + paramValue + "' ORDER BY emp.employee_id ASC"; } else if (treeNodeType.contains("regionsFindAll_bc_countriesList_1")) { queryString = "select * from employees emp INNER JOIN departments dept \n" + "ON emp.department_id = dept.department_id JOIN locations loc \n" + "ON dept.location_id = loc.location_id JOIN countries cont \n" + "ON loc.country_id = cont.country_id and cont.country_name = '" + paramValue + "' ORDER BY emp.employee_id ASC"; } else if (treeNodeType.contains("regionsFindAll_bc_locationsList_1")) { queryString = "select * from employees emp INNER JOIN departments dept ON emp.department_id = dept.department_id JOIN locations loc ON dept.location_id = loc.location_id and loc.city = '" + paramValue + "' ORDER BY emp.employee_id ASC"; } else if (treeNodeType.trim().contains("regionsFindAll_bc_departmentsList_1")) { queryString = "select * from Employees emp INNER JOIN Departments dept ON emp.DEPARTMENT_ID = dept.DEPARTMENT_ID and dept.DEPARTMENT_NAME = '" + paramValue + "'"; } } catch (NullPointerException e) { System.out.println(e.getMessage()); } return em.createNativeQuery(queryString, Employees.class).getResultList(); } In the ViewController project, create two ADF taskflow with page Fragments and name them as FirstTaskflow and SecondTaskflow respectively. Open FirstTaskflow,from component palette drop view(Page Fragment) name it as TreeList.jsff. Open SeconfTaskflow, from component palette drop view(Page Fragment) name it as EmpList.jsff and create two paramters in its overview parameters tab as shown in below image. Open TreeList.jsff , from data control palette drop regionsFindAll->Tree as ADF Tree. In Edit Tree Binding dialog, for Tree Level Rules select the display attributes as follows:-model.Regions - regionNamemodel.Countries - countryNamemodel.Locations - citymodel.Departments - departmentName In structure panel, click on af:Tree - t1 and select selectionListener with edit property. Create a "TreeBean" managed bean with scope as "session" as shown in below Image. Create new method as getTreeNodeSelectedValue and click ok. Open TreeBean managed bean and add the below code: private String treeNodeType;private String paramValue;public void getTreeNodeSelectedValue(SelectionEvent selectionEvent) { RichTree tree = (RichTree)selectionEvent.getSource(); RowKeySet addedSet = selectionEvent.getAddedSet(); Iterator i = addedSet.iterator(); TreeModel model = (TreeModel)tree.getValue(); model.setRowKey(i.next()); JUCtrlHierNodeBinding node = (JUCtrlHierNodeBinding)tree.getRowData(); //oracle.jbo.Row Row rw = node.getRow(); Object selectedTreeNode = node.getAttribute(0); Object treeListType = node.getBindings(); String treeNodeType = treeListType.toString(); this.setParamValue(selectedTreeNode.toString()); this.setTreeNodeType(treeNodeType); } public void setTreeNodeType(String treeNodeType) { this.treeNodeType = treeNodeType; } public String getTreeNodeType() { return treeNodeType; } public void setParamValue(String paramValue) { this.paramValue = paramValue; } public String getParamValue() { return paramValue; }<br />Open EmpList.jsff , from data control palette drop empFilteredByTreeNode->Employees->Table as ADF Read-only Table. After selecting the  Employees result set, in Edit Action Binding dialog window pass the pageFlowScope parameters as shown in below Image. In empList.jsff page, click Binding tab and click on Create Executable binding and select Invoke action and follow as shown in below image. Edit executeEmpFiltered invoke action properties and set the Refresh to ifNeeded, So when ever the page needs the method will be executed. Create Main.jspx page with page template as Oracle Three Column Layout. Drop FirstTaskflow as Region in start facet and drop SecondTaskflow as Region in center facet, Edit task Flow Binding dialog window pass the Input Paramters as shown in below Image. Run the Main.jspx, tree will be displayed in left region and emp details will displyaed on the right region. Click on the Americas in tree node, all emp related to the Americas related will be displayed. Click on Americas->United States of America->South San Francisco->Accounting, only employee belongs to the Accounting department will be displayed.

This article describes on Display Tree/Details using taskflow regions.Use Case Description Let us take scenario where we need to display Tree/Details, left regioncontains category hierarchy with items...

EJB

Achieve Named Criteria with multiple tables in EJB Data control

In EJB create a named criteria using sparse xml and in named criteria wizard, only attributes related to the that particular entities will be displayed.  So here we can filter results only on particular entity bean. Take a scenario where we need to create Named Criteria based on multiple tables using EJB. In BC4J we can achieve this by creating view object based on multiple tables. So in this article, we will try to achieve named criteria based on multiple tables using EJB.Implementation StepsCreate Java EE Web Application with entity based on Departments and Employees, then create a session bean and data control for the session bean.Create a Java Bean, name as CustomBean and add below code to the file. Here in java bean from both Departments and Employees tables three fields are taken. public class CustomBean { private BigDecimal departmentId; private String departmentName; private BigDecimal locationId; private BigDecimal employeeId; private String firstName; private String lastName; public CustomBean() { super(); } public void setDepartmentId(BigDecimal departmentId) { this.departmentId = departmentId; } public BigDecimal getDepartmentId() { return departmentId; } public void setDepartmentName(String departmentName) { this.departmentName = departmentName; } public String getDepartmentName() { return departmentName; } public void setLocationId(BigDecimal locationId) { this.locationId = locationId; } public BigDecimal getLocationId() { return locationId; } public void setEmployeeId(BigDecimal employeeId) { this.employeeId = employeeId; } public BigDecimal getEmployeeId() { return employeeId; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getFirstName() { return firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getLastName() { return lastName; }} Open the sessionEJb file and add the below code to the session bean and expose the method in local/remote interface and generate a data control for that. Note:- Here in the below code "em" is a EntityManager. public List<CustomBean> getCustomBeanFindAll() { String queryString = "select d.department_id, d.department_name, d.location_id, e.employee_id, e.first_name, e.last_name from departments d, employees e\n" + "where e.department_id = d.department_id"; Query genericSearchQuery = em.createNativeQuery(queryString, "CustomQuery"); List resultList = genericSearchQuery.getResultList(); Iterator resultListIterator = resultList.iterator(); List<CustomBean> customList = new ArrayList(); while (resultListIterator.hasNext()) { Object col[] = (Object[])resultListIterator.next(); CustomBean custom = new CustomBean(); custom.setDepartmentId((BigDecimal)col[0]); custom.setDepartmentName((String)col[1]); custom.setLocationId((BigDecimal)col[2]); custom.setEmployeeId((BigDecimal)col[3]); custom.setFirstName((String)col[4]); custom.setLastName((String)col[5]); customList.add(custom); } return customList;} Open the DataControls.dcx file and create sparse xml for customBean. In sparse xml navigate to Named criteria tab -> Bind Variable section, create two binding variables deptId,fName. In sparse xml navigate to Named criteria tab ->Named criteria, create a named criteria and map the query attributes to the bind variables. In the ViewController create a file jspx page, from data control palette drop customBeanFindAll->Named Criteria->CustomBeanCriteria->Query as ADF Query Panel with Table. Run the jspx page and enter values in search form with departmentId as 50 and firstName as "M". Named criteria will filter the query of a data source and display the result like below.

In EJB create a named criteria using sparse xml and in named criteria wizard, only attributes related to the that particular entities will be displayed. So here we can filter results only on...

ADF

Refreshing One Column based on the value of Another Column in ADFdi Table

When using ADF Desktop Integration, quite frequently, we get into a situation where we would like to refresh one column based on the value of another column. In ADF Faces, we can achieve this by setting the autoSubmit property and partialTriggers property for the corresponding columns.However, in ADFdi, we do not have such option. Though we can achieve this by using LOVs and Dependent LOVs. But, in some scenarios we would like to achieve this when using an Input Text Component. In this article, we will simulate this Auto Refresh functionality in a ADFdi Table.Note : Since we would be using VBA code to achieve this, we can use this only on the Macro Enabled Excel Workbooks.Let us assume that we have a View Object based on the Emp table. We could take an example of having a transient attribute in the VO, that gives the sum of Salary and Commission attributes. In the above example, we've added a new transient attribute (SalPlusComm) to the EmpVO, that would give the sum of Sal and Comm attributes. Since we need this attribute to get refreshed when either Sal or Comm attribute changes, we set the Sal and Comm attributes as Dependencies. Also, we set the AutoSubmit property (under UI Hints tab) for the Sal and Comm attributes. Now, we are done with the model layer. We can now, create a jspx page and then Drag and Drop EmpView as ADF Table. After this, we create an Excel Workbook (macro enabled), enable ADF Desktop Integration for it, set the required Workbook Properties, and then add a Table based on the EmpView. As there are no straight forward way in ADFdi to trigger a request to server when a value of a cell is changed, we will now add a DoubleClickActionSet for the Sal and Comm columns. This DoubleClickActionSet will have the Table.RowUpSync and Table.RowDownSync actions. Above example image shows the DoubleClickActionSet for Sal column. In the same manner, we need to add the DoubleClickActionSet for the Comm column as well.Now, we have the workbook, that would fetch the SalPlusComm attribute (after recalculation in the model), when we change the Sal / Comm attribute and then double click on that column. To do this automatically when the user tabs out / presses enter key on the cells, we'll write a bit of VBA Code on the Worksheet where we've this table (Go to Developer Tab and Click on Visual Basic). Private Sub Worksheet_Change(ByVal Target As Range) If Target.Column = 14 Or Target.Column = 15 Then Target.Select Application.CommandBars("Cell").Controls("Invoke Action...").Execute End IfEnd SubExcel would trigger Worksheet_Change event when a cell in the worksheet is modified. So, we would code our logic in that event. The above code assumes that Sal column is present in the N (14th) column on the worksheet and Comm column is present in O (15th) column. So, we would execute our logic only when the contents in these two columns change.ADFdi would provide a context menu (Invoke Action...) when a DoubleClickActionSet is added to a particular column. We'll make use of that context menu and invoke it programatically. We invoke that context menu programatically using the following line of code Application.CommandBars("Cell").Controls("Invoke Action...").Execute Now, we run our workbook, modify the value of Sal column for any row and tab out of that field would automatically update the value of SalPlusComm column. Here, a simple example (Transient Attribute) is taken for the explanation. In the similar fashion, we can also have a DoubleClickActionSet to contain a method in the Impl that would perform this calculation as well. Tip: If you are not able to view the image fully, right click on the image and choose View Image option to see it completely.

When using ADF Desktop Integration, quite frequently, we get into a situation where we would like to refresh one column based on the valueof another column. In ADF Faces, we can achieve this by...

ADF

Dynamic Pie Graph Generation by Drag And Drop Rows from ADF Table

In normal scenarios, we display the graph and chart to get graphical representation of data. In this article, we'll see how to create graph dynamically by dragging the contents from ADF table and dropping on the graph.Environment : JDeveloper PS5 (11.1.1.6.0)Assuming that we have a table that displays the Department's details. We'll build a dynamic pie graph to display the Employee details for the departments that are dragged from the Department's table. For our usecase, we need to drag the Departments from Table and Drop it on the Pie Chart to get the Employees details corresponding to the Depts selected.For this, we need to add DragSource in the Dept Table and DropTarget in Emp Chart. <af:table value="#{bindings.DeptView1.collectionModel}" var="row"  rows="#{bindings.DeptView1.rangeSize}"  emptyText="#{bindings.DeptView1.viewable ? 'No data to display.' : 'Access Denied.'}"  fetchSize="#{bindings.DeptView1.rangeSize}"  rowBandingInterval="0"  selectionListener="#{bindings.DeptView1.collectionModel.makeCurrent}" rowSelection="multiple" id="t1"> <af:dragSource discriminant="Dept" defaultAction="COPY"/> ....  .... <dvt:pieGraph id="pieGraph1" subType="PIE_MULTI" customLayout="CL_NONE"> <af:dropTarget> <af:dataFlavor flavorClass="org.apache.myfaces.trinidad.model.RowKeySet" discriminant="Dept"/> </af:dropTarget> .... .... Now that we've added the drag source and drop target, we need to have a method in our AM/VO's impl class, that take the department number as input and return the list of employees under it and their details as ArrayList. public ArrayList getEmpDetsForDept(int Deptno) { ArrayList empDetsAL = new ArrayList(); getEmpView1().setWhereClause("Deptno=" + Deptno); getEmpView1().executeQuery(); getEmpView1().first(); if(getEmpView1().getRowCount()>0) { empDetsAL.add(new Object[]{""+Deptno, getEmpView1().getCurrentRow().getAttribute("Ename").toString(), new Double(getEmpView1().getCurrentRow().getAttribute("Sal").toString())} ); while (getEmpView1().hasNext()){ empDetsAL.add(new Object[]{""+Deptno, getEmpView1().getCurrentRow().getAttribute("Ename").toString(), new Double(getEmpView1().getCurrentRow().getAttribute("Sal").toString())} ); getEmpView1().next(); } } return empDetsAL; } Now, the main part comes. Pie Graphs can be based on ArrayList. So, in our backing bean, we'll have an attribute of type ArrayList. Also, we'll have a variable to to bind the graph for triggering PPR. private List chartData=new ArrayList(); private UIGraph empChart; public void setChartData(List chartData) { this.chartData = chartData; } public List getChartData() { return chartData; } public void setEmpChart(UIGraph empChart) { this.empChart = empChart; } public UIGraph getEmpChart() { return empChart; }As we need to find out the Departments that are dragged from table, we'll have a method in the backing bean to get the list of dragged Departments, iterate through them, pass each to the AM / VO method created to get Emp details and then construct the ArrayList. public DnDAction dropDeptInPie(DropEvent dropEvent) { RichTable table = (RichTable) dropEvent.getDragComponent(); Transferable t = dropEvent.getTransferable(); DataFlavor<RowKeySet> df = DataFlavor.getDataFlavor(RowKeySet.class, "Dept"); RowKeySet rks = t.getData(df); Iterator iter = rks.iterator(); if(getChartData()!=null) getChartData().clear(); while (iter.hasNext()) { List key = (List)iter.next(); table.setRowKey(key); JUCtrlHierNodeBinding rowBinding = (JUCtrlHierNodeBinding) table.getRowData(); Row row = (Row) rowBinding.getRow(); String Deptno = row.getAttribute("Deptno").toString(); BindingContainer bindings = getBindings(); OperationBinding operationBinding = bindings.getOperationBinding("getEmpDetsForDept"); operationBinding.getParamsMap().put("Deptno", Deptno); ArrayList result = (ArrayList)operationBinding.execute(); if (operationBinding.getErrors().isEmpty()) { if(getChartData()!=null)getChartData().addAll(result); else setChartData(result); } } AdfFacesContext.getCurrentInstance().addPartialTarget(empChart); return DnDAction.NONE; } public BindingContainer getBindings() { return BindingContext.getCurrent().getCurrentBindingsEntry(); } In order to make the Pie Graph use the ArrayList as source, we need to bind this to the tabularData Property of the pie graph. Let us also bind the chart to the variable we created in backing bean and set its dropListener to the method created above. Now, our pieGraph's source in jspx page would look like <dvt:pieGraph id="pieGraph1" subType="PIE_MULTI" customLayout="CL_NONE" binding="#{pageFlowScope.DnDBean.empChart}" tabularData="#{pageFlowScope.DnDBean.chartData}"> <af:dropTarget dropListener="#{pageFlowScope.DnDBean.dropDeptInPie}"> <af:dataFlavor flavorClass="org.apache.myfaces.trinidad.model.RowKeySet" discriminant="Dept"/> </af:dropTarget> Now, let us run the page, select couple of Departments and Drop them on the Pie chart. Here, we've dragged the departments 10 & 30, and dropped them on the chart to get the Salary of the employees belonging to those departments as slices.

In normal scenarios, we display the graph and chart to get graphical representation of data. In this article, we'll see how to create graphdynamically by dragging the contents from ADF table and...

ADF

Passing comma separated string as bind variable for VO query's IN operator

Quite often, we want to pass a parameter to the bind variable in the VO's query with a comma separated value, for the where clause with an IN operator. However, normal SQL query that the VO contain interpret that whole comma separated value as a single String and our usecase fail to get fulfilled.Ex. question in OTN thread : https://forums.oracle.com/forums/thread.jspa?messageID=10125366To overcome this, Mohammad Jabr has written a blog entry with the help of  Steve Muench's example #126. This has been achieved by using a TYPE and CASTing it to get the list.In this article, we'll see another option to alter the query using regexp_substr, without having to use a TYPE and CAST.Let us take an example of a VO created using EMP table with the following query. SELECT Emp.EMPNO, Emp.ENAME, Emp.JOB, Emp.MGR, Emp.HIREDATE, Emp.SAL, Emp.COMM, Emp.DEPTNOFROM EMP Emp We'll add a where clause to the VO's query with a bind variable that takes comma separated string as input. Here, we would be including regexp_substr function (Oracle DB >=10g), to split the comma separated string and return them as rows.Now, our Where clause of the VO's query would be looking like WHERE Emp.ENAME in (select regexp_substr(:Bind_Ename_Comma_Sep_List,'[^,]+', 1, level) from dual connect by regexp_substr(:Bind_Ename_Comma_Sep_List, '[^,]+', 1, level) is not null)Also, we'll add a Bind Variable Bind_Ename_Comma_Sep_List of String data type. Once after modifying the Where Cluase and after adding the bind variable, our VO would be looking like To validate our query, let us run the AM tester to check the result Validate the result by entering a comma separated ENAME list to the bind variable (SMITH,ALLEN,JONES). Check out the query result As it can be seen, we've passed 3 comma separated Enames to the bind variable, which in turn fetched only those records with the matching 3 Enames.

Quite often, we want to pass a parameter to the bind variable in the VO's query with a comma separated value, for the where clause with an INoperator. However, normal SQL query that the VO contain...

ADF Desktop Integration

Custom Upload options in ADF Desktop Integration

About      In ADFdi enabled excel workbook while uploading the changes performed in ADF Table,standard upload options dialog appears like below.     In this article,we will see how to customize these options in a dialog. Usecase     Let us take a simple example of Employee table.ImplementationAssumption: An ADF Web Application with ADF Desktop Integration enabled workbook having Employee table as below screenshot is available. Now let's create a new jspx page titled 'UploadOptions.jspx'.The below code adds two checkboxes and buttons.Let's copy this into the Source view of jspx page.<!-- Check box for AbortUploadOnFailure --><af:selectBooleanCheckbox text="Abort Upload On Failure" id="sbc1"  value="#{requestScope.abortUploadOnFailure}" autoSubmit="true" selected="true"/><!--Check box for DownloadAfterUpload --><af:selectBooleanCheckbox text="Download After Upload" id="sbc2" autoSubmit="true"  value="#{requestScope.downloadAfterUpload}"/><!--Command button for Continue action --><af:button text="Continue" id="b1" inlineStyle="width:100px;" partialSubmit="false"><af:setActionListener from="continue" to="#{requestScope.action}"/></af:button><!-- Command button for Abort action --><af:button text="Abort" id="b2" inlineStyle="width:100px;" partialSubmit="false"><af:setActionListener from="abort" to="#{requestScope.action}" /></af:button>The UploadOptions.jspx page now looks like below: Below Span elements have to be used to perform custom upload actions in ADFdi Table.ADFdiCloseWindow - When a web page has to be closed,this span element can be set toContinue  - to close the web page and invoke next action in actions set orAbort       - to close the web page and terminate the action set.ADFdiAbortUploadOnFailure - If this element is set to True, the action set stops uploading if it encounters a failure. If the element references False, the action set attempts to upload all rows and indicates if each row succeeded or failed to upload.ADFdiDownloadAfterUpload - If this element is set to True, the action set downloads data into the ADFdi Table component after the action set uploads modified data.Let us add the below code at the end of tag Form in source view of jspx,to include the above mentioned span elements.<!-- Closes the Upload Options dialog and then invokes next action in the action set--><f:verbatim rendered="#{requestScope.action eq 'continue'}"><span id="ADFdiCloseWindow">Continue</span></f:verbatim><!-- Closes the Upload Options dialog but aborts next actions in action set--><f:verbatim rendered="#{requestScope eq 'abort'}"><span id="ADFdiCloseWindow">Abort</span></f:verbatim> <!-- If the span element is set to   True, the action set stops uploading if it encounters a failure.  False, the action set attempts to upload all rows and indicates if each row succeeded or failed to upload. --><f:verbatim><span id="ADFdiAbortUploadOnFailure">${requestScope.abortUploadOnFailure}</span>  </f:verbatim>  <!--If the span element is set toTrue, the action set downloads data from the Fusion web application to the ADF Table after the action set uploads modified data --><f:verbatim><span id="ADFdiDownloadAfterUpload">${requestScope.downloadAfterUpload}</span></f:verbatim>In ADFdi excel workbook,let us add this new jspx file as dialog before Table.Upload action in Ribbon Commands of Worksheet Properties. Now we run the excel workbook and download data into ADF Table as shown above.Let's update a row by changing the Sal=4000 of Martin. On clicking Upload Ribbon command like below: the custom upload actions dialog gets opened with 'Abort Upload On Failure' check box selected by default. We can select 'Download After Upload' check box and click on Continue button.We can see data updated and downloaded again with new value like below: This is a simple example of how upload options can be customized. Using this, we can add more custom options to the dialog, which is not available in the standard upload options dialog. We will see such options sooner in my next blog.

About      In ADFdi enabled excel workbook while uploading the changes performed in ADF Table,standard upload options dialog appears like below.     In this article,we will see how to customize these...

ADF

What does featureOff attribute do in af:panelCollection

Panel Collection in ADF (af:panelCollection) has an attribute - featureOff, which manages the visibility of certain controls / features of panelCollection to the end user.As per the doc guide, here are the list of valid values for this attribute. Value Turns off statusBar Status bar viewMenu 'View' menu formatMenu 'Format' menu columnsMenuItem 'Columns' sub-menu item columnsMenuItem:col1,col20 Columns with column ID: 'col1' and 'col20' inside 'Columns' sub-menu freezeMenuItem 'Freeze' menu item detachMenuItem 'Detach' menu item sortMenuItem 'Sort' menu item reorderColumnsMenuItem 'Reorder Columns' menu item resizeColumnsMenuItem 'Resize Columns' menu item wrapMenuItem 'Wrap' menu item showAsTopMenuItem Tree/TreeTable 'Show As Top' menu item scrollToFirstMenuItem Tree/TreeTable 'Scroll To First' menu item scrollToLastMenuItem Tree/TreeTable 'Scroll To Last' menu item freezeToolbarItem 'Freeze' toolbar item detachToolbarItem 'Detach' toolbar item wrapToolbarItem 'Wrap' toolbar item showAsTopToolbarItem Tree/TreeTable 'Show As Top' toolbar item wrap 'Wrap' menu and toolbar items freeze 'Freeze' menu and toolbar items detach 'Detach' menu and toolbar items In this article, we will find out what happens at runtime when different values are specified for this attribute (Note : This attribute takes a space-separated list of default features to be turned off for the panelCollection - as mentioned above)1. statusBar <af:panelCollection id="pc1" featuresOff="statusBar">When we set statusBar to the featuresOff attribute, it hides panelCollection's status bar. 2. viewMenu <af:panelCollection id="pc1" featuresOff="viewMenu">When we set viewMenu to the featuresOff attribute, it completely removes the View Menu. 3. formatMenu  <af:panelCollection id="pc1" featuresOff="formatMenu"> When we set formatMenu to the featuresOff attribute, it completely removes the Format Menu. 4. columnsMenuItem  <af:panelCollection id="pc1" featuresOff="columnsMenuItem"> When we set columnsMenuItem to the featuresOff attribute, it removes the Columns menu item under View menu. Check the next option to hide specific columns. 5. columnsMenuItem:col1,col20<af:panelCollection id="pc1" featuresOff="columnsMenuItem:col1,col2"> When we set columnsMenuItem:.. to the featuresOff attribute, it removes the specified columns from the Columns menu item under View menu. If you want to hide the entire Columns menu item, check the previous option. In the above example image, columns c3 and c4 belong to the columns Empno and Ename. 6. freezeMenuItem <af:panelCollection id="pc1" featuresOff="freezeMenuItem"> When we set freezeMenuItem to the featuresOff attribute, it removes Freeze menu item under View menu . 7. detachMenuItem <af:panelCollection id="pc1" featuresOff="detachMenuItem"> When we set detachMenuItem to the featuresOff attribute, it removes Detach menu item under View menu . 8. sortMenuItem <af:panelCollection id="pc1" featuresOff="sortMenuItem"> When we set sortMenuItem to the featuresOff attribute, it removes entire Sort menu item under View menu . 9. reorderColumnsMenuItem<af:panelCollection id="pc1" featuresOff="reorderColumnsMenuItem"> When we set reorderColumnsMenuItem to the featuresOff attribute, it removes Reorder Columns... menu item under View menu . 10. resizeColumnsMenuItem <af:panelCollection id="pc1" featuresOff="resizeColumnsMenuItem"> When we set resizeColumnsMenuItem to the featuresOff attribute, it removes Resize Columns... menu item under Format menu . 11. wrapMenuItem <af:panelCollection id="pc1" featuresOff="wrapMenuItem"> When we set wrapMenuItem to the featuresOff attribute, it removes Wrap menu item under Format menu . 12. showAsTopMenuItem <af:panelCollection id="pc1" featuresOff="showAsTopMenuItem"> When we set showAsTopMenuItem to the featuresOff attribute, it removes Show as Top and Go to Top menu items under View menu (Applicable for the tree/treeTable) . 13. scrollToFirstMenuItem <af:panelCollection id="pc1" featuresOff="scrollToFirstMenuItem"> When we set scrollToFirstMenuItem to the featuresOff attribute, it removes Scroll to First menu item under View menu (Applicable for the tree/treeTable) . 14. scrollToLastMenuItem <af:panelCollection id="pc1" featuresOff="scrollToLastMenuItem"> When we set scrollToLastMenuItem to the featuresOff attribute, it removes Scroll to Last menu item under View menu (Applicable for the tree/treeTable) . 15. freezeToolbarItem <af:panelCollection id="pc1" featuresOff="freezeToolbarItem"> When we set freezeToolbarItem to the featuresOff attribute, it removes Freeze button from the Toolbar. 16. detachToolbarItem <af:panelCollection id="pc1" featuresOff="detachToolbarItem"> When we set detachToolbarItem to the featuresOff attribute, it removes Detach button from the Toolbar. 17. wrapToolbarItem <af:panelCollection id="pc1" featuresOff="wrapToolbarItem"> When we set wrapToolbarItem to the featuresOff attribute, it removes Wrap button from the Toolbar. 18. showAsTopToolbarItem <af:panelCollection id="pc1" featuresOff="showAsTopToolbarItem"> When we set showAsTopToolbarItem to the featuresOff attribute, it removes Go Up, Go to Top and Show as Top buttons from the Toolbar (Applicable for tree/treeTable). 19. wrap <af:panelCollection id="pc1" featuresOff="wrap"> When we set wrap to the featuresOff attribute, it removes Wrap menu item from Format Menu as well as from the Toolbar. Equivalent to featuresOff="wrapMenuItem wrapToolbarItem". 20. freeze <af:panelCollection id="pc1" featuresOff="freeze"> When we set freeze to the featuresOff attribute, it removes Freeze menu item from View Menu as well as from the Toolbar. Equivalent to featuresOff="freezeMenuItem freezeToolbarItem". 21. detach <af:panelCollection id="pc1" featuresOff="detach"> When we set detach to the featuresOff attribute, it removes Detach menu item from View Menu as well as from the Toolbar. Equivalent to featuresOff="detachMenuItem detachToolbarItem". These options would be useful when using a panelCollection for customizing at end user. A separate options could be provided using these, so that end user can customize the LAF of the panelCollection.

Panel Collection in ADF (af:panelCollection) has an attribute - featureOff, which manages the visibility of certain controls / features of panelCollection to the end user.As per the doc guide, here...

ADF

Business Rules Editor for View Objects in JDeveloper 11.1.2.0.0

JDeveloper 11.1.2.0.0 has a new tab in the View Objects Editor - Business Rules. This easily tend to make people misunderstand that this Editor can be used for adding validation rules for the attributes in the View Object. However, it is not true. Lets check out what this editor is all about. As the online help for this page statesUse to create and maintain business rules based on Groovy Language expressions and declarative validation rules for this view object including: Validators for transient attributes Bind variable default value expressions for SQL queries Bind variable value mappings for view accessors Transient attribute value expressions Transient attribute value expression recalculation conditions Attribute default value expressions We'll see how we can use this editor to edit different types : Transient Attributes :  We can use this editor for a. adding validation rules, b. edit default value expression a. As like the Entity Attributes, we can add many validation rules for the transient attributes in VO as well. Ex. In the above image, EmpType is a transient attribute on Emp VO.We can see there are two rules added. First one is a validation rule (List Validator), restricting the user to enter either one of the value specified for the attribute. Second one is the default value expression for the attribute. Upon selecting the node, the default value groovy expression would become editable in the Script Expression field below, wherein we can modify it and test the syntax as well.Note : We can add the validation rule only for the transient attributes which are Updatable. Also, we can edit only the default values which are script expressions only. Not the literal values.Bind Variables :Similar to the transient attributes, we can use this editor for modifying and testing the default value expression for the Bind Variables of the VO as well.Ex : In the above example image, we can see a Bind Variable (Bind_Hiredate) added to the Query, which has the default value expression as adf.currentDate.Using this editor, we can modify this expression and test the syntax.View Accessor : If we have a bind variable to the VO and use it as List Data Source for any of the attributes in the VO, we can use this editor to change the value of the bind variable in the View Accessor.Ex : In the above example image, we have couple of Bind Variables in the View Accessors (they are used as Lists and Dependent Lists for this View Object). Using this editor, we can edit the values of those bind variables.We can also use this editor for modifying and testing the default value expression on the VO attributes and the re-calculation conditions.

JDeveloper 11.1.2.0.0 has a new tab in the View Objects Editor - Business Rules. This easily tend to make people misunderstand that this Editor can be usedfor adding validation rules for the...

ADF

Project Gantt chart using ADF BC

This article describes simple example of using Project Gantt chart using ADF Business components.Use Case DescriptionLet us create a simple Project Gantt chart using ADF Business components & try to get the selected tasks details. Implementation stepsA project Gantt chart is used for project management. The chart liststasks vertically and shows the duration of each task as a bar on ahorizontal time line.To create a basic project gantt chart,we first need to define  2 tables as below:1)task_table with taskid,task_type,start_date & end_date 2)subtask_table with subtaskid,subtask_type,start_date, end_date &  taskidNow we can create Business components for the above 2 tables .Then we will create new jspx page -projectGantt.jspx Drop TaskView1 as Gantt->Project: Select all required columns under tasks & subtasks tabs of 'create Project Gantt chart' dialog.We have created Project Gantt chart that lists tasks & its subtasks.Now if we need to get all task details selected by the user then define taskSelectionListener for the dvt:projectGantt in jspx source page: taskSelectionListener="#{test.taskSelectlistener}" public void taskListener(TaskSelectionEvent taskSelectionEvent) {// This codes gives all the tasks selected by user System.out.println("Selected task details +taskSelectionEvent.getTask()); }Run the above page & note that it shows all details of tasks nodes & expanding these tasks nodes shows its corresponding subtasks details.Now if user selects 2 tasks,we can see that it prints the complete task details for the selected tasks.

This article describes simple example of using Project Gantt chart using ADF Business components.Use Case DescriptionLet us create a simple Project Gantt chart using ADF Business components & try to...

BC4J

Creating Custom validation rule and register it

What is Validation Rule? Avalidation rule is a piece of code that performs some checkensuring that data meets given constraints.In an enterprise application development environment, often it might require developers to have validation be performed based on some logic at several places across projects. Instead of redundant validation creation, a custom validation rule provides a library with a validation rules that can be registered and used across applications.A custom Validation is encapsulated in a reusable component so that you do not have to writeit every time when you need to do input validation.Here is how we can easily implement a custom validation that checks for name of an employee to be "KING" For creating a custom Validation ,1.        Create Generic Application Workspace "CustomValidator" withthe project "Model" 2.        Create an BC4J based on emp table.3.        Create a custom validation rule.In EmpNamerule class, update thevalidateValue(..) method as follows: public boolean validateValue(Object value) { EntityImpl emp = (EntityImpl)value; if(emp.getAttribute("Ename").toString().equals("KING")){ return false; } return true; } Create ADF Library: Next step would be to create ADF library.Create ADF library with name lets say testADFLibrary1.jarRegister ADF LibraryNext step is to register the ADF library , so that its available across the applications. Invoke the menu "Tools -> Preferences"Select the option "Business Components -> Registered Rules" from left paneClick on button "Pick Library". The dialog "Select Library" comes up with  the user library addedAdd new library' that points to the above jarCheck the checkbox "Register" and set the name for the ruleSample UsageHere is how we can easily implement a validation rule that restrict the name of the employee not to be "KING".Create new Application with BC4J based on EMP table.Create new validation under Business rule tab for Ename & select the above custom validation rule.Run the AppModule tester.

What is Validation Rule? A validation rule is a piece of code that performs some check ensuring that data meets given constraints. Inan enterprise application development environment, often it...

ADF

Create Master Detail Detail records in EJB using Train

This article describes the creation of master detail detail records using EJB Datacontrol.This is done using ADF Train component.Use Case DescriptionLets us consider that we have countries->locations->departments table with master->detail->detail relationship.We will create countries in first train step ,locations in next train step & departments in the last train step.Implementation stepsLet us suppose that we have created Java EE Web Application with Entities from countries ,locations & departments table .Also add 'ADF Faces Components 11' under ViewController->project properties-> JSP Tag Libraries.Then we will create Stateless Session Bean and and generate data control for the Stateless Session Bean.Now create ADF Task Flow by enabling Train option in the Task flow WizardTaskflow shows 3 views that correspond to countries,locations & departments.It also has create method activity defined that creates new record for countries & this is achieved by dropping countriesFindAll->Operations->Create method from EJB Datacontrol:Create country.jsff,location.jsff & department.jsff pages. Drop train component on all these page fragments with value "#{controllerContext.currentViewPort.taskFlowContext.trainModel}" Open country.jsff & from datacontrol drop countriesFindAll as ADF Form without including navigation controls.Also drop persistCountries(Countries) method as ADF Button 'persistCountries' to persist the dataOnce we create countries & persist the data,we would like to navigate to next train step to create locations.This navigation can be achieved by adding action property to 'persistCountries' commandButton :<af:commandButton actionListener="#{bindings.persistCountries.execute}" text="persistCountries" action="{controllerContext.currentViewPort.taskFlowContext.trainModel.getNext}" disabled="#{!bindings.persistCountries.enabled}" id="cb1"/> Open location.jsff & drop countriesFindAll->locationsList as ADF Master Form Detail Table on the above page Fragment.Drop countriesFindAll->locationsList->Operations->Create as ADF button .And drop mergeLocations(Locations)method from EJB datacontrol as ADF Button 'mergeLocations' to merge the dataAgain this mergeLocations button should have action="#{controllerContext.currentViewPort.taskFlowContext.trainModel.getNext}" to navigate to next train stepOpen department.jsff & drop countriesFindAll->locationsList->departmentsList as ADF Master Form ,Detail Table on the above page Fragment .Drop countriesFindAll->locationsList->departmentsList ->Operations->Create as ADF button .And drop mergeDepartments(Departments)method from EJB datacontrol as ADF Button'mergeDepartments' to merge the dataNow we will create a train.jspx page & drop the above created ADF Task Flow as region on this pageRun this page,it shows train with 3 steps & these train steps allow us to create master->Detail->Detail records

This article describes the creation of master detail detail records using EJB Datacontrol.This is done using ADF Train component.Use Case DescriptionLets us consider that we...

ADF

Contextual events with EJB DC

This article describes contextual events with EJB DatacontrolUse Case DescriptionLet us consider a scenario wherein the user wants to display deptno list & commandButton in region1 & region2 displays the Emp records corresponding to selected deptno in region1.We will try to achieve this using contextual events.When the user selects deptno & clicks on the commandButton ,a contextual event with payLoad parameter is broadcasted by taskflow1.This event is then consumed by the  taskflow2 and the handleEvent() handler passes payLoad parameter(i.e deptno) to sessionBean.SessionBean has findByDeptno() method that returns the Emp records & taskflow2 displays the respective Emp records .Implementation stepsLet us suppose that we have created Java EE Web Application with Entities from Emp & Dept table .Also add 'ADF Faces Components 11' under ViewController->project properties-> JSP Tag Libraries.Edit Emp.java & create a custom named query that returns Emp Object for the respective deptno : @NamedQuery(name = "findEmpByDeptno", query = "select o from Emp o  where o.dept.deptno = :deptNo")Let us create Stateful Session Bean and expose the Named Query through the Session Facade.Create a contextual handle event that passes deptno as payload parameter:    public void handleEvent(Object payload)     {           this.setDepartNo((BigDecimal)payload);    }Modify findEmpByDeptno namedQuery as below: public List<Emp> findEmpByDeptno() {   return em.createNamedQuery("findEmpByDeptno").setParameter ("deptNo",  this.getDepartNo()).getResultList();}Generate Data control for the above Session Bean & expose the above method through the Session Facade. Create a ADF taskflow1 with page Fragments & drop  view activity(DeptView) on that.In the same taskflow drop Execute operation((findByDeptno()->Emp->Operations->Execute).Define control flow case 'execute' from DeptView to Execute operation in taskflow.Drop deptno as selectOneChoice & commandButton 'showEmpRecords' on the DeptView page Fragment page.Set showEmpRecords action property  as 'execute'In its page definition create deptno attribute value that points to deptFindAllIterator &  handler event method action binding to handle the event:               Select commandButton 'showEmpRecords' & create new contextual event on that:Now we will create new Event subscriber in its contextual events binding editor tab:Create taskflow2 that displays Emp table(findByDeptno()->Emp) & create main.jspx page,drop both the taskflows as regionRun the page & now if user selects deptno,table below shows Emp records corresponding to the selected deptno.

This article describes contextual events with EJB DatacontrolUse Case DescriptionLet us consider a scenario wherein the user wants to display deptno list & commandButton in region1 & region2 displays...

EJB

AutoSuggest behavior In ADF Using EJB

AutoSuggest feature somewhat expected feature, nowadays that most of the top sites have implemented this functionality. This feature makes your site as user friendly and easy to navigate in inputText feature.AutoSuggest behavior in ADF adds a pull-down menu of suggested values to a text field. The user can either click directly on a suggestion to enter it into the field, or navigate the list using the up and down arrow keys, selecting a value using the enter key.Lets create a Java EE Web Application with Entities based on Departments, edit the Departments.java entity and add the below code.@NamedQuery(name = "Departments.filteredValues", query = "select o from Departments o where o.departmentName like CONCAT(:deptName,'%')Create a Stateless Session Bean and data control for the Stateless Session Bean. Add the below code to the session bean and expose the method in local/remote interface and generate a data control for that.Note:- Here in the below code "em" is a EntityManager./** select o from Departments o where o.departmentName like CONCAT(:deptName,'%') */public List<String> getDepartmentsFilteredValues(String deptName) { //To store the resultset List<String> deptNameResultset = new ArrayList<String>(); Query query = em.createNamedQuery("Departments.filteredValues").setParameter("deptName", deptName); Vector result = (Vector)query.getResultList(); int resultSize = result.size(); for (int i = 0; i > resultSize; i++) { Departments dept = (Departments)result.get(i); deptNameResultset.add(dept.getDepartmentName()); } return deptNameResultset;}In the ViewController create a file AutoSuggest.jspx page, from component palette drag and drop <af:inputText/> and in PI palette change the label to Dept Name. Add the autoSuggestBehavior tag to the inputText. Click on the autoSuggestBehavior, in  PI palette click on Edit property for Suggested Items and create a "AutoSuggest" managed bean with scope as "request" as shown in below Image.Create new method as deptNameResultList and click ok.In AutoSuggest.jspx page, go to binding tab and click create binding by selecting methodAction and click ok with parameter blank as shown in below image Open AutoSuggest.java managed bean and paste the below code.public List deptNameResultList(String paramValue) { //Store the deptName result set List<SelectItem> deptResultList = new ArrayList<SelectItem>(); //Filter the values using Items List List<SelectItem> items = new ArrayList<SelectItem>(); BindingContainer bindings = getBindings(); //Execute the Method OperationBinding operationBinding = bindings.getOperationBinding("getDepartmentsFilteredValues"); //Populate the deptName parameter operationBinding.getParamsMap().put("deptName", paramValue); operationBinding.execute(); if (operationBinding.getResult() != null) { operationBinding.getResult(); ArrayList result = (ArrayList)operationBinding.getResult(); int resultSize = result.size(); for (int i = 0; i < resultSize; i++) { deptResultList.add(new SelectItem(result.get(i))); } } for (SelectItem item : deptResultList) { if (item.getLabel().startsWith(paramValue)) { items.add(item); } } return items;}public BindingContainer getBindings() { return BindingContext.getCurrent().getCurrentBindingsEntry();}Run AutoSuggest.jspx, Dept Name text field will be displayed. As soon as the user has typed a character, a filtered list of suggested values is presented( for ex: C), Now traverse the list by using up and down arrow and select a suggested value from the list and thus applying that value to the inputText component. 

AutoSuggest feature somewhat expected feature, nowadays that most of the top sites have implemented this functionality. This feature makes your site as user friendly and easy to navigate in inputText...

Faces

Paritally restricting user entry in the ADF input text - using Java Script

Recently came across a forum post in which the OP wanted to let the users edit the content of the text field partially. https://forums.oracle.com/forums/thread.jspa?forumID=83&threadID=2259832Here is an example. Let us assume the input text contains the following text. "You can edit the content inside { this }". In this, users should be able to edit only the content inside { }. I.e Only "this" should be editable. To achieve this, we can use a java script method, that tracks the cursor position and ignore the user edits if the cursor position is not between the curly braces. After which, the method would be used in the client listener for the input text.Example code snippet.<af:inputText label="Partial Editable Text Item" id="it1" value="You can edit the content inside { this }" clientComponent="true" ><af:clientListener type="keyPress" method="validateValue" /> </af:inputText><af:resource type="javascript"> function validateValue(evt){ var inputTxt=document.getElementById('it1::content'); var startPos = inputTxt.value.indexOf("{"); var endPos = inputTxt.value.indexOf("}"); var cursorPos = inputTxt.selectionStart; if (cursorPos &lt; startPos+2 || cursorPos > endPos-1) { alert("Cannot Edit"); evt.cancel(); } }</af:resource>More complex example by Frank Nimphius http://blogs.oracle.com/jdevotnharvest/entry/get_social_security_numbers_rightNote : Tested the above snippet successfully in Mozilla Firefox and IE 9.

Recently came across a forum post in which the OP wanted to let the users edit the content of the text field partially. https://forums.oracle.com/forums/thread.jspa?forumID=83&threadID=2259832 Here is...

ADF

Creating Matrix Report using ADF Pivot Table

Matrix Report can be achieved using ADF Pivot Table, we have to set drill down parameters to have hierarchical view in the report. Data Aggregation option allows us to use mathematical operations like Sum, Average, Count, Maximum, Minimum, Standard Deviation, and Variance on data.This article shows how to create a Drill down Matrix Report with Department wise Total Salary using ADF Pivot Table.Create Business Components from DEPARTMENTS and EMPLOYEES tables of HR schema.Drop EmployeesView1 from Data Control Palette to jspx page as ADF Pivot Table.In Select display attributes panel first drop DepartmentId from 'Available Attributes' list to 'Row and Columns edges', drop EmployeeId below DepartmentId in 'Row and Columns edges'.  From 'Available Attributes' list drop FirstName, LastName, Salary, JobId to 'Data Labels' section. In 'Configure drilling' panel select 'Insert Drilling' option, Set 'Insert Parent Row' as 'After Children'. Check enable Drill Path for Drill Down report. Drilling option gives a Tree structure for the selected Attributes. Drill Paths are derived from the Attributes dropped in 'Row and Column Edges' In Select display attributes panel.Add 'Salary' attribute to configure Data Aggregation.Select 'Category Totals' tab and add Categories Attribute as 'DepartmentId' and 'Insert Total' as 'After'.Configure sorting categories based on DepartmentId attribute in ascending order.Finish the wizard and run the page.Expand DepartmentId to find the Employees, also note the Department wise Salary and Total Salary.

Matrix Report can be achieved using ADF Pivot Table, we have to set drill down parameters to have hierarchical view in the report. Data Aggregation option allows us to use mathematical operations...

ADF

Passing parameter to EJB Method in taskflow

This article describes on passing parameter to EJB Method in taskflow. Use Case DescriptionSuppose we have a table displaying Dept records.Table also has column link & clicking on this link displays a region in popup.This region accepts deptno parameter,executes EJB Method & displays respective Emp details in a popup.Implementation stepsLet us suppose that we have created Java EE Web Application with Entities from Emp & Dept table .Also add 'ADF Faces Components 11' under ViewController->project properties-> JSP Tag Libraries.Edit Emp.java & create a custom named query that returns Emp Object for the respective deptno : @NamedQuery(name = "findEmpByDeptno", query = "select o from Emp o  where o.dept.deptno = :deptNo")Let us create Stateful Session Bean and expose the Named Query through the Session Facade.Our use case deals with passing parameters to EJB method in taskflow.So we will define simple EJB method that just accepts deptno parameter & stores its value in private variable:    public void passDeptno(BigDecimal deptNo)  { this.setDepartNo(deptNo); }Now that we have separate method to accept parameter we will modify findEmpByDeptno namedQuery as below: public List<Emp> findEmpByDeptno() {   return em.createNamedQuery("findEmpByDeptno").setParameter ("deptNo", this.getDepartNo()).getResultList();}Generate Data control for the above Session Bean & expose the above method through the Session Facade. Create a ADF taskflow with page Fragments & create an inputParameter 'inputParameter1' in its overview parameters tab:Drop passDeptno(BigDecimal) as Method Call activity with value as #{pageFlowScope.inputParameter1}.Drop findEmpByDeptno()->Operations->execute operation as Method Call activity & then drop  emp view activity on the taskflow.Define all control flows. Create emp.jsff page fragment & drop findEmpByDeptno()->Emp as ADF Table with single row selectionNow we will create main.jspx page & drop deptFindAll as ADF table with single row selection on this.We will also create deptno attribute bindings in page definition file:Insert a new column inside the table that displays Emp Details.Drop the above created taskflow as region inside the column.Pass '#{sessionScope.deptno}' value for inputParameter1 & set the taskflow's ifNedded property to 'Refresh'.Here we are using setPropertyListener to pass parameter to taskflow method:<af:column id="c4" headerText="Emp details"> <af:commandLink text="Emp details" id="cl1"> <af:showPopupBehavior popupId="p1"/> </af:commandLink> <af:popup id="p1" contentDelivery="lazyUncached"><af:dialog id="d2" title="Emp Details" type="none"> <af:region value="#{bindings.taskflowdefinition1.regionModel}" id="r1"/></af:dialog> <af:setPropertyListener type="popupFetch" from="#{bindings.deptno.inputValue}" to="#{sessionScope.deptno}"/> </af:popup></af:column>Run the page,it shows Dept records.Select any dept record & click on 'Emp Details' link.It shows popup with its respective Emp records

This article describes on passing parameter to EJB Method in taskflow.Use Case DescriptionSuppose we have a table displaying Dept records.Table also has column link & clicking on this link displays a...

EJB

Custom Table Pagination Using EJB Native Query

Let us take scenario where the table has more records. Here employees table has more number of records, if the entire records are displayed in single ADF table, It will be difficult for user to navigate or traverse to the exact record. This can be achieved by implementing pagination, Pagination is an important aspect when displaying large number of records. This blog would be of help if you are building applications that render large number of records in a table. With pagination, the number of records displayed can be controlled into several manageable chunks, thus making it easy to locate the records of interest.Model Diagram:Here in the above model diagram, Employees table schema.Let us consider the above Employees table has more number of records, User will not be able to see all the records at the same time on web page. For ex:- Employees Details PageWe use the af:iterator tag to implement the custom table with pagination. This tag renders a collection in the same fashion as the af:table tag does. Same as af:table tag, af:iterator can be based on table binding available in page definition. It iterates over data collection and renders data rows. First, create entities based on  Employees, then create a stateless session bean and data control for the session bean. Add the below code to the session bean and expose the method in local/remote interface and generate a data control for that.Note:- Here in the below code "em" is a EntityManager. /** * Returns list of employee list starting at the given first index with the given max row count. * @return list of employee list starting at the given first index with the given max row count. */ public List<Employees> employeesByLimit(int firstRow, int maxRow) { String queryString = "select * from Employees order by employee_id ASC"; return em.createNativeQuery(queryString, Employees.class).setMaxResults(maxRow).setFirstResult(firstRow).getResultList(); } /** * Returns total amount of rows in table. * @return Total amount of rows in table. */ public int employeesTotalRows() { String queryString = "select * from Employees order by employee_id ASC"; Query query = em.createNativeQuery(queryString); List results = query.getResultList(); return results.size(); }In the ViewController create a file CustomPagination.jspx page, right click and "Go to Page Definition", CustomPaginationPageDef.xml file will be created.  Create a CustomPagination managed bean with scope as "sessionScope" add the below code: private int firstRow = 0; private int rowsPerPage = 10; private int totalRows; private int totalPages; private int currentPage = 1; public CustomPagination() { this.loadList(); } public void loadList() { /** * Returns total amount of rows in table. * @return Total amount of rows in table. */ BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry(); AttributeBinding attr = (AttributeBinding)bindings.getControlBinding("EmployeesTotalRowCount"); String val = attr.getInputValue().toString(); int rows = Integer.parseInt(val); this.setTotalRows(rows); double val1 = ((double)this.getTotalRows() / this.getRowsPerPage()); int totalPagesCal = (int)Math.ceil(val1); this.setTotalPages((totalPagesCal != 0) ? totalPagesCal : 1); } public void firstActionListener(ActionEvent actionEvent) { this.setCurrentPage(1); this.setFirstRow(0); } public void previousActionListener(ActionEvent actionEvent) { this.setCurrentPage(this.getCurrentPage() - 1); this.setFirstRow(this.getFirstRow() - this.getRowsPerPage()); } public void nextActionListener(ActionEvent actionEvent) { this.setCurrentPage(this.getCurrentPage() + 1); this.setFirstRow(this.getFirstRow() + this.getRowsPerPage()); } public void lastActionListener(ActionEvent actionEvent) { this.setCurrentPage(this.getTotalPages()); this.setFirstRow(this.getTotalRows() - ((this.getTotalRows() % this.getRowsPerPage() != 0) ? this.getTotalRows() % this.getRowsPerPage() : this.getRowsPerPage())); } public boolean isBeforeDisabled() { return this.getFirstRow() == 0; } public boolean isAfterDisabled() { return this.getFirstRow() >= this.getTotalRows() - this.getRowsPerPage(); } public void setFirstRow(int firstRow) { this.firstRow = firstRow; } public int getFirstRow() { return firstRow; } public void setRowsPerPage(int rowsPerPage) { this.rowsPerPage = rowsPerPage; } public int getRowsPerPage() { return rowsPerPage; } public void setTotalRows(int totalRows) { this.totalRows = totalRows; } public int getTotalRows() { return totalRows; } public void setTotalPages(int totalPages) { this.totalPages = totalPages; } public int getTotalPages() { return totalPages; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getCurrentPage() { return currentPage; }Open CustomPagination.jspx, click on Binding tab and and click on Create control binding and select methodAction for employeesTotalRows as shown in below image.Open CustomPaginationPageDef.xml and add the below code snippet inside "variableIterator" tag. <variable Type="int" Name="employeesTotalRows_Return" IsQueriable="false" IsUpdateable="0" DefaultValue="${bindings.employeesTotalRows.result}"/>Open CustomPagination.jspx,  click on Binding tab and click on Create control binding and select attributeValues and create attribute binding for employeesTotalRows_Return and in Property Inspector change the id to "EmployeesTotalRowCount" Click on Create control binding and select methodAction for employeesByLimit as shown in below imageCreate Tree binding for control of Employees result set.Click on Create Executable binding and select Invoke action and follow as shown in below image.Edit TotalRows invoke actiion and set the Refresh to prepareModel, so when ever page loads employeesTotalRows method will get executed.Go to CustomPagination.jspx Source tab and copy the below code snippet. As mentioned above af:iterator tag to implement the custom table with pagination.<af:group id="g1"><af:panelGroupLayout id="pgl1" layout="scroll"><af:spacer width="10" height="10" id="s16"/><af:panelGroupLayout id="pgl9" layout="horizontal"><af:spacer width="10" height="10" id="s9"/><af:panelGroupLayout id="pgl10" inlineStyle="width:75px;" layout="horizontal"><af:outputText value="Employeed Id" id="ot1" inlineStyle="font-weight:bold;"/></af:panelGroupLayout><af:spacer width="10" height="10" id="s7"/><af:panelGroupLayout id="pgl7" inlineStyle="width:75px;" layout="horizontal"><af:outputText value="First Name" id="ot6" inlineStyle="font-weight:bold;"/></af:panelGroupLayout><af:spacer width="10" height="10" id="s10"/><af:panelGroupLayout id="pgl11" inlineStyle="width:75px;" layout="horizontal"><af:outputText value="Last Name" id="ot4" inlineStyle="font-weight:bold;"/></af:panelGroupLayout><af:spacer width="10" height="10" id="s11"/><af:panelGroupLayout id="pgl12" inlineStyle="width:75px;" layout="horizontal"><af:outputText value="Email" id="ot7" inlineStyle="font-weight:bold;"/></af:panelGroupLayout><af:spacer width="10" height="10" id="s12"/><af:panelGroupLayout id="pgl15" inlineStyle="width:75px;" layout="horizontal"><af:outputText value="Salary" id="ot10" inlineStyle="font-weight:bold;"/></af:panelGroupLayout></af:panelGroupLayout><af:separator id="s15"/><af:spacer width="10" height="10" id="s2"/><af:iterator id="i1" value="#{bindings.result.collectionModel}" var="row"><af:panelGroupLayout id="pgl2" layout="horizontal"><af:spacer width="10" height="10" id="s3"/><af:panelGroupLayout id="pgl3" layout="horizontal" inlineStyle="width:75px;"><af:outputText value="#{row.employeeId}" id="ot8"/></af:panelGroupLayout><af:spacer width="10" height="10" id="s13"/><af:panelGroupLayout id="pgl13" layout="horizontal" inlineStyle="width:75px;"><af:outputText value="#{row.firstName}" id="ot11"/></af:panelGroupLayout><af:spacer width="10" height="10" id="s4"/><af:panelGroupLayout id="pgl4" layout="horizontal" inlineStyle="width:75px;"><af:outputText value="#{row.lastName}" id="ot9"/></af:panelGroupLayout><af:spacer width="10" height="10" id="s6"/><af:panelGroupLayout id="pgl5" layout="horizontal" inlineStyle="width:75px;"><af:outputText value="#{row.email}" id="ot2"/></af:panelGroupLayout><af:spacer width="10" height="10" id="s8"/><af:panelGroupLayout id="pgl8" inlineStyle="width:75px;" layout="horizontal"><af:outputText value="#{row.salary}" id="ot3"/></af:panelGroupLayout></af:panelGroupLayout><af:spacer width="10" height="10" id="s1"/></af:iterator><af:panelGroupLayout id="pgl6"><af:commandButton text="First" id="cb1" actionListener="#{CustomPagination.firstActionListener}" partialTriggers="i1" disabled="#{CustomPagination.beforeDisabled}"/><af:commandButton text="Prev" id="cb2" actionListener="#{CustomPagination.previousActionListener}" partialTriggers="i1" disabled="#{CustomPagination.beforeDisabled}"/><af:commandButton text="Next" id="cb3" actionListener="#{CustomPagination.nextActionListener}" partialTriggers="i1" disabled="#{CustomPagination.afterDisabled}"/><af:commandButton text="Last" id="cb4" actionListener="#{CustomPagination.lastActionListener}" partialTriggers="i1" disabled="#{CustomPagination.afterDisabled}"/><af:spacer width="10" height="10" id="s5"/><af:outputText value="Page #{CustomPagination.currentPage} / #{CustomPagination.totalPages}" id="ot5"/></af:panelGroupLayout></af:panelGroupLayout></af:group>Run the CustomPagination.jspx, Now It always displays 10 rows (configurable) in the CustomPagination.java page. The page provides buttons to navigate between pages and shows current page number. If user is moves to second or third page, navigation buttons for previous page will be enabled, If we navigate to the last page, navigation buttons for next navigation become disabled and If we navigate to the first page, First and Prev buttons should be disabled.

Let us take scenario where the table has more records. Here employees table has more number of records, if the entire records are displayed in single ADFtable, It will be difficult for user to...

EJB

Using Message-Driven Bean and JMS Queue with ADF

EJB3.0 Message-Driven Bean asynchronously listens to JMS Queue/Topic and processes the messages from its clients.In this article we will see how Message-Driven Bean listens to JMS Queue and process the message sent to Queue by a client, here I will be using ADF jspx page as our client.This article will be split into two Sections. First Section, is for creating JMS Queue from WLS console, this is to help those who are not familiar in managing JMS from WLS console. Second Section, shows how to send a message from ADF client (jspx page) to JMS Queue and how to make Message-Driven Bean listen to the JMS Queue. Section 1: Creating JMS Queue from WLS consoleYou need to have Integrated or Standalone WLS instance up and running.FileSystem type Persistence Store has to be created to store JMS messages.JMS Server is required to manage JMS Queues targeted at it.Use File Store create above as Persistence Store.Set 'DefaultServer' (for Integrated WLS) or 'AdminServer' (for Standalone WLS) as its Target Server.JMS System Module is required to hold the queues.Target JMS Module to server on which JMS Server is target.Check 'Would you like to add resources to this JMS system module' to include JMS queue to this newly created JMS Module.Create Sub Deployment and target it to JMS Server.Under Configurations tab click New button to create Connection Factories, Queues resources.Create JMS Connection Factory.Now Target the Connection Factory to Sub Deployment created above.Similarly create a Queue and target it to Sub Deployment.With this we have configured WLS to handle JMS Queue.Section 2: Send message from ADF client to JMS Queue and use Message-Driven Bean listen to the JMS Queue.In a Custom Application Create Message-Driven BeanonMessage() of Message-Driven Bean is called by container when it receives message from a client.onMessage() has to be modified accordingly to process the received message.public void onMessage(Message message) { try{ String sub= message.getStringProperty("subject"); String mess= message.getStringProperty("message"); System.out.println("Subject = " + sub); System.out.println("Message = " + mess); } catch(Exception e){ e.printStackTrace(); }}Create jspx page in View Controller project.Drop two Input Texts from component palette to jspx page for Subject and Message.Drop Command Button from component palette to jspx page.Bind Subject, Message input text to backing bean.Create Action binding for send command button.Add below code to send message to JMS queue.QueueConnectionFactory connectionFactory;try { connectionFactory = (QueueConnectionFactory)new InitialContext().lookup("jms.MDBConnectionFactory1"); QueueConnection connection = connectionFactory.createQueueConnection(); connection.start(); QueueSession queueSession = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = (Queue)new InitialContext().lookup("weblogic.wsee.DefaultQueue"); QueueSender queueSender = queueSession.createSender(queue); Message message = queueSession.createMessage(); message.setJMSType("logMessage"); message.setLongProperty("time", System.currentTimeMillis()); message.setStringProperty("subject", this.getIt1().getValue().toString()); message.setStringProperty("message", this.getIt2().getValue().toString()); queueSender.send(message); queueSession.close(); connection.close();} catch (Exception e) { e.printStackTrace();}Run jspx pageGive values to  Subject, Message and hit Send button.onMessage() reads this message prints as Server Log.

EJB3.0 Message-Driven Bean asynchronously listens to JMS Queue/Topic and processes the messages from its clients.In this article we will see how Message-Driven Bean listens to JMS Queue and process...

EJB

Call DB Stored Procedure using @NamedStoredProcedureQuery Injection

Oracle Database Stored Procedure can be called from EJB business layer to perform complex DB specific operations. This approach will avoid overhead from frequent network hits which could impact end-user result. DB Stored Procedure can be invoked from EJB Session Bean business logic using org.eclipse.persistence.queries.StoredProcedureCall API. Using this approach requires more coding to handle the Session and Arguments of the Stored Procedure, thereby increasing effort on maintenance. EJB 3.0 introduces @NamedStoredProcedureQuery Injection to call Database Stored Procedure as NamedQueries. This blog will take you through the steps to call Oracle Database Stored Procedure using @NamedStoredProcedureQuery.EMP_SAL_INCREMENT procedure available in HR schema will be used in this sample.Create Entity from EMPLOYEES table.Add @NamedStoredProcedureQuery above @NamedQueries to Employees.java with definition as given below -@NamedStoredProcedureQuery(name="Employees.increaseEmpSal", procedureName = "EMP_SAL_INCREMENT", resultClass=void.class, resultSetMapping = "", returnsResultSet = false, parameters = { @StoredProcedureParameter(name = "EMP_ID", queryParameter = "EMPID"), @StoredProcedureParameter(name = "SAL_INCR", queryParameter = "SALINCR")})Observe how Stored Procedure's arguments are handled easily in  @NamedStoredProcedureQuery using @StoredProcedureParameter.Expose Entity Bean by creating a Session Facade.Business method need to be added to Session Bean to access the Stored Procedure exposed as NamedQuery. public void salaryRaise(Long empId, Long salIncrease) throws Exception { try{ Query query = em.createNamedQuery("Employees.increaseEmpSal"); query.setParameter("EMPID", empId); query.setParameter("SALINCR", salIncrease); query.executeUpdate(); } catch(Exception ex){ throw ex; } }Expose business method through Session Bean Remote Interface.void salaryRaise(Long empId, Long salIncrease) throws Exception;Session Bean Client is required to invoke the method exposed through remote interface.Call exposed method in Session Bean Client main method. final Context context = getInitialContext(); SessionEJB sessionEJB = (SessionEJB)context.lookup("Your-JNDI-lookup");sessionEJB.salaryRaise(new Long(200), new Long(1000));Deploy Session BeanRun Session Bean Client.Salary of Employee with Id 200 will be increased by 1000.

Oracle Database Stored Procedure can be called from EJB business layer to perform complex DB specific operations. This approach will avoid overhead from frequent network hits which could...

Webservices

Database Web Service using Toplink DB Provider

With JDeveloper 11gR2 you can now create database based web services using JAX-WS Provider. The key differences between this and the already existing PL/SQL Web Services support is:Based on JAX-WS ProviderSupports SQL Queries for creating Web ServicesSupports Table CRUD OperationsThis is present as a new option in the New Gallery under 'Web Services'When you invoke the New Gallery option, it present you with three options to choose from:In this entry I will explain the options of creating service based on SQL queries and Table CRUD operations.SQL Query based Service When you select this option, on 'Next' page it asks you for the DB Conn details. You can also choose if you want SOAP 1.1 or 1.2 format. For this example, I will proceed with SOAP 1.1, the default option.On the Next page, you can give the SQL query. The wizard support Bind Variables, so you can parametrize your queries. Give "?" as a input parameter you want to give at runtime, and the "Bind Variables" button will get enabled. Here you can specify the name and type of the variable.Finish the wizard. Now you can test your service in Analyzer:See that the bind variable specified comes as a input parameter in the Analyzer Input Form:CRUD OperationsFor this, At Step 2 of Wizard, select the radio button "Generate Table CRUD Service Provider"At the next step, select the DB Connection and the table for which you want to generate the default set of operations:Finish the Wizard. Now, run the service in Analyzer for a quick check.See that all the basic operations are exposed:

With JDeveloper 11gR2 you can now create database based web services using JAX-WS Provider. The key differences between this and the already existing PL/SQL Web Services support is:Based on JAX-WS...

BC4J

How to call a method defined in AppmoduleImpl using groovy expression?

Usecase Description:Suppose we have a Transient attribute that stores the value returned by an Appmodule method,then the easy way to call this method in transient attribute would be using Groovy expression.Consider a simple method in AppmoduleImpl java class that returns the Department name of the selected row of Emp table: public String getDeptName(Number dno)    {        if (dno == null)            return null;        else {            ViewObject vo = findViewObject("DeptView1");            try {                Row row =                    vo.findByKey(new Key(new Object[] { new oracle.jbo.domain.Number(dno) }),                                 1)[0];                if (row != null) {                    Object name = row.getAttribute("Dname");                    if (name != null)                        return name.toString();                    else                        return null;                } else                    return "Specified dept does not exists";            } catch (Exception e) {                e.printStackTrace();                return null;            }        }    }Create an Updatable Transient attribute in EmpView Object.Edit its value & provide a groovy expression "adf.object.applicationModule.getDeptName(Deptno)" to call the above methodRun the AppModule & note that the transient attribute returns the Department name corresponding to the selected row of Emp table.

Usecase Description:Suppose we have a Transient attribute that stores the value returned by an Appmodule method,then the easy way to call this method in transient attribute would be using...

ADF

Customizing display of components in ADF Libraries

Introduction:ADF Libraries are Java archive files, from which ADF Components like Business Components, Data controls, taskflows etc can be reused. This data however only lists default names of components. This ariticle deals with cuztomizing metadata visibility in ADF Libraries through the  use of resource bundles.   Sample Application:Customizing visibility and component names inside an ADF Library needs two things:A custom Meta-Inf file.A Resource bundle - a .properties file.The following steps illustrate this feature:Create a Fusion Web Application and create ADFBC Components based on Dept and Emp tables in the model,Create a View controller with a bounded taskflow, with 2 view objects - Dept and Emp. Define control flow scope, and create page fragments out of them. Create an ADF Library deployment profile in the View Controller project.In the View Controller project create a .properties file - LibraryBundle.properties..name=Friendly jar name.description=Friendly long description of the jar.tooltip=This is the tooltip text to display on mouse hover.helptopic=alternateHelpSystemTopicIdADF_DataControl|model/AppModule.xml.name=Friendly BC DC name 5. Create a custom metainf file in your local system:Specification-Title: WebCenter ServiceList TaskFlowsSpecification-Version: 11.1.1.0.0Specification-Vendor: Oracle Corp.Implementation-Version: JDEVADF_MAIN_GENERIC_080316.1855.4913Implementation-Vendor: Oracle Corp.Help-Topic: someHelpSystemTopicIdBundle-Classes: LibraryBundle6. Save this as Custommetainf.mf. Create a ADF Library deployment profile.7. Add Custommetainf.mf in the Jar options while creating the deployment profile.8. Deploy the jar, and create a file system connection to it. Open it in the resource palette.Note that both the Jar names, and the Data control names are both displayed with customized names that were defined in the resource bundles.

Introduction:ADF Libraries are Java archive files, from which ADF Components like Business Components, Data controls, taskflows etc can be reused. This data however only lists default names of...

EJB

Native Query using the SQL 'IN' clause

Use-Case Description:Consider a case where we need to retrieve employees where Department and Employees entities are associated by One to Many mapping, the retrieval is using complex queries with a complex result set.Ex: JPQL with "IN clause" where we need to pass series of values in one parameter, say list type. As the Java Persistence Query Language does not support passing a list of items as an input/named parameter, we are limited by the JPQL language to use "IN clause" in named queries. Here is one solution to overcome this limitation, this can be achieved by creating native SQL queries to run complex queries and also handle complex result sets.First, create entities based on Department, Employees, then create a stateless session bean and data control for the session bean. Add the below code to the session bean and expose the method in local/remote interface and generate a data control for that.Note: Parameters in the example below are hard coded.The code below describes one way of creating a native query and defining a result set that can map to an entity. Notice that the result set is mapped to the Employees entity class.Note:- Here in the below code "em" is a EntityManager. public List<Employees> NativeQuery() { String queryString = "select * from Employees where department_id in (10, 20, 40, 50) order by department_id ASC"; return em.createNativeQuery(queryString, Employees.class).getResultList(); }Here is another way of creating a native query using custom code to generate a custom result set. public List<Employees> NativeQueryCustomCode() { String queryString = "select * from Employees where department_id in (10, 20, 40, 50) order by department_id ASC"; Query genericSearchQuery = em.createNativeQuery(queryString, "InQuery"); List resultList = genericSearchQuery.getResultList(); Iterator resultListIterator = resultList.iterator(); List<Employees> employeesList = new ArrayList(); while (resultListIterator.hasNext()) { Object col[] = (Object[])resultListIterator.next(); Employees employees = new Employees(); BigDecimal employeeId = (BigDecimal)col[0]; employees.setEmployeeId(employeeId.longValue()); employees.setFirstName((String)col[1]); employees.setLastName((String)col[2]); employees.setEmail((String)col[3]); employees.setPhoneNumber((String)col[4]); employees.setJobId((String)col[6]); BigDecimal salary = (BigDecimal)col[7]; employees.setSalary(salary.doubleValue()); employees.setCommissionPct((Double)col[8]); Departments departments = new Departments(); BigDecimal departmentId = (BigDecimal)col[10]; departments.setDepartmentId(departmentId.longValue()); employees.setDepartments(departments); employeesList.add(employees); } return employeesList;}In the ViewController create a file NativeQuery.jspx, from the DataControl palette drag and drop NativeQuery->Employees as ADF Read-only Table and select the columns to be displayed.Run NativeQuery.jspx, Employees who belong to the departments with Id (10,20,30,40) should only be displayed. 

Use-Case Description: Consider a case where we need to retrieve employees where Department and Employees entities are associated by One to Manymapping, the retrieval is using complex queries with a...

EJB

Simulating dependent LOV using EJB Native Query

This Use case simulates dependent LOV. Consider a case where we need to retrieve employees where Department and Employees entities are associated by One to Many mapping. Here employees table has more number of records, if the entire records are  displayed in single ADF table. It will be difficult for user to search, Filter or traverse to the exact record.Model Diagram: Employees, Departments table schema.Below Employees details page has more number of records, User will not be able to see all the records at the same time on web page. User has to scroll down to find the exact record.Toolbar filters is one of the solution for navigating to the records, Toolbar filter enables the user to filter the rows in a table. Using toolbar filters performance issues can be improved by reducing result set size while loading the page. We will try to achieve the toolbar filters by simulating dependent LOV using EJb Native Query. From the above Employees Details Page, select the departmentId and jobId as toolbar filters. First, create entities based on Department, Employees, then create a stateless session bean and data control for the session bean. Add the below code to the session bean and expose the method in local/remote interface and generate a data control for that.Note:- Here in the below code "em" is a EntityManager. public List<Employees> EmployeesFilteredResult(Long departmentId, String jobId) { String queryString = null; if (departmentId == null &amp;&amp; jobId == null) { queryString = "select * from Employees where department_id like '%' and job_id like '%'"; } else if (departmentId != null &amp;&amp; jobId == null) { queryString = "select * from Employees where department_id = " + departmentId + " and job_id like '%'"; } else if (departmentId != null &amp;&amp; jobId != null) { queryString = "select * from Employees where department_id = " + departmentId + " and job_id = '" + jobId + "'"; } System.out.println(queryString); Query genericSearchQuery = em.createNativeQuery(queryString, Employees.class); return genericSearchQuery.getResultList();}public List<String> EmployeesDistinctJobByDept(Long departmentId) { List<String> empResultList = new ArrayList<String>(); try { String queryString = "select distinct JOB_ID from Employees where department_id = " + departmentId; System.out.println(queryString); Query genericSearchQuery = em.createNativeQuery(queryString, "DistinctSearch"); List resultList = genericSearchQuery.getResultList(); Iterator resultListIterator = resultList.iterator(); while (resultListIterator.hasNext()) { Object col[] = (Object[])resultListIterator.next(); empResultList.add((String)col[0]); } return empResultList; } catch (NullPointerException npe) { return empResultList; }}In the ViewController create a file DependentLOV.jspx page, from Data Control palette  and drop Panel Collection component, drop ADF toolbar inside the Panel Collection area, drop Panel Group Layout inside ADF toolbar. From DataControl palette drag and drop departmentsFindAll->Single Selection as ADF Select One Choice, In Edit List Binding select departmentName as Display Attribute. Select the departmentName select one choice, In Property Inspector make AutoSubmit: true, edit ValueChangeListener and create a DependentLOV.java managed bean with scope as "sessionScope"and create new method "selectedDeptIdValue", Open DependentLOV.java and paste the below code. private String deptIdValue; private String JobIdValue; public void setDeptIdValue(String deptIdValue) { this.deptIdValue = deptIdValue; } public String getDeptIdValue() { return deptIdValue; } public void setJobIdValue(String JobIdValue) { this.JobIdValue = JobIdValue; } public String getJobIdValue() { return JobIdValue; }Right click on DependentLOV.jspx go to page definition. Create control binding by selecting attributeValues in Insert Item dialog window.From DataControl palette drag and drop EmployeesDistinctJobByDept->return->element as Single Selection->ADF Select One Choice inside ADF toolbar, In Edit Action Binding select the parameter value as #{DependentLOV.deptIdValue}Select the jobId select one choice, In Property Inspector make AutoSubmit: true and set partialTriggers to departmentName select one choice . Edit ValueChangeListener and create a new method "selectedJobIdValue".From DataControl palette drag and drop EmployeesFilteredResult->Employees as Table->ADF Read-only Table and select the columns to be displayed. In Edit Action Binding select the parameter as below Select the employee table, In Property Inspector set partialTriggers to both departmentName and jobId select one choice. Open DependentLOV.java and overwrite the below code.public void selectedDeptIdValue(ValueChangeEvent valueChangeEvent) { Integer stateIndex = (Integer)valueChangeEvent.getNewValue(); BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry(); JUCtrlListBinding listBinding = (JUCtrlListBinding)bindings.get("departmentsFindAll"); Object assignedId = null; if (listBinding != null) { assignedId = listBinding.getDCIteratorBinding().getRowAtRangeIndex(stateIndex.intValue()).getAttribute("departmentId"); Long deptId = Long.parseLong(assignedId.toString()); this.setDeptIdValue(deptId); } OperationBinding operationBinding = bindings.getOperationBinding("EmployeesDistinctJobByDept"); Object result = operationBinding.execute(); this.setJobIdValue(null); } public void selectedJobIdValue(ValueChangeEvent valueChangeEvent) { Integer stateIndex = (Integer)valueChangeEvent.getNewValue(); DCBindingContainer bindings = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry(); DCIteratorBinding tableIter = bindings.findIteratorBinding("EmployeesDistinctJobByDeptIter"); RowSetIterator tableRowSetIter = tableIter.getRowSetIterator(); Object iterRow = null; iterRow = tableRowSetIter.getRowAtRangeIndex(stateIndex.intValue()).getAttribute("element"); this.setJobIdValue(iterRow.toString());} Run the DependentLOV.jspx and select the Dept Name from Dept selection box. JobId selection box will be updated with JobId's associated with Dept Name and Employees table will be refreshed with records for the selected Dept Name. On select of both dept name and job id table will be refreshed with the respective records.

This Use case simulates dependent LOV.Consider a case where we need to retrieve employees where Department and Employees entities are associated by One to Many mapping. Here employees table has more...

ADF

WSDC - DT in RT

One of new features for adapter data controls  introduced in 11.1.1.4.0 is this feature of performing the DT operations at RT.This feature is enabled by exposing few api in the DCAdapterFactory. In this entry I'll walk through this feature for a basic WSDC.This application has a basic web service in the model which would be used in the RT for creating the WSDC.The backing bean WSDC.java in the ViewController project contains the code for the DC creation :The wsdl and name(DC name ) are bind to the DTView.jspx.The WSDefinition is created by passing the name and wsdl url as parameters.The dc(DataControl) is created using the createDataControl Api of the data control factory(dcf).Thecreated DC must now be available in the DC palette in RT.This is donewith help of MDS where we install the dc and then flush the changes.Oncethis is done control passes to RTView.jspx where we have rendered theDC palette  similar to jdeveloper using a ADF Tree table.The classesunder view.support and view.tree model, reads through elements in theDC and adds  them to the tree table.We can now select the DCfrom this palette and this updates the widget Drop down list box whichwill show all the possible components.Select the required component andclick on insert.This inserts the object to page below.(This operationis similar to DnD in Jdev)The component is added to page using a DOM Parser where the node for the component is added to page source.:Oncethe full page is designed , we can access the created the page and theperform the required action.For the web service in the app ,  drop theadd method as a parameter form and the return as output text.Providevalues for a and b and verify the result.Sample output page :

One of new features for adapter data controls  introduced in 11.1.1.4.0 is this feature of performing the DT operations at RT. This feature is enabled by exposing few api in the DCAdapterFactory.In...

EJB

Alphabet filter in ADF Faces table toolbar using EJB NamedQuery

Let us take scenario where the table has more records. It will be difficult for user to search or travel to the exact record.Model Diagram:Here in the above model diagram, Employees table schema.Let us assume the above Employees table has more records, User will not be able to see all the records at the same time on web page. For ex:- Employees Details Page Here In the above scenario, It will be difficult to search for the required records. Suppose if the records starts with alphabet "W" then user as to select scroll till the end page. Performance issues can be improved using using alphabet, and other toolbar filters by reducing result set size while loading the page. Alphabet filters will be one of the solution for navigating to the records. Create a Entity based on Employees table and add one named query, create a session bean and data control for that.@NamedQuery(name = "Employees.filterByAlphabet",query = "select o from Employees o where o.email like CONCAT(:email,'%')")Create a FilterByAlphabet.jspx page and drop the getEmployeesFilterByAlphabet->result DC as Table->ADF Read Only Table with email column sort option enabled. Surround the employee table with panel collection and toolbar with inside the panel. Add the below code inside the toolbar. <af:commandLink text="All" id="cl1" actionListener="#{FilterByAlphabet.getSelectedAlphabet}"/><af:spacer width="15" height="10" id="s1"/><af:commandLink text="A" id="cl2" actionListener="#{FilterByAlphabet.getSelectedAlphabet}"/><af:commandLink text="B" id="cl3" actionListener="#{FilterByAlphabet.getSelectedAlphabet}"/><af:commandLink text="C" id="cl4" actionListener="#{FilterByAlphabet.getSelectedAlphabet}"/><af:commandLink text="D" id="cl5" actionListener="#{FilterByAlphabet.getSelectedAlphabet}"/><af:commandLink text="E" id="cl6" actionListener="#{FilterByAlphabet.getSelectedAlphabet}"/><af:commandLink text="F" id="cl7" actionListener="#{FilterByAlphabet.getSelectedAlphabet}"/><af:commandLink text="G" id="cl8" actionListener="#{FilterByAlphabet.getSelectedAlphabet}"/><af:commandLink text="H" id="cl9" actionListener="#{FilterByAlphabet.getSelectedAlphabet}"/><af:commandLink text="I" id="cl10" actionListener="#{FilterByAlphabet.getSelectedAlphabet}"/><af:commandLink text="J" id="cl11" actionListener="#{FilterByAlphabet.getSelectedAlphabet}"/><af:commandLink text="K" id="cl12" actionListener="#{FilterByAlphabet.getSelectedAlphabet}"/><af:commandLink text="L" id="cl13" actionListener="#{FilterByAlphabet.getSelectedAlphabet}"/><af:commandLink text="M" id="cl14" actionListener="#{FilterByAlphabet.getSelectedAlphabet}"/><af:commandLink text="N" id="cl15" actionListener="#{FilterByAlphabet.getSelectedAlphabet}"/><af:commandLink text="O" id="cl16" actionListener="#{FilterByAlphabet.getSelectedAlphabet}"/><af:commandLink text="P" id="cl27" actionListener="#{FilterByAlphabet.getSelectedAlphabet}"/><af:commandLink text="Q" id="cl28" actionListener="#{FilterByAlphabet.getSelectedAlphabet}"/><af:commandLink text="R" id="cl29" actionListener="#{FilterByAlphabet.getSelectedAlphabet}"/><af:commandLink text="S" id="cl30" actionListener="#{FilterByAlphabet.getSelectedAlphabet}"/><af:commandLink text="T" id="cl31" actionListener="#{FilterByAlphabet.getSelectedAlphabet}"/><af:commandLink text="U" id="cl32" actionListener="#{FilterByAlphabet.getSelectedAlphabet}"/><af:commandLink text="V" id="cl33" actionListener="#{FilterByAlphabet.getSelectedAlphabet}"/><af:commandLink text="W" id="cl34" actionListener="#{FilterByAlphabet.getSelectedAlphabet}"/><af:commandLink text="X" id="cl35" actionListener="#{FilterByAlphabet.getSelectedAlphabet}"/><af:commandLink text="Y" id="cl36" actionListener="#{FilterByAlphabet.getSelectedAlphabet}"/><af:commandLink text="Z" id="cl37" actionListener="#{FilterByAlphabet.getSelectedAlphabet}"/>Create a FilterByAlphabet managed bean with scope as "sessionScope" add the below code :private String filteredValue;public void setFilteredValue(String filteredValue) { this.filteredValue = filteredValue;}public String getFilteredValue() { return filteredValue;}public void getSelectedAlphabet(ActionEvent actionEvent) { RichCommandLink rcl = (RichCommandLink)actionEvent.getComponent(); if (rcl.getText().equals("All")) { this.setFilteredValue(""); } else { this.setFilteredValue(rcl.getText()); }}Go to the page definition and edit the getEmployeesFilterByAlphabet action binding and map the value to #{FilterByAlphabet.filteredValue}Run the FilterByAlphabet.jspx and Selecting a letter adds an <attribute> Starts With condition to the query whose result set is displayed in the table. Clicking the alphabet "A" letter will results the records that starts with "A". So user can filter the records based on alphabet choice.

Let us take scenario where the table has more records. It will be difficult for user to search or travel to the exact record. Model Diagram: Here in the above model diagram, Employees table schema.Let...

Faces

Merge Records in Session bean by using ADF Drag/Drop

This article describes how to merge multiple selected records in Session Bean using ADF drag & drop feature. Below described is simple use case that shows how exactly this can be achieved. Here we will have table & user input field.Table shows  EMP records & user input field accepts Salary.When we drag & drop multiple records on user input field,the selected records get updated with the new Salary provided. Steps: Let us suppose that we have created Java EE Web Application with Entities from Emp table.Then create EJB Session Bean & generate Data control for the same. Write a simple code in sessionEJBBean & expose this method to local interface :  public void updateEmprecords(List empList, Object sal) {       Emp emp = null;       for (int i = 0; i < empList.size(); i++)       {        emp = em.find(Emp.class, empList.get(i));         emp.setSal((BigDecimal)sal);       }      em.merge(emp);   } Now let us create updateEmpRecords.jspx page in viewController project & Drop empFindAll object as ADF Table Define custom SelectionListener method for the table :   public void selectionListener(SelectionEvent selectionEvent)     {     // This method gets the Empno of the selected record & stores in the list object      UIXTable table = (UIXTable)selectionEvent.getComponent();      FacesCtrlHierNodeBinding fcr      =(FacesCtrlHierNodeBinding)table.getSelectedRowData();      Number empNo = (Number)fcr.getAttribute("empno") ;      this.getSelectedRowsList().add(empNo);     }Set table's selectedRowKeys to #{bindings.empFindAll.collectionModel.selectedRow}"Drop inputText on the same jspx page that accepts Salary .Now we would like to drag records from the above table & drop that on the inputtext field.This feature can be achieved by inserting dragSource operation inside the table & dropTraget operation inside the inputText:<af:dragSource discriminant="tab"/> //Insert this inside the table<af:inputText label="Enter Salary" id="it13" autoSubmit="true"       binding="# {test.deptValue}">       <af:dropTarget dropListener="#{test.handleTableDrop}">       <af:dataFlavor        flavorClass="org.apache.myfaces.trinidad.model.RowKeySet"    discriminant="tab"/>       </af:dropTarget>       <af:convertNumber/> </af:inputText> In the above code when the user drags & drops multiple records on inputText,the dropListener method gets called.Goto the respective page definition file & create updateEmprecords method action& execute actiondropListener method code:        public DnDAction handleTableDrop(DropEvent dropEvent)        {          //Below code gets the updateEmprecords method,passes parameters & executes method            DataFlavor<RowKeySet> df = DataFlavor.getDataFlavor(RowKeySet.class);            RowKeySet droppedKeySet = dropEvent.getTransferable().getData(df);            if (droppedKeySet != null && droppedKeySet.size() > 0)           {                  DCBindingContainer bindings =                 (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();                  OperationBinding updateEmp;                  updateEmp= bindings.getOperationBinding("updateEmprecords");                  updateEmp.getParamsMap().put("sal",                  this.getDeptValue().getAttributes().get("value"));                            updateEmp.getParamsMap().put("empList", this.getSelectedRowsList());                  updateEmp.execute(); //Below code performs execute operation to refresh the updated records                 OperationBinding executeBinding;                 executeBinding= bindings.getOperationBinding("Execute");                 executeBinding.execute(); AdfFacesContext.getCurrentInstance().addPartialTarget(dropEvent.getDragComponent());                this.getSelectedRowsList().clear();          }                 return DnDAction.NONE;        }Run updateEmpRecords.jspx page & enter any Salary say '5000'.Select multiple records in table & drop these selected records on the inputText Salary.Note that all the selected records salary value gets updated to 5000.Technorati Tags: ADF Drag and drop,EJB Session bean,ADF table,inputText,DropEvent 

This article describes how to merge multiple selected records in Session Bean using ADF drag & drop feature. Below described is simple use case that shows how exactly this can be achieved. Here we will...

ADF

Adding graph in excel based on the content of ADFdi Table

Often we tend to represent the data present in the table in a graphical format to give a visual impression of the data. This article would be explaining the way to achieve it using the data we have in ADFdi table of the integrated workbook.Pre-requisites:Microsoft Office 2007JDeveloper 11.1.1.1.0 and aboveAssuming we are already having an ADFdi enabled workbook with a table based on an Employee table as shown in the image below.Also, add the table.download to the ribbon toolbar as menu item / as action for the startup event.From excel, we'll add a new 3D bar chartNow, we need to select the data range for the chart. We will take an example of chart based on the salary of the employees. So, the data for the X-Axis of the chart would be the Ename and the data for the Y-Axis being the salary. We can do that by right clicking on the Chart and selecting Select Data. We would select the Legend Entry Series name as the Sal header column in the table, and for the data, we select both the header row and the row below it (by holding Shift key).And, for the Category Axis, we select the Ename header row and the row below it (by holding Shift key).We can get the chart now, by running the Workbook and downloading the data into the table.This simple example can be enhanced for complex graphs by using the data from the ADFdi table to use the power of excel along with ADF Desktop Integration.

Often we tend to represent the data present in the table in a graphical format to give a visual impression of the data. This article would be explaining the way to achieve it using the data we have in...

Toplink

JPA - insert and retrieve clob and blob types

This article describes about the JPA feature for handling clob and blob data types.You will learn the following in this article.@Lob annotationClient code to insert and retrieve the clob/blob typesEnd to End ADFaces application to retrieve the image from database table and display it in web page.Use Case DescriptionPersisting and reading the image from database using JPA clob/blob type.@Lob annotationBy default, TopLink JPA assumes that all persistent data can be represented as typical database data types.Use the @Lob annotation with a basic mapping to specify that a persistent property or field should be persisted as a large object to a database-supported large object type.A Lob may be either a binary or character type. TopLink JPA infers the Lob type from the type of the persistent field or property.For string and character-based types, the default is Clob. In all other cases, the default is Blob.ExampleBelow code shows how to use this annotation to specify that persistent field picture should be persisted as a Blob.public class Person implements Serializable {    @Id    @Column(nullable = false, length = 20)    private String name;    @Column(nullable = false)    @Lob    private byte[] picture;    @Column(nullable = false, length = 20)}Client code to insert and retrieve the clob/blob typesReading a image file and inserting to Database tableBelow client code will read the image from a file and persist to Person table in database.                      Person p=new Person();                      p.setName("Tom");                      p.setSex("male");                      p.setPicture(writtingImage("Image location"));// - c:\images\test.jpg                      sessionEJB.persistPerson(p);//Retrieving the image from Database table and writing to a file                      List<Person> plist=sessionEJB.getPersonFindAll();//                      Person person=(Person)plist.get(0);//get a person object                      retrieveImage(person.getPicture());   //get picture retrieved from Table //Private method to create byte[] from image file  private static byte[] writtingImage(String fileLocation) {      System.out.println("file lication is"+fileLocation);     IOManager manager=new IOManager();        try {           return manager.getBytesFromFile(fileLocation);                    } catch (IOException e) {        }        return null;    }//Private method to read byte[] from database and write to a image file    private static void retrieveImage(byte[] b) {    IOManager manager=new IOManager();        try {            manager.putBytesInFile("c:\\webtest.jpg",b);        } catch (IOException e) {        }    }End to End ADFaces application to retrieve the image from database table and display it in web page.Please find the application in this link.Following are the j2ee components used in the sample application.ADFFaces(jspx page)HttpServlet Class - Will make a call to EJB and retrieve the person object from person table.Read the byte[] and write to response using Outputstream.SessionEJBBean - This is a session facade to make a local call to JPA entitiesJPA Entity(Person.java) - Person java class with setter and getter method annotated with @Lob representing the clob/blob types for picture field.

This article describes about the JPA feature for handling clob and blob data types.You will learn the following in this article.@Lob annotation Client code to insert and retrieve the clob/blob types End...

EJB

EJB Persist On Master Child Relationship

Let us take scenario where in users wants to persist master child relationship. Here will have two tables dept, emp (using Scott Schema) which are having master child relation.Model Diagram: Here in the above model diagram, Dept is the Master table and Emp is child table and Dept is related to emp by one to n relationship. Lets assume we need to make new entries in emp table using EJB persist method. Create a Emp form manually dropping the fields, where deptno will be dropped as Single Selection -> ADF Select One Choice (which is a foreign key in emp table) from deptFindAll DC. Make sure to bind all field variables in backing bean.Employee Form:Once the Emp form created, If the persistEmp() method is used to commit the record this will persist all the Emp fields into emp table except deptno, because the deptno will be passed as a Object reference in persistEmp method  (Its foreign key reference). So directly deptno can't be passed to the persistEmp method instead deptno should be explicitly set to the emp object, then the persist will save the deptno to the emp table.Below solution is one way of work around to achieve this scenario -Create a method in sessionBean for adding emp records and expose this method in DataControl.     For Ex: Here in the below code 'em" is a EntityManager.            private EntityManager em - will be member variable in sessionEJBBeanpublic void addEmpRecord(String ename, String job, BigDecimal deptno) { Emp emp = new Emp(); emp.setEname(ename); emp.setJob(job); //setting the deptno explicitly Dept dept = new Dept(); dept.setDeptno(deptno); //passing the dept object emp.setDept(dept); //persist the emp object data to Emp table em.persist(emp);}From DataControl palette Drop addEmpRecord as Method ADF button, In Edit action binding window enter the parameter values which are binded in backing bean.     For Ex:     If the name deptno textfield is binded with "deptno" variable in backing bean, then El Expression Builder pass value as "#{backingbean.deptno.value}"Binding:

Let us take scenario where in users wants to persist master child relationship. Here will have two tables dept, emp (using Scott Schema) which are having master child relation. Model Diagram: Here in...

ADF

Insert Record by Drag & Drop from ADF Tree to ADF Tree Table

If you want to create record based on the values Dragged from ADF Tree and Dropped on a ADF Tree Table, then here you go.UseCase DescriptionUserDrags a tree node from ADF Tree and Drops it on a ADF Tree Table node.A new row gets added in the Tree Table based on the source tree node,subsequently a record gets added to the database table on which Treetable in based on.Following description helps to achieve this using ADF BC.Run the DragDropSchema.sql to create required tables.Create Business Components from tables (PRODUCTS, COMPONENTS, SUB_COMPONENTS, USERS, USER_COMPONENTS) created above.Add custom method to App Module Impl, this method will be used to insert record from view layer.   public String createUserComponents(String p_bugdbId, String p_productId, String p_componentId, String p_subComponentId){    Row newUserComponentsRow = this.getUserComponentsView1().createRow();    try {      newUserComponentsRow.setAttribute("Bugdbid", p_bugdbId);      newUserComponentsRow.setAttribute("ProductId", new oracle.jbo.domain.Number(p_productId));      newUserComponentsRow.setAttribute("Component1", p_componentId);      newUserComponentsRow.setAttribute("SubComponent", p_subComponentId);    } catch (Exception e) {        e.printStackTrace();        return "Failure";    }        return "Success";  }Expose this method to client interface.To display the root node we need a custom VO which can be achieved using below query.SELECT Users.ACTIVE, Users.BUGDB_ID, Users.EMAIL, Users.FIRSTNAME, Users.GLOBAL_ID, Users.LASTNAME, Users.MANAGER_ID, Users.MANAGER_PRIVILEGEFROM USERS UsersWHERE Users.MANAGER_ID is NULLCreate VL between UsersView and UsersRootNodeView VOs.Drop ProductsView from DC as ADF Tree to jspx page.Add Tree Level Rule based on ComponentsView and SubComponentsView.Drop UsersRootNodeView as ADF Tree TableAdd Tree Level Rules based on UserComponentsView and UsersView.Add DragSource to ADF Tree and CollectionDropTarget to ADF Tree Table respectively.Bind CollectionDropTarget's DropTarget to backing bean and implement method of signature DnDAction (DropEvent),this method gets invoked when Tree Table encounters a drop action, heredetails required for creating new record are captured from the dragsource and passed to 'createUserComponents' method.public DnDAction onTreeDrop(DropEvent dropEvent) {      String newBugdbId = "";      String msgtxt="";            try {          // Getting the target node bugdb id          Object serverRowKey = dropEvent.getDropSite();          if (serverRowKey != null) {                  //Code for Tree Table as target              String dropcomponent = dropEvent.getDropComponent().toString();              dropcomponent = (String)dropcomponent.subSequence(0, dropcomponent.indexOf("["));              if (dropcomponent.equals("RichTreeTable")){                RichTreeTable richTreeTable = (RichTreeTable)dropEvent.getDropComponent();                richTreeTable.setRowKey(serverRowKey);                int rowIndexTreeTable = richTreeTable.getRowIndex();                //Drop Target Logic                if (((JUCtrlHierNodeBinding)richTreeTable.getRowData(rowIndexTreeTable)).getAttributeValue()==null) {                  //Get Parent                  newBugdbId = (String)((JUCtrlHierNodeBinding)richTreeTable.getRowData(rowIndexTreeTable)).getParent().getAttributeValue();                } else {                  if (isNum(((JUCtrlHierNodeBinding)richTreeTable.getRowData(rowIndexTreeTable)).getAttributeValue().toString())) {                    //Get Parent's parent                              newBugdbId = (String)((JUCtrlHierNodeBinding)richTreeTable.getRowData(rowIndexTreeTable)).getParent().getParent().getAttributeValue();                  } else{                      //Dropped on USER                                          newBugdbId = (String)((JUCtrlHierNodeBinding)richTreeTable.getRowData(rowIndexTreeTable)).getAttributeValue();                  }                  }              }           }                     DataFlavor<RowKeySet> df = DataFlavor.getDataFlavor(RowKeySet.class);          RowKeySet droppedValue = dropEvent.getTransferable().getData(df);            Object[] keys = droppedValue.toArray();          Key componentKey = null;          Key subComponentKey = null;           // binding for createUserComponents method defined in AppModuleImpl class  to insert record in database.                      operationBinding = bindings.getOperationBinding("createUserComponents");            // get the Product, Component, Subcomponent details and insert to UserComponents table.          // loop through the keys if more than one comp/subcomponent is select.                   for (int i = 0; i < keys.length; i++) {                  System.out.println("in for :"+i);              List list = (List)keys[i];                  System.out.println("list "+i+" : "+list);              System.out.println("list size "+list.size());              if (list.size() == 1) {                                // we cannot drag and drop  the highest node !                                msgtxt="You cannot drop Products, please drop Component or SubComponent from the Tree.";                  System.out.println(msgtxt);                                this.showInfoMessage(msgtxt);              } else {                  if (list.size() == 2) {                    // were doing the first branch, in this case all components.                    componentKey = (Key)list.get(1);                    Object[] droppedProdCompValues = componentKey.getAttributeValues();                    operationBinding.getParamsMap().put("p_bugdbId",newBugdbId);                    operationBinding.getParamsMap().put("p_productId",droppedProdCompValues[0]);                    operationBinding.getParamsMap().put("p_componentId",droppedProdCompValues[1]);                    operationBinding.getParamsMap().put("p_subComponentId","ALL");                    Object result = operationBinding.execute();              } else {                    subComponentKey = (Key)list.get(2);                    Object[] droppedProdCompSubCompValues = subComponentKey.getAttributeValues();                    operationBinding.getParamsMap().put("p_bugdbId",newBugdbId);                    operationBinding.getParamsMap().put("p_productId",droppedProdCompSubCompValues[0]);                    operationBinding.getParamsMap().put("p_componentId",droppedProdCompSubCompValues[1]);                    operationBinding.getParamsMap().put("p_subComponentId",droppedProdCompSubCompValues[2]);                    Object result = operationBinding.execute();                  }                   }            }                        /* this.getCil1().setDisabled(false);            this.getCil1().setPartialSubmit(true); */                      return DnDAction.MOVE;        } catch (Exception ex) {          System.out.println("drop failed with : " + ex.getMessage());          ex.printStackTrace();                  /* this.getCil1().setDisabled(true); */          return DnDAction.NONE;          }    }Run jspx page and drop a Component or Subcomponent from Products Tree to UserComponents Tree Table.

If you want to create record based on the values Dragged from ADF Tree and Dropped on a ADF Tree Table, then here you go. UseCase Description UserDrags a tree node from ADF Tree and Drops it on a ADF...

Toplink

How to use Object Type Converter

UseCase DescriptionUser will enter a String in the form which has to be persisted in the database as a NumberFrom the User Interface we might be getting a String value which has to be persisted in the database as a number. In this scenario we can use converters to map the java object which is of type String to its database value which is a Number.For example , there is a 'Person' table in database which is used to store the user details passed from the User Interface. It has a 'Status' column which is of the value  Number. But from the User Interface String values (Active/InActive) are passed . For persisting the user details we can use Object type converter and provide the mappings for status column corresponding to the String values.Object type converter can be used if you want to have a mapping for a field for example when departmentName on the entity is of String value and mapped to dept_name field on the database table which is of the value Number.Implementation stepsSample EJB API for setting the value of status on Person Entity as a String    public void createPerson(String status,String firstName,String lastName) {                Person person = new Person();                // status will be set as a String value received from the User Interface         person.setStatus(status);                person.setFirstname(firstName);        person.setLastname(lastName);                persistPerson(person);         }In the sample code shown above status is passed as a String, this has to be converted to Number. The String value obtained will be set on Person object and persistPerson API will be called for creating a new person from the values passed from the User Interface. Steps to configure Object type converter: 1. Navigate to Person Entity from persistence.xml and navigate to status field2. Click on Conversion tab and select Converted check box3. Select Object Type Converter radio button and set the Data Type Class to      java.math.BigDecimal and Object Type Class to java.lang.String4. Specify the conversion values for all the values that can be passed from the user interface  as shown below5. Set the Default Object value Object Type Converter maps the status column in the database to the corresponding String values set in the converter. In this type of scenario, Object Type Converter can be effectively used to map the Java Object to a database column which is of a different data type.  

UseCase Description User will enter a String in the form which has to be persisted in the database as a Number From the User Interface we might be getting a String value which has to bepersisted in the...

ADF

Changing Endpoint URL for a Web Service Data Control

When you move your application from Development to Production, there is more often then not, a need to change the web service endpoint URL in your ADF application. If you are using a Web Service Data Control(WSDC), you can do this in more than one ways. The following example illustrates how this can be done.At Design TimeIf the application workspace is in your control, you can quickly do this by updating the definition in DataControl.dcx file:Along with this, you will also need to change the endpoint in connections.xml. So invoke the Edit Connections dialog: Then, change the endpoint URL.At DeploymentAnother way to change is changing the endpoint at the ear level, at deployment. So when you select Deploy -> Application Server at the Application level, it will bring up a Deployment Configuration dialog, in which you can edit the WSDL URL:Also, change the Port URL:At Post DeploymentIf your need to change this post deployment, you can do it through Oracle Enterprise Manager. But for this, your application needs to be configured with a writable MDS repository. It is recommended you use a Database MDS store during deployment. So have your application configured (by having an entry in adf-config.xml) and server configured (by having a MDS store registered). Once done, you can configure the ADF Connection in EM for this application:Change the WSDL location here on 'Edit':Also, change the Port using Advance Connection Configuration:Change the Endpoint Address here:Apply Changes and you are done!

When you move your application from Development to Production, there is more often then not, a need to change the web service endpoint URL in your ADF application. If you are using a Web Service Data...

EJB

Simulating LOV (List Of Values) in EJB

This Use case simulates lov(list of values) in EJB.It uses HR Schema with locations & countries tables.Based on the value selected in lov,it performs query in database & displays result in ADF Form.Steps Let us suppose that we have created Java EE Web Application with Entities from locations & countries tables.Add custom NamedQuery to Locations.java bean that returns the list of Locations for the respective countryId parameter: @NamedQuery(name = "Localtions.FindByCountryId", query = "select o from Locations o where o.countries.countryId = :countryId") Create Stateless Session Bean and expose the Named Queries through the Session Facade. And then generate Datacontrol from SessionBean local interface.Create LovTestpage.jspx page in ViewController project & drop countryId parameter as selectOneChoiceAdd countriesFindAll as List Data Source in the Edit List Binding EditorAdd valueChangeListener to selectOneChoice by creating Managed Bean testBean.java & valueChangeListenerMethod in this Managed Bean .public void valueChangeListenerMethod(ValueChangeEvent valueChangeEvent) {  // This method passes the selected value to the method & method is executed       BindingContainer bindings = getBindings();OperationBinding operationBinding =  bindings.getOperationBinding("getLocaltionsFindByCountryId");operationBinding.getParamsMap().put("countryId", valueChangeEvent.getNewValue().toString());Object result = operationBinding.execute(); }public static BindingContainer getBindings() {            return BindingContext.getCurrent().getCurrentBindingsEntry(); }By Default the selectOneChoice returns index in its valueChangeListener method,in order to return the selected value,modify these entries:a)Goto the page Definition file & add a List Binding:     <list ListOperMode="navigation"      IterBinding="countriesFindAllIterator"     ListIter="countriesFindAllIterator" id="countryIdLOV"></list>b)SelectOneChoice code in jspx page should be:<af:selectOneChoice value="#{testBean.countryValue}" label="#{bindings.countryId.label}"  autoSubmit="true" required="#{bindings.countryId.hints.mandatory}"  shortDesc="#{bindings.countryId.hints.tooltip}" id="soc1" valueChangeListener=  "#{testBean.valueChangeListenerMethod}" >              <af:forEach items="#{bindings.countryIdLOV.iteratorBinding.allRowsInRange}" var="var1">   <af:selectItem id="si2" label="#{var1.dataProvider.countryId}"     value="#{var1.dataProvider.countryId}"/>  </af:forEach></af:selectOneChoice>Open LovTestpage.jspx page & drop Locations as ADF FormRun the above page & note that the form shows the location details of the selected countryIdNow lets try to extend the same use case to achieve Dependent lov's.In the same above jspx page,drop Locations node as selectOneChoice with display attribute as 'locationId'.Try to run the page & note that the Locations list changes dynamically based on the countryId selection.

This Use case simulates lov(list of values) in EJB.It uses HR Schema with locations & countries tables.Based on the value selected in lov,it performs query in database & displays result in ADF Form.Ste...

ADF

Creating a UI First Design

This article explains creating a UI first design for enterprise applications.Usecase DescriptionThe use case deals with developing a UI first design. Sometimes, it might be required to develop UI, and data might not be readily available to test the application. ADF provides a facility called placeholder data controls, that act as place holders for any type of data control that one might want to use. Place holder data controls contain sample data entered directly, or uploaded via a csf file. The binding can then be altered to rebind any other data control that one might choose to create.This usecase will include steps to create placeholder data controls, create lovs, create a master child relationship all using a UI first design approach with manually entered sample data. It will also show rebinding datacontrols (in this case ADFBC).Steps:1. Create a Fusion Web application.2. Create a placeholder Data Control from File -> New Gallery -> Business Tier -> Data Controls -> Place Holder Data Control.3. Select Placeholder in Data controls,right click & create place holder data type with 2attributes of number and String datatypes 4. Enter sample data for both.5. Click OK to create the Place holder data type.6. Create another Place holder data type with 2 attributes of Number and String data type.7. Choose the String attribute and select Use LOV Binding Checkbox8. In the ensuing dialog, select the String attribute as list data type, and shuttle the display items to the right and click OK.9.Click OK on the Create Place Holder Data Type Dialog.10. In the View controller, create a jspx page, and drag and drop the PHDC as an ADF Form.11. Create another ADF Model project with ADFBC components based on Dept Table.12. Open the jspx page, and click on the String field and choose Bind to Data control.13. Choose Dname from under DeptView114. Run the page to see the rebinded Data control.

This article explains creating a UI first design for enterprise applications.Usecase Description The use case deals with developing a UI first design. Sometimes, it mightbe required to develop UI, and...

Webservices

Using Global Policy Attachment with JRF Proxies

In Oracle Fusion Middleware 11g R1 PS3 (11.1.1.4.0) WSM has implemented a mechanism to provide the ability to create and attach policy sets to subjects on a global scope (domain, server, application, or SOA composite). In this entry we will have a look how this can be done using Web Services WLST Globally-available Policy Set Management Commands for a JRF Web Service Proxy.To start, let's start by creating a POJO Web Service in JDeveloper and attach a OWSM security policy to it. Say, the service definition looks like: Run the service in Integrated Weblogic Server. Next, create a proxy in a new Project for the above service. Use all the defaults and at the Client Policy Configuration page make sure that you don't pick the corresponding Client policy. Now create the ADF WebService Conn for the proxy using the context menu.Accept the defaults and press Ok.This will create a connections.xml file for you, which you can see under ADF META-INF in Application Resources. Once generated, modify (or create new) the client class as follows:AddServicePortClient.javaTo successfully compile the above code, you need to add the library "ADF Model Runtime" to the project.Once compiled, create a Bean DC for the Client class.Now create an ADF Library Jar File for this project and using the Resource Palette, create a File System Connection to this jar, so that we can use this data control in a reusable fashion.At this point before we use the DC with a client, let's configure the server by creating a Policy Set and attaching appropriate policies with this Policy Set.For this start the wlst command from <ORACLE_HOME>\oracle_common\common\binOnce you are connected to the Integrated WLS, this is the set of commands you need to setup a Policy Set for this case:wls:/DefaultDomain/serverConfig> beginRepositorySession()Repository session begun.wls:/DefaultDomain/serverConfig> createPolicySet("ws-conn-set","ws-connection","Domain('D*')")Description defaulted to "Global policy attachments for Web Service Connection resources."The policy set was created successfully in the session.wls:/DefaultDomain/serverConfig> attachPolicySetPolicy("oracle/wss11_x509_token_with_message_protection_client_policy")Policy reference added.wls:/DefaultDomain/serverConfig> commitRepositorySession()The policy set ws-conn-set is valid.Creating policy set ws-conn-set in repository.Repository session committed successfully.Now, create a new Fusion Web Application and add the Data Control from File System Conn to the Model Project.Now create a jspx page using the above Data Control and run the page. If you have HTTP Analyzer running, you can see that the call has been made to the service in a secure manner.If at any point you change the security policy at the service, all you need to do is update the Policy Set with the corresponding new client policy and re-deploy the client.

In Oracle Fusion Middleware 11g R1 PS3 (11.1.1.4.0) WSM has implemented a mechanism to provide the ability to create and attach policy sets to subjects on aglobal scope (domain, server, application,...

EJB

Difference between EJB Persist & Merge operation

This article gives the difference between EJB Persist & Merge operations with scenarios.Use Case DescriptionUsers working on EJB persist & merge operations often have this question in mind " When merge can create new entity as well as modify existing entity,then why do we have 2 separate operations - persist & merge?" The reason is very simple.If we use merge operation to create new entity & if the entity exists then it does not throw any exception,but persist throws exception if the entity already exists.Merge should be used to modify the existing entity.The sql statement that gets executed on persist operation is insert statement.But in case of merge first select statement gets executed & then update sql statement gets executed.Scenario 1: Persist operation to create new Emp recordLet us suppose that we have created Java EE Web Application with Entities from Emp table Create session bean & generate data control for the sameDrop Emp Object(Expand SessionEJBLocal->Constructors under Data Controls) as ADF Parameter form in jspx pageDrop persistEmp(Emp) as ADF CommandButton & provide #{bindings.EmpIterator.currentRow.dataProvider} as the value for emp parameter.Then run this page & provide values for Emp,click on 'persistEmp' button.New Emp record gets created.So when we execute persist operation only insert sql statement gets executed :INSERT INTO EMP (EMPNO, COMM, HIREDATE, ENAME, JOB, DEPTNO, SAL, MGR) VALUES (?, ?, ?, ?, ?, ?, ?, ?)    bind => [2, null, null, e2, null, 10, null, null]Scenario 2: Merge operation to modify existing Emp recordLet us suppose that we have a Java EE Web Application created with Entities from Emp table & have created session bean with data control.Drop empFindAll() Object as ADF form on jspx page.Drop mergeEmp(Emp) operation as commandButton & provide #{bindings.EmpIterator.currentRow.dataProvider} as the value for emp parameter.Then run this page & modify values for Emp record,click on 'mergeEmp' button.The respective Emp record gets modified.So when we execute merge operation select & update sql statements gets executed :SELECT EMPNO, COMM, HIREDATE, ENAME, JOB, DEPTNO, SAL, MGR FROM EMP WHERE (EMPNO = ?) bind => [7566]UPDATE EMP SET ENAME = ? WHERE (EMPNO = ?) bind => [KINGS, 7839]

This article gives the difference between EJB Persist & Merge operations with scenarios.Use Case Description Users working on EJB persist & merge operations often havethis question in mind " When...

ADF

How to set conditional activation to taskflows?

This article describes implementing conditional activation to taskflows.Use Case DescriptionSuppose we have a taskflow dropped as region on a page & this region is enclosed in a popup .By default when the page is loaded the respective region also gets loaded.Hence a region model needs to provide a viewId whenever one is requested.  A consequence of this is the TaskFlowRegionModel always has to initialize its task flow and execute the task flow's default activity in order to determine a viewId, even if the region is not visible on the page.This can lead to unnecessary performance overhead of executing task flow to generate viewIds for regions that are never visible. In order to increase the performance,we need to set the taskflow bindings activation property to 'conditional'.Below described is a simple usecase that shows how exactly we can set the conditional activations to taskflow bindings.Steps:1.Create an ADF Fusion web Application2.Create Business components for Emp table3.Create a view criteria where deptno=:some_bind_variable4.Generate EmpViewImpl.java file & write the below code.Then expose this to client interface.    public void filterEmpRecords(Number deptNo){            // Code to filter the deptnos         ensureVariableManager().setVariableValue("some_bind_variable",  deptNo);        this.applyViewCriteria(this.getViewCriteria("EmpViewCriteria"));        this.executeQuery();       }5.Create an ADF Taskflow with page fragements & drop the above method on the taskflow6.Also drop the view activity(showEmp.jsff) .Define control flow case from the above method activity to the view activity.Set the method activity as default activity7.Create  main.jspx page & drop the above taskflow as region on this page8.Surround the region with the dialog & surround the dialog with the popup(id is Popup1)9.Drop the commandButton on the above page & insert af:showPopupBehavior inside the commandButton:<af:commandButton text="show popup" id="cb1"><af:showPopupBehavior popupId="::Popup1"/></af:commandButton>10.Now if we execute this main page ,we will notice that the method action gets called even before the popup is launched.We can avoid this this by setting the activation property of the taskflow to conditional11.Goto the bindings of the above main page & select the taskflow binding ,set its activation property to 'conditional' & active property to Boolean value #{Somebean.popupVisible}.By default its value should be false.12.We need to set the above Boolean value to true only when the popup is launched.This can be achieved by inserting setPropertyListener inside the popup:<af:setPropertyListener from="true" to="#{Somebean.popupVisible}" type="popupFetch"/>13.Now if we run the page,we will notice that the method action is not called & only when we click on 'show popup' button the method action gets called.

This article describes implementing conditional activation to taskflows.Use Case Description Suppose we have a taskflow dropped as region on a page &this region is enclosed in a popup .By default when...

Faces

Getting all selected rows in ADF Table with multiple rows selection enabled

When we build a web application which contains an ADF Table (with multiselect option), in many cases, we require to get all the selected rows to process through backing bean. This example will illustrate how to achieve that.Assuming that we already have an application, that contains an ADF Table with multi-selection enabled (i.e the web page look something like the image shown below).img empTableRT : Table based on Emp To access the table in the backing bean (through command button click, for ex.), we add an attribute with accessors in the backing bean and bind it to ADF Table RichTable empTable; public void setEmpTable(RichTable empTable) { this.empTable = empTable; } public RichTable getEmpTable() { return empTable; }code snippet of the af:table in jspx page.<af:table value="#{bindings.EmpView1.collectionModel}" var="row" rows="#{bindings.EmpView1.rangeSize}" emptyText="#{bindings.EmpView1.viewable ? 'No data to display.' : 'Access Denied.'}" fetchSize="#{bindings.EmpView1.rangeSize}" rowBandingInterval="0" selectedRowKeys="#{bindings.EmpView1.collectionModel.selectedRow}" selectionListener="#{bindings.EmpView1.collectionModel.makeCurrent}" rowSelection="multiple" id="t1" binding="#{backingBeanScope.EmpBean.empTable}">Let us add a command button in the jspx page to print down the "Ename"s of selected rows.<af:commandButton text="Print selected Emps" id="cb1" action="#{backingBeanScope.EmpBean.printSelectedEmpNames}"/>The method printSelectedEmpNames in the backing bean gets the selected row keys from the table, gets the corresponding Enames from the iterator (on which the table is based on) and prints them.public String printSelectedEmpNames() { RowKeySet selectedEmps = getEmpTable().getSelectedRowKeys(); Iterator selectedEmpIter = selectedEmps.iterator(); DCBindingContainer bindings = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry(); DCIteratorBinding empIter = bindings.findIteratorBinding("EmpView1Iterator"); RowSetIterator empRSIter = empIter.getRowSetIterator(); while(selectedEmpIter.hasNext()){ Key key = (Key)((List)selectedEmpIter.next()).get(0); Row currentRow = empRSIter.getRow(key); System.out.println(currentRow.getAttribute("Ename")); } return null; }We run the page and click button to check the selected rows.As we've selected 7 rows, clicking on the "Print selected Emps" button is expected to print 7 Enames.But..... It just prints only one Ename.CLARKWell, this is because of the selectedRowKeys property of the af:table. Let us try removing that and see if we get the expected output.<af:table value="#{bindings.EmpView1.collectionModel}" var="row" rows="#{bindings.EmpView1.rangeSize}" emptyText="#{bindings.EmpView1.viewable ? 'No data to display.' : 'Access Denied.'}" fetchSize="#{bindings.EmpView1.rangeSize}" rowBandingInterval="0" selectionListener="#{bindings.EmpView1.collectionModel.makeCurrent}" rowSelection="multiple" id="t1" binding="#{backingBeanScope.EmpBean.empTable}">Now, when we run the page, select 7 rows and click on the print button, it prints outJONESALLENCLARKWARDSMITHMARTINBLAKEThat is what we expected. Now, the question is why this happens?. It is because, since value of this selectedRowKeys property is #{bindings.EmpView1.collectionModel.selectedRow}, the selectedRowKeys will contain only the "row which is selected last". By unsetting this attribute, we let the table to push all the selected rows to selectedRowKeys, which will help us duringgetEmpTable().getSelectedRowKeys();in the backing bean. JDeveloper automatically adds this property to the ADF Table when it is created by dragging from the data control. So, removing this property from the af:table would get us desired result.

When we build a web application which contains an ADF Table (with multiselect option), in many cases, we require to get all the selected rows to process through backing bean. This example will...