Flipkart Search

Showing posts with label adf. Show all posts
Showing posts with label adf. Show all posts

Tuesday, 27 January 2015

Precaution while using javascript in a page fragment or in ADF region

Don't include javascript in the page Fragment just after the jsp:root tag . It will cause undesired effects if this page is navigated from somewhere else.
This will be a wrong approach for a jsff page
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1"
          xmlns:af="http://xmlns.oracle.com/adf/faces/rich"
          xmlns:f="http://java.sun.com/jsf/core">
  <af:resource type="javascript" source="/js/custom.js"/>

The right approach is to include this resource component inside a  container component . Like this
<af:panelFormLayout>
  <af:resource type="javascript" source="/js/custom.js"/>
</af:panelFormLayout> 

Tuesday, 13 January 2015

ADF Performance Tuning part-1 - Production tuning


  1. animation-enabled=false in trinidad-config.xml file
  2. in web.xml file do the following changes if not done already
    1. oracle.adf.view.rich.automation.ENABLE=false
    2. oracle.adf.view.rich.ASSERT_ENABLED=false
    3. org.apache.myfaces.trinidad.CHECK_FILE_MODIFICATION=false
    4.  org.apache.myfaces.trinidad.COMPRESS_VIEW_STATES=true
    5. org.apache.myfaces.trinidad.DEBUG_JAVASCRIPT=false
    6. org.apache.myfaces.trinidad.DISABLE_CONTENT_COMPRESSION=false
    7. oracle.adf.view.rich.libraryPartitioning.DISABLED=false 
    8. oracle.adf.view.rich.LOGGER_LEVEL=false
    9. javax.faces.STATE_SAVING_METHOD=client 
    10. oracle.adf.view.rich.versionString.HIDDEN=true

  3.  Use the ADFLogger
  4. Don't use System.out.* or System.err.* - These have major impact on performance
  5. Remove commented out code
  6. Do not import view or controller classes
  7. Close callableStatement, preparedStatements and RowSetIterators
  8. Use application module JDBC data source only not  JDBC URLs.
  9. Run with Enable Application Module pooling on for production .
  10. Define at least one entity object key attribute per entity object.
  11.  Ensure entity object UI Hints and messages are internationalized
  12. Avoid read only view objects as far as possible
  13. Use view criteria over editing view object where clauses
  14. Never use view object select *
  15. Limit custom code in bean accessors -ie. in getters and setters
  16. Use beans only defined in the task flow for reuse 
  17. Avoid applicationScope and sessionScope variables
  18. Define applicationScope and sessionScope beans in adfc-config.xml
  19. Only create backing beans when actually needed, do not bind unnecessary component references into backing beans.
  20. Avoid long component ID lengths.
  21. Avoid unnecessary use of clientComponent=true
  22. Use rendered=false over visible=false wherever possible.
  23. Never rely on UI side validation.
  24. Avoid inline page/fragment JavaScript and CSS
  25. Manual tests for UIs should include stretch / shrink behavior.
  26. Manual tests for UIs should include changing font size[Zoom-in and Zoom-out testing]
  27. url.rewriting.enabled should be false in weblogic.xml
  28. Make sure jbo.debugoutput  is disabled for production
  29. Make HA available. Add this entry in adf-config.xml file
  <adf-controller-config xmlns="http://xmlns.oracle.com/adf/controller/config">
    <adf-scope-ha-support>true</adf-scope-ha-support>
  </adf-controller-config>



Monday, 22 December 2014

Insert new row at the end of an ADF Table

In some of case you may want to insert a new row at the end of the table then this method will come handy.

 public String CreateInsert() { 
DCBindingContainer bindings = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
        DCIteratorBinding dcIterBind =
            (DCIteratorBinding)bindings.get("EmployeeView1Iterator");
        Row newRow = dcIterBind.getViewObject().createRow();
        newRow.setNewRowState(Row.STATUS_INITIALIZED);
        ViewObject vo = dcIterBind.getViewObject();
        vo.last();
        // to insert row at the end of the table
        vo.next();
        vo.insertRow(newRow);
        return null; 

}

Wednesday, 26 November 2014

JSF Lifecycle in short

  1. JSF Restore View: First phase receives the page request from JSF servlet and attempts to find and restore server side components state (A set of server side memory objects that builds the server side hierarchical page structure.). If view can't found as identified by requested view id , a new view is created on the server and the current page's view is stored in FacesContext static object.
  2. Apply request values: The requested values are read and converted to the data type requested by underlying model attributes. The values are accessed from UI components submitted values and passed to local value. When an input component's immediate attribute is set to true, its component validation is performed and component's listeners are executed within this phase. This is one of two phases in which page navigation can occur.
  3. Process Validation: Components are validated for missing data. At the end of this phase value change events are fired.
  4. Update Model Values: Model is updated with the validated value of UI components local values. Then local values of UI components are discarded.
  5. Invoke Application: During this phase , all application level events such as Form Submits are executed. This phase also executes a view layer logic that is stored in action listeners. Page navigation can occur in this phase.
  6. Render Response: Prepares the page view for display on client (Browser). If page view is called for first time, then restore view phase directly passed control to this phase.

Wednesday, 2 July 2014

working with ADF af:inputListOfValues

By default this component will provide an editable inputText , where user can edit value . In some cases we don't want to give this functionality, we just want to give functionality to select the values.
for this we have to make
editMode="select"

Thursday, 22 May 2014

How to make Appmodule service interface

Exposing Appmodule's VO as a webservice is pretty easy in Oracle ADF. It can be achieved very quickly
Here are the steps:
  1.  Open the Appmodule and go to ServiceInterface link.
  2. Before creating the ServiceInterface you can also create your custom methods exposed to AM. These will be also converted to webservices.
  3. Now click on + icon in the ServiceInterface tab of AM.
  4. Custom methods exposed to AM will be displayed here as the Service
    Custom methods. Expose these if you want to.
  5. Now go to Service View Instances tab to expose your VOs to the webservices.
  6. Now you are ready to deploy this AM service interface to your server. Follow the deployment steps as follows:-
  7. Go to your model- >right click-> Deployment profiles->Business Components Service interface-> give a meaning full profile name.
  8. Now go to Application properties ->Deployment->Edit the ear-> Application Assembly->Model->Check only MiddleTier[Uncheck the common].
  9. Click Ok and deploy the ear to your server.
  10. Don't forget to add yourAppModuleNameService?wsdl after the model context-root

Monday, 5 May 2014

Useful methods in Oracle ADF. Part -1

1. Getting the VO

a.)  DCBindingContainer dcBindings = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
            DCIteratorBinding dcIterBind = (DCIteratorBinding)dcBindings.get("VO1Iterator");  //VO1Iterator define in page def
            ViewObject vo = dcIterBind.getViewObject();
b.) AppModuleImpl amImpl= getApplicationModuleImpl();

     ViewObject vo=  amImpl.getVO();

2. Getting the Application module
a.)
ApplicationModule am=vo.getApplicationModule();
b.)
        FacesContext fc = FacesContext.getCurrentInstance();
        ValueBinding vb = fc.getApplication().createValueBinding("#{data}");
        BindingContext bc = (BindingContext)vb.getValue(fc);
        DCDataControl dc = bc.findDataControl("AppModuleDataControl");
        PublicPortalAppModuleImpl am = (PublicPortalAppModuleImpl)dc.getDataProvider();
3. Row count of a table
        RowSetIterator invoiceRsItr = dcIterBind.getRowSetIterator();
        System.out.println("invoiceRsItr.invoiceRsItr.getRowCount(): " +
                           invoiceRsItr.getRowCount()); 

4. Get URL parameter value
  public static String getURLParamVal(String pv_strParamerName) {
    HttpServletRequest objHttpServletRequest = (HttpServletRequest)getFacesContext().getExternalContext().getRequest();
    return objHttpServletRequest.getParameter(pv_strParamerName);
  }

5. Get operationBinding e.g.- RollBack , Commit etc
      public static OperationBinding getOperBinding(String operationName)
      {
      OperationBinding operBind=null;
      FacesContext fc = FacesContext.getCurrentInstance();
      ValueBinding vb = fc.getApplication().createValueBinding("#{bindings}");
      DCBindingContainer bindingContainer = (DCBindingContainer)vb.getValue(fc);
      oper = (OperationBinding)bindingContainer.getOperationBinding(operation);
      return operBind;
      } 

6. Get the selected rows for ADF table
      a.)  DCBindingContainer dcBindings =(DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
        DCIteratorBinding dcIterBind =
            (DCIteratorBinding)dcBindings.get("EmployeesView1Iterator");
        RowSetIterator invoiceRsItr = dcIterBind.getRowSetIterator();
        RowKeySet rwkset1 = tableBind.getSelectedRowKeys();
        Iterator iter=rwkset1.iterator();
        Row row=null;
        while (iter.hasNext()) {
            Key key=(Key)((List)iter.next()).get(0);
            System.out.println("key "+key);
            row =
        invoiceRsItr.getRow(key);
            System.out.println("Email Selected-->" +
                               row.getAttribute("Email"));
        } 

Note: HR schema's employee table is used, tableBind is the binding of the UI adf table
b.)   
        Iterator iter = tableBind.getSelectedRowKeys().iterator();
        while (iter.hasNext()) {
            Object key= iter.next();
            tableBind.setRowKey(key);
            FacesCtrlHierNodeBinding rw = (FacesCtrlHierNodeBinding)tableBind.getRowData();
            System.out.println("Invoice Selected-->" +
                               rw.getAttribute("Email"));
            }

7. Selecting all rows of the table by a booleanCheckBox 

    public static void checkUncheckAll(String dcIteratorName, String rowName,
                                 String checkBoxVal) {
        DCBindingContainer dcBindings =
            (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
        DCIteratorBinding dcIterBind =
            (DCIteratorBinding)dcBindings.get(dcIteratorName);
        RowSetIterator rsetIter = dcIterBind.getRowSetIterator();
        Row rw = null;
        boolean isFirst = true;
        while (rsetIter.hasNext()) {
            if (isFirst) {
                rw = rsetIter.first();
                isFirst = false;
            } else {
                rw = rsetIter.next();
            }
            rw.setAttribute(rowName, checkBoxVal);
        }
       // rsetIter.reset();    //reset to start the Iterator all over
        rsetIter.closeRowSetIterator();  //always remember to closeit-think it as resultset
    } 


Note:  dcIteratorName- name of VO iterator from Page Binding,VO column which has be implemented as checkBox,checkbox value-Boolean or Yes/No depending upon your logic
 8. Get the name of VOs exposed to the particular am
       String vonames[]= vo.getApplicationModule().getViewObjectNames();
        for (int i=0;i<vonames.length;i++){
            System.out.println(vonames[i]);
        }

Friday, 4 April 2014

ADF javaScript / JS Hacks

1. Using JS in a jsff page
jsff doesn't usually load the js when the af:resource tag is embeded just after jsp:root tag.
To make it work add af:resource inside a formLayout or panelGroupLayout.
            <af:panelGroupLayout>
                      <af:resource type="javascript">
                           function fnc(evt){ ... }
                      </af:resource>
            </af:panelGroupLayout>

more detailed info can be found at
https://blogs.oracle.com/jdevotnharvest/entry/gotcha_when_using_javascript_in

ADF CSS hacks

1. Changing default icon for ADF input text error 
          af|message::error-icon{
                 content:url(/adf/images/error.gif);
                  }

2.

Monday, 31 March 2014

Custom Export to Excel in functionality in Oracle ADF

    public static void exportHtmlTableToExcel(DCIteratorBinding customVO1Iterator) throws IOException {

                String filename = "ExportedExcel.csv";

        customVO1Iterator.setRangeSize(4000);

        //Setup the output

        String contentType = "application/vnd.ms-excel";
        FacesContext fc = FacesContext.getCurrentInstance();
        HttpServletResponse response =
            (HttpServletResponse)fc.getExternalContext().getResponse();
        response.setHeader("Content-disposition",
                           "attachment; filename=" + filename);

        response.setContentType(contentType);
        PrintWriter out = response.getWriter();
        RowSetIterator rsi = customVO1Iterator.getRowSetIterator();
        //    Get the Headers
        String[] attNames = rsi.getRowAtRangeIndex(0).getAttributeNames();

        for (int i = 0; i < attNames.length; i++) {
            if (i > 0)
                out.print(",");
            out.print(attNames[i]);

        }
        out.println();
//Setting the first row data ,was creating problem in my application-- so called reset
                rsi.reset();
        Boolean isFirst = true;
        while (rsi.hasNext()) {
            Row currentRow = null;
            if (isFirst) {
                currentRow = rsi.first();
                isFirst = false;
            } else {
                currentRow = rsi.next();
            }
            if (currentRow != null) {
                Object[] attValues = currentRow.getAttributeValues();
                for (int j = 0; j < attValues.length; j++) {
                    if (j > 0)
                        out.print(",");
                    if (attValues[j] != null)
                        out.print("\"" + attValues[j] + "\"");
                }

            }
            out.println();
        }
        out.close();

        fc.responseComplete();

        customVO1Iterator.setRangeSize(30);

    }

Wednesday, 5 February 2014

Controlling ADF loopback Script

This code controls the ADF loopback script to run on each new window opened, whether its a ADF popup or browser popup.




<context-param>
    <param-name>
        oracle.adf.view.rich.newWindowDetect.OPTIONS
   </param-name>
    <param-value>off</param-value>
  </context-param>

Thursday, 26 December 2013

Normal Pop up implementation in ADF

import org.apache.myfaces.trinidad.util.Service;


FacesContext fctx=FacesContext.getCurrentInstance();
       ExternalContext ectx=fctx.getExternalContext();
//      ectx.redirect("test1.jspx"); // to open in same tab
       ExtendedRenderKitService erks =
       Service.getService(fctx.getRenderKit(), ExtendedRenderKitService.class);
       String url = "window.open('" + "
reports.jspx" + "','\"_self\"','\"toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=600,height=500\"');";
       erks.addScript(FacesContext.getCurrentInstance(), url);
       ///code to open reports in pop up///

Friday, 6 September 2013

truncate output text or see more implementation - ADF output text tutorial-11

Some time we have requirement to show only a fix length of text in UI and show remaining text on demand.Oracle ADF provides this functionality out of box.
In the property of OutputText we can find truncate at
 truncateAt=10

It truncates the text at 10, or it can be decided by an EL or java method return


In the above example text is  truncated on 10th letter and then ... is appended to show there is more text.Hovering the mouse above text will show the whole content.

Sunday, 25 August 2013

getting the DB connection from Weblogic datasource / JNDI

If you have any java/J2ee/ADF project deployed to a weblogic server and you have already created data source for DB connection. You can also get the DB connection in the java code for any specific task.
So here it goes.

public static Connection getConnection(String dsName) throws NamingException,
SQLException {
Connection con = null;
DataSource datasource = null;

Context initialContext = new InitialContext();
if (initialContext == null) {
}
datasource = (DataSource)initialContext.lookup(dsName);
if (datasource != null) {
con = datasource.getConnection();
} else {
System.out.println("Failed to lookup datasource.");
}
return con;
}


Remember this will create a new DB connection. So after getting the job done make sure you close this connection

Wednesday, 14 August 2013

ADF Custom validators for input text

ADF is very rich in providing validations out of the box whether client Side or Server Side.
Its safe to provide server side validations as well so that no can escape the validations by turning off js.
Here are the some default validators provided by ADF.
1.  ByteLengthValidator
2. DateTimeRangeValidator
3. DateRestrictionValidator
4. DoubleRangeValidator
5. LengthValidator
6. LongRangeValidator
7. RegExpValidator

Let's start making some custom Validators. I am starting with an EmailValidator
Make a Validator Class.

package com.rk.validator;


import java.io.Serializable;


import java.util.regex.Matcher;

import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;


public class EmailValidator implements Serializable, Validator {


    public EmailValidator() {
        super();
    }

    public void validate(FacesContext facesContext, UIComponent uiComponent,
                         Object object) {
        String value = (String)object;
        if ((value == null) || value.length() == 0) {
            System.out.println("null value found");
            return;
            //System.out.println("null value found");
        }
        //String expression="^[\\\\w\\\\-]([\\\\.\\\\w])+[\\\\w]+@([\\\\w\\\\-]+\\\\.)+[A-Z]{2,4}$";
        String expression =
            "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
        CharSequence inputstr = value;
        Pattern pattern =
            Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(inputstr);
        if (!matcher.matches()) {
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                                          "Enter the proper Email Id",
                                                          null));
        }

    }
}

....................................
Now go to faces-config.xml and open validators tab give a meaningfull Id like EmailValidator and classname
in this case it should be com.rk.validator.EmailValidator

and the input file just write
<af:inputText label="Enter EmailID" id="it1" autoSubmit="true">
<f:validator validatorid="EmailValidator"/>
</af:inputText>

And you are done.

Saturday, 20 April 2013

logout in oracle ADF / expiring session in ADF

One of the way of logging out user is ::

public String logout() throws IOException {
    ExternalContext ectx=FacesContext.getCurrentInstance().getExternalContext();
HttpServletResponse resp = (HttpServletResponse)ectx.getResponse();
HttpSession sess = (HttpSession)ectx.getSession(false);
sess.invalidate();
  resp.sendRedirect("login.jspx");
return null;
}

Sunday, 3 March 2013

get user's details / Browser's details in Oracle ADF

        RequestContext rCtx = RequestContext.getCurrentInstance();
        FacesContext fctx=FacesContext.getCurrentInstance();
        Agent agnt = rCtx.getAgent();
  1.         //Get user's Browser's engine name
        String browser = agnt.getAgentName();

     2.   //Get user's Browser's engine version
        String browser_version = agnt.getAgentVersion();

    3. //Get user's IP address
        String userIpAddress =                      ((HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest()).getRemoteAddr();
     4.   //Get user's Platform
        String platform = agnt.getPlatformName();
      
      5. //Get user's Platform's version
        String platformVersion = agnt.getPlatformVersion();
        Map reqHeader=
FacesContext.getCurrentInstance().getExternalContext().getRequestHeaderMap();
     6. // Get the User agent
 System.out.println(reqHeader.get("User-Agent"));

Sunday, 25 November 2012

Static list in ADF the other way

The manage bean property of ADF can also provide the static list without a actual managed Bean{Interesting ??}. Let's do with an Example.
Inside your adfc-config.xml or your page-flow.xml register this list as below

  <managed-bean id="__3">
        <managed-bean-name>StaticBean</managed-bean-name>
        <managed-bean-class>java.util.HashMap</managed-bean-class>
        <managed-bean-scope>application</managed-bean-scope>
        <map-entries>
            <map-entry>
                <key>rahulkaitian</key>
                <value>http://rahulkaitian.blogspot.in</value>
            </map-entry>
            <map-entry>
                <key>rahulkumar07</key>
                <value>http://rahulkumar07.blogspot.in</value>
            </map-entry>
        </map-entries>
    </managed-bean>







and access the pair  in EL as #{StaticBean['rahulkaitian']}

Sunday, 15 April 2012

Showing User Specific Table data in Adf - Part 1

This is a very normal use case where a user has to see his own data. We usually do it by saving userdata in DB according to some UserId{Like emailId } or some specific number or anything...For this tutorial you should have a table with user specific data....For this example I took Employee table of HR schema .....
There are two methods to do this.....
1. Execute with Params{With Bind Variables}
2. ViewObject Implementation Class
In Part 1. I will how to achieve this goal by Execute with Params{With Bind Variables}...
Steps:::
1. First create a desired VO and Bind a variable to it.{This should be the your userId which can be anything}
2. Now give a where clause to your VO which binds your bind Variable

3. Now create a task-flow{or a jspx page}......I prefer taskflow to ensure re usability...

4. Now add a view to it ..and make sure you select document tpye: JSP XML


5. Now go to datacontrol and expand your employee collection and go to operation section and drag and drop ExecuteWithParams to your page as an ADF parameter Form 
6. Now drag and drop your table on the same jsff page see above..
7. Now go to jsff page Bindings and then go to structure window{left below corner}and you can see Executables . Now right click on Executables->Insert Inside executables->invoke Action. Give any string as id and Binds as ExecuteWithParams . Go to its property and make refresh:always {Note: click on the image below for better visibility}



8. Now again go to binding tab of the jsff page{you must be there already }. See the cursor{Means edit the bindings->ExecuteWithParams

9. Now you will see the dialog as below...go to value -> show El  Expression Builder

10. Now delete the existing text and map it to security context user name...
11. Now you can delete the adf parameter form in the jsff page{So that user can't view it}.. or you can make the adf panel form layout render false which contains the ExecuteWithParams form field and Button

12. Now you have to give a login page to the user so that he can give his user name and password to login and see his data...In adf this is very simple...Go to Application->Secure->Configure ADF security...

Follow the next screens as it is--



13. Now click next-next or finish and open Application Resources->Descriptors->META-INF->jazn-data.xml and add your user and give userId as Name
14. Add an application role and add the existing user to this role...

15. Now go to resource Grants tab then Resource Type->Task Flow and give your task grant to application rule..

16. Now create a blank jspx page and drop adf page flow into it as region
17. Now grant this jspx to the same application role....
18. Now run your application and Enjoy
see the sample..earlier
 And now with ExecuteWithParams