Tuesday, December 30, 2014

Optmizing View Object Run time performance

Fetch Tuning ParametersUsage
Fetch Mode
The default fetch option is the All Rows option, which will be retrieved As Needed (FetchMode="FETCH_AS_NEEDED") or All at Once (FetchMode="FETCH_ALL"), depending on which option is desired. The As Needed option ensures that anexecuteQuery() operation on the view object initially retrieves only as many rows as necessary to fill the first page of a display, whose number of rows is set based on the view object's range size.
Fetch Size
In conjunction with the Fetch Mode option, the in Batches of field controls the number of records fetched at one time from the database (FetchSize in the view object XML). The default value is 1, which will give poor performance unless only one row will be fetched. The suggested configuration is to set this value to n+1 where n is the number of rows to be displayed in the user interface.
Max Fetch Size
The default max fetch size for a view object is -1, which means that there is no limit to the number of rows the view object can fetch. In cases where the result set should contain only n rows of data, the option Only up to row number should be selected and set to n. The developer can alternatively call setMaxFetchSize(n) to set this programmatically or manually add the parameter MaxFetchSize to the view object XML.
For view objects whose WHERE clause expects to retrieve a single row, set the option At Most One Row. This way the view object knows you don't expect any more rows and it will skip its normal test for that situation.
As mentioned earlier, setting a maximum fetch size of 0 (zero) makes the view object insert-only. In this case, no select query will be issued, so no rows will be fetched.
When you want to specify a global threshold for all view object queries in the application, you can configure the Row Fetch Limit property in the adf-config.xml file. Setting this property means you can avoid changing the Max Fetch Size for individual query operations. If you do specify a fetch limit for individual view objects, the Row Fetch Limit setting will be ignored in those cases. For more details about Row Fetch Limit, see Section 42.1.1, "Limiting the View Object Max Fetch Size to Fetch the First n Rows."
Forward-only Mode
If a data set will only be traversed going forward, then forward-only mode can help performance when iterating through the data set. This can be configured by programmatically calling setForwardOnly(true) on the view object. Setting forward-only will also prevent caching previous sets of rows as the data set is traversed.
When you tune view objects, you should also consider these issues:
  • Large data sets: View objects provide a mechanism to page through large data sets such that a user can jump to a specific page in the results. This is configured by calling setRangeSize(n) followed by setAccessMode(RowSet.RANGE_PAGING) on the view object where n is the number of rows contained within one page. When the user navigates to a specific page in the data set, the application can call scrollToRangePage(P) on the view object to navigate to page P. Range paging fetches and caches only the current page of rows in the view object row cache at the cost of another query execution to retrieve each page of data. Range paging is not appropriate where it is beneficial to have all fetched rows in the view object row cache (for example, when the application needs to read all rows in a dataset for an LOV or page back and forth in records of a small data set.
  • Spillover: There is a facility to use the data source as "virtual memory" when the JVM container runs out of memory. By default, this is disabled and can be turned on as a last resort by setting jbo.use.pers.coll=true. Enabling spillover can have a large performance impact.
  • SQL platform: If the generic SQL92 SQL platform is used to connect to generic SQL92-compliant databases, then some view object tuning options will not function correctly. The parameter that choosing the generic SQL92 SQL platform affects the most is the fetch size. When SQL92 SQL platform is used, the fetch size defaults to 10 rows regardless of what is configured for the view object. You can set the SQL platform when you define the database connection or you can define it as global project setting in the adf-config.xml file. By default, the SQL platform will beOracle. To manually override the SQL platform, you can also pass the parameter -Djbo.SQLBuilder="SQL92" to the JVM upon startup.
Additionally, you have some options to tune the view objects' associated SQL for better database performance:
  • Bind variables: If the query associated with the view object contains values that may change from execution to execution, use bind variables. Using bind variables in the query allows the query to reexecute without needing to reparse the query on the database. You can add bind variables to the view object in the Query page of the overview editor for the view object. For more information, see Section 5.10, "Working with Bind Variables."
  • Query optimizer hints: The view object can pass hints to the database to influence which execution plan to use for the associated query. The optimizer hints can be specified in the Retrieve from the Database group box in the Tuning section of the overview editor for the view object. For information about optimizer hints, see Section 42.2.4.3, "Specify a Query Optimizer Hint if Necessary."
Reference : http://docs.oracle.com/cd/E16162_01/web.1112/e16182/bcqueryresults.htm#ADFFD19565

Monday, November 10, 2014

Monday, September 22, 2014

Code Corner ADF Examples

http://www.oracle.com/technetwork/developer-tools/adf/learnmore/index-101235.html#CodeCornerSamples

Tuesday, September 9, 2014

Wednesday, August 13, 2014

Problem not fetching all the records when executing a View Object in ADF

Execute the View Object :

this.getXyzEOView().getViewObject().setQueryMode(ViewObjectImpl.QUERY_MODE_SCAN_DATABASE_TABLES|ViewObjectImpl.QUERY_MODE_SCAN_ENTITY_ROWS|ViewObjectImpl.QUERY_MODE_SCAN_UNPOSTED_ENTITY_ROWS|ViewObjectImpl.QUERY_MODE_SCAN_VIEW_ROWS);

Thursday, July 17, 2014

Run the page after rebuilt in adf

Replace the target in the jdeveloper properties with the below line:



C:\Oracle\Middleware-New\jdeveloper\jdeveloper.exe -J-Doracle.jdeveloper.adrs.incr.buildMonitor=false

Monday, June 16, 2014

ADF Best Practices

ADF Best Practices:
1.        Avoid Web services -- performance issues.
2.        Avoid JDBC Raw calls – framework already takes care of that
3.        Resource bundles – Error messages, tooltips and labels
4.        UI Properties files – File of tokens and matching strings
5.        Clean check out – everytime when starting a development
6.        One to Many mapping of EO s and VO s – Using joins in VO s is preferable
7.        Use ROVO when possible – Helps performance by bypassing the entity cache
8.        Define VO s at design time rather than at run time – VO s created at run time will incur an overhead in the performance
9.        Use named bind variables in queries to filter the data based on a number of parameters – Can use executeWithParams as a search form
10.     Performance – Define how many and what matter the rows are being fetched
                        Optimizer hints
                        Define the query plan the DB will use when executing a query

                            
11.     Application Module Configuration setting:

a.        While Developing : ‘jbo.ampool.doampooling’ parameter to ‘false’
As you exit out your application while testing, re-runs of the application wont be locked by the application you just exited.
b.        While Testing : ‘jbo.dofailover’ parameter to ‘false’
Thus disabling application fail over. This will allow application with out having to save the failover information.
c.        If the application uses the same database user to access application data ensure that you are not running with dynamic JDBC credentials. Use ‘jbo.ampool.dynamicjdbccredentials’ set to ‘false’

12.     Java Server Faces:
Do not mix JSFs with any other raw HTML tables for layout.

13.     Backing Beans:
The backing bean is a one-stop-shop for the code associated with a web page and generally speaking it is good practice,  if you require code to support a page, to have one backing bean per page.

14.     Managed Beans:

If it is required to store the state information to be held for the user interface then this should be done through managed beans.ADF Best Practices:
1.        Avoid Web services -- performance issues.
2.        Avoid JDBC Raw calls – framework already takes care of that
3.        Resource bundles – Error messages, tooltips and labels
4.        UI Properties files – File of tokens and matching strings
5.        Clean check out – everytime when starting a development
6.        One to Many mapping of EO s and VO s – Using joins in VO s is preferable
7.        Use ROVO when possible – Helps performance by bypassing the entity cache
8.        Define VO s at design time rather than at run time – VO s created at run time will incur an overhead in the performance
9.        Use named bind variables in queries to filter the data based on a number of parameters – Can use executeWithParams as a search form
10.     Performance – Define how many and what matter the rows are being fetched
                           Optimizer hints
                               Define the query plan the DB will use when executing a query
                            
11.     Application Module Configuration setting:
a.        While Developing : ‘jbo.ampool.doampooling’ parameter to ‘false’
As you exit out your application while testing, re-runs of the application wont be locked by the application you just exited.
b.        While Testing : ‘jbo.dofailover’ parameter to ‘false’
Thus disabling application fail over. This will allow application with out having to save the failover information.
c.        If the application uses the same database user to access application data ensure that you are not running with dynamic JDBC credentials. Use ‘jbo.ampool.dynamicjdbccredentials’ set to ‘false’

12.     Java Server Faces:
Do not mix JSFs with any other raw HTML tables for layout.

13.     Backing Beans:
The backing bean is a one-stop-shop for the code associated with a web page and generally speaking it is good practice,  if you require code to support a page, to have one backing bean per page.

14.     Managed Beans:
If it is required to store the state information to be held for the user interface then this should be done through managed beans.

Thursday, May 15, 2014

Refresh Page in ADF

The following code refreshes the whole page

  1. FacesContext fctx = FacesContext.getCurrentInstance();
    String refreshpage = fctx.getViewRoot().getViewId();ViewHandler ViewH = fctx.getApplication().getViewHandler();
    UIViewRoot UIV = ViewH.createView(fctx, refreshpage);
    UIV.setViewId(refreshpage);
    fctx.setViewRoot(UIV);

To refresh a specific component :

  1. AdfFacesContext.getCurrentInstance().addPartialTarget(UIComponent);

Friday, May 9, 2014

Web Service Proxy in adf

Requirement : Create a web service proxy and use that to invoke the web service and get the response.

As per my understanding web service proxy created java classes that can be used to invoke the web service from the application.

Creating a web service proxy is pretty simple, we just need to have the wsdl url.

On 11.1.1.5.0 the options would be something like this:


select web service proxy

On 11.1.2.0


Now we need to select the different options in the wizard:

NOTE :  The Client style is usually JAX-WS Style but sometimes when invoking a .net service or any other legacy services we might encounter an error whil creating the web service. 

That case we might want to create a JAX-RPC weblogic style. 

In my case i had a .net service which i wasnt even able to test it in SOAPUI. This case go for JAX-RPC which will serve the purpose.

Please be informed that you can see these style selections only when we create a generic application with the web services shuffled in the project technologies, then you would see this option 

This new application can be used as a jar in the working application/project where you want to use the service.

For a regular SOA service we dont have to worry about all this. 

After successfully creating a Web Service Proxy we can see various .java files created. We have to search for class ending in *client.java class where you have the comments 

// add your code here 

Once we are aware of the input types pass the request and get the response here. 

If the request has to be sent from a different application, we need to add this application in the dependencies and class paths as a .jar file



Wednesday, May 7, 2014

Usage Of Servlets in ADF To Show Af:Image Based On a Parameter

Requirement : Show a Picture based on an Id which is coming from a service.

Solution : Create a Servlet in ViewController


Select appropriate methods to implement from doGet(), doPost(), service(), doPut(), doDelete().

In my case i had to implement the doGet() method to get the response from the servlet and show that on the jsff page.

The URL pattern will let you point to the appropriate Servlet from the page.

A java class something like this will get generated:

package client;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.*;
import javax.servlet.http.*;

public class Servlet1
  extends HttpServlet
{
  private static final String CONTENT_TYPE = "text/html; charset=windows-1252";

  public void init(ServletConfig config)
    throws ServletException
  {
    super.init(config);
  }

  public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    response.setContentType(CONTENT_TYPE);
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head><title>Servlet1</title></head>");
    out.println("<body>");
    out.println("<p>The servlet has received a GET. This is the reply.</p>");
    out.println("</body></html>");
    out.close();
  }
}

Override the doGet() method as per the requirement :
In my case i pass an Id to a service and get the byte[] in response to it.
I need to convert it to a jpg file, so set the content type to "image/jpg".
Write that to the out response of the doGet() and we are done defining and implementing the Servlet.

For Ex :

  public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    if (request.getParameter("dsId") != null)
    {
      OutputStream out = null;
      try
      {
        /*
          Code to get the Id from the service, added a jar file to the ViewController which has the webservice proxy client
          */
               }
        if (imageByte != null)
        {
          response.setContentType("image/jpg");
          out = response.getOutputStream();
          out.write(imageByte);
          out.flush();
        }
      }
      catch (Exception ex)
      {
        ex.printStackTrace();
      }
      finally
      {
        if (out != null)
          out.close();
      }
    }
  }
}

On the page where the image has to be showed on the run time give the appropriate Servlet URL

For Ex:

<af:image source="/dsimageservlet?dsId=#{bindings.DistributorId.inputValue}" id="i12"
                            inlineStyle="height:150px; width:150px;"/>

The newly added servlet can be view in web.xml file in my case the name is DSImageServlet.


Thats it, run the page and view the servlet response on the page.



Tuesday, April 29, 2014

Make, Rebuild and Make all option in JDeveloper

Make : Make operation compiles only the source files that have been changed since they were last compiled, or have dependencies that have been changed.

Rebuild : It compiles the source files unconditionally.

Make is done on individual source files, on working sets or on containers such as packages, projects, and workspaces.

Clean All: Cleans all the projects

Make all : Compiles not only the working project but all the projects.

Monday, April 28, 2014

Groovy Expression Usage in ADF, JDeveloper

Different points where Goovy code can be dropped:
1. Values for View and Entity objects attributes.
2. Validation rules on Entity object attributes.
3. Expressions for error messages.
4. Values for view object bind variables.
5. View object transient attribute validations.
Some of the properties of groovy scripting language

- Groovy is a scripting language having java like syntax
- Groovy is executed at run time
-  
Can be used in Entity and View objects in attribute validators(Entity Objects),attribute default values( Entity and View),bind variable default values ( View) place holder for error messages (EO validation rules)
- Define script expression validator or Compare validator 
- Error message tokens can be defined for handling validation failures 
- Conditional execution of validatiors are possible 
- Default value of bind variable in view object can be defined using groovy expression 
- Default value of view criteria 
- Default value and optional re-calculation condition for EO
- Value of transient for EO and VO 

Referencing Buisiness components objects in Groovy expression
Top level object is "adf" . Accessible ADF objects throgh groovy are 
- adf.context - Reference to ADFContext 
- adf.object - Equivalent to this operator in java.
- Entity Objects attributes - Reference methods and attributes of EntityImpl class.
- Entity Objects script validator rules - Attributes and method of ViewImpl class.
- View Object attributes 
- Bind Variable in view Object 
- Bind variable in view accessors 
- Transient attributes 
- adf.error 
- adf.userSession 
- adf.currentDate 
- adf.currentDateTime 
- Referencing custom buisiness components methods and attributes 
eg. Sal*12 - annualsalary .
PromotionDate>HireDate 

Method of entity class in validation rule.For validators use source keyword
eg. source.getDefaultSalaryForGrade()

- newValue - Attribute value being set 
-oldValue - current value of attribute being set 

if(Job=’SALESMAN’)
{
 return newValue<source.getMaxSalaryForGrade(Job)
}

Manipulating business component attribute values in a groovy expression
RowSet Objects
-          rowSetAttr.sum(GroovyExpr)
-          rowSetAttr.count(GroovyExpr)
-          rowSetAttr.avg(GroovyExpr)
-          rowSetAttr.min(GroovyExpr)
-          rowSetAttr.max(GroovyExpr)
EmployeesInDept.sum(“Sal+adf.object.getBenefitsValue(Job)”)


Thursday, April 10, 2014

Increase log level in ADF

In the ViewController -> Project Properties

set this value in the Run/Debug/Profile

-Dmock=true -Djbo.debugoutput=console


Sample expression in Instyle ADF :

Example 1 : color a column conditionally in a table
#{(row.TotalWeighed!=null)? (row.GreenOrRed=='Green'? 'background-color:Green;color:White;' : 'background-color:Red;color:White'):''}

Example 2: Load an image based on the logged in user:
#{sessionScope.loggedInUser=='InternalUser'? 'background-image:url("Image/internalfacing.png")' : 'background-image:url("Image/ds_facing.png")'}

Thursday, February 20, 2014

Display messages from the backing bean programmatically

        if(condition ){
        String messageText = " Message to be displayed";
        FacesMessage fm = new FacesMessage(messageText);
        // set the severity of the message
        fm.setSeverity(FacesMessage.SEVERITY_INFO);
        FacesContext context = FacesContext.getCurrentInstance();
        context.addMessage(null, fm);
    }

Monday, February 10, 2014

Dynamic query in ADF

http://mahmoudoracle.blogspot.com/2012/05/adf-dynamic-view-object.html#.Uvlr5fldVZs

Today I want to write about dynamic view object which allow me to change its data source (SQL query) and attributes at run time.

I will use oracle.jbo.ApplicationModule::createViewObjectFromQueryStmt method to do this issue.

I will present how to do this step by step


Create View Object and Application Module
1-  Right click on Model project and choose New


2- Choose from left pane "ADF Business Component" , then from list choose  "View Object" and click"OK" button


3-  Enter "DynamicVO" in "Name" and choose "Sql Query" radio button and click "Next" button.


4-  Write in Select field "select * from dual" and click "Next" button until reach Window "Step 8 of 9"


5- Check "Add to Application Module" check box and click "Finish" button.


Implement Changes in Application Module
1- Open application module "AppModule", then open Java tab and check "Generate Application Module Class AppModuleImpl" check box


2- Open AppModuleImpl.java Class and Add the below method for dynamic view object

   public void changeDynamicVoQuery(String sqlStatement) {  
     ViewObject dynamicVO = this.findViewObject("DynamicVO1");  
     dynamicVO.remove();  
     dynamicVO = this.createViewObjectFromQueryStmt("DynamicVO1", sqlStatement);  
     dynamicVO.executeQuery();  
   }  

3- Open "AppModule" then open Java tab and Add changeDynamicVoQuery method to Client Interface



Test Business Component
1- Right click on AppModue in Application navigator and choose Run from drop down list.


2- Right click on AppModule in left pane and choose Show from drop down lsit
     Write "Select * from Emp" in sqlStatement parameter
      Click on Execute button, The result will be Success .


3- Click double click on DynamicVO1 in left pane, it will display the data of DynamicVO and display data which I entered "Select * from Emp" before not "Select * from dual" that was used in design time of view object. 


To use dynamic view objects in ADF Faces, you should use ADF Dynamic Table or ADF Dynamic Form.