Flipkart Search

Showing posts with label Adf Blogs. Show all posts
Showing posts with label Adf Blogs. Show all posts

Friday, 15 May 2015

Set Initial focus on any ADF UI component

Often developers requires focus on a particular UI component on page load. ADF provides out-of-the-box feature for this problem. All you need is the exact component id of that element.
In this example I will show you how to move cursor to the input box used as a username input. This component was inside a bounded-taskflow exposed in a jspx region.
First the jspx code .

 <af:document id="d1" title="#{sessionScope.pageTitle}" 
partialTriggers="r1" initialFocusId="r1:0:sf1:it1">

This is our login module and now will try to find out its id generated on the webpage by developer tool.
We can now see the actual id of the UI component exposed in browser. It is the same ID we need to put in 
initialFocusId.


Tuesday, 27 January 2015

Using google / custom fonts in the ADF application

In ADF use can use any google font as you used to use default fonts provided by ADF or Webcenter.
Here are the steps.

  1. Register the css file in the page through the af:resource tag
<af:resource type="css" source="http://fonts.googleapis.com/css?family=Lobster"/>

     2. Make an entry in the application's css file.

.inText {
    font-family: 'Lobster', cursive;
    font-size: medium;
}

   3. Put the above styleclass in the component
<af:outputText styleClass="inText " value="Text with google font"
                                         id="ol1"/>


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, 5 January 2015

Useful methods in Oracle ADF part-2

//1. Method to call a flow in taskFlow programatically 


 public static void gotoFlow(String flowName) {
        FacesContext context = FacesContext.getCurrentInstance();
        Application app = context.getApplication();
        NavigationHandler handler = app.getNavigationHandler();
        handler.handleNavigation(context, null, flowName);
    }
//2. Util method to show error and Success Msg
 public static void showMsg(String msgBody, String msgSeverity) {
        FacesMessage fm = new FacesMessage(msgBody);
        if (msgSeverity.equals("info")) {
            fm.setSeverity(FacesMessage.SEVERITY_INFO);
        } else if (msgSeverity.equals("warn")) {
            fm.setSeverity(FacesMessage.SEVERITY_WARN);
        } else if (msgSeverity.equals("error")) {
            fm.setSeverity(FacesMessage.SEVERITY_ERROR);
        } else {
            fm.setSeverity(FacesMessage.SEVERITY_FATAL);
        }
        FacesContext fctx = FacesContext.getCurrentInstance();
        fctx.addMessage(null, fm);
    }
//3. Get Cookie value in ADF
 
        public static String getCookieValue(String cookieName) {
        FacesContext fctx = FacesContext.getCurrentInstance();
        ExternalContext ectx = fctx.getExternalContext();
        Map vRequestCookieMap = ectx.getRequestCookieMap();
        Cookie cookie = (Cookie)vRequestCookieMap.get(cookieName);
        if (cookie != null) {
            return cookie.getValue();
        }
        return null;
    }
   
   
//4. Load a jsp or jspx page (redirect to a page)
 
  public static String loadPage(String pageName) {
        FacesContext vFacesContext = FacesContext.getCurrentInstance();
        ExternalContext vExternalContext = vFacesContext.getExternalContext();
        ControllerContext controllerCtx = null;
        controllerCtx = ControllerContext.getInstance();
        String activityURL = controllerCtx.getGlobalViewActivityURL(pageName);
        try {
            vExternalContext.redirect(activityURL.substring(0,
                                                            activityURL.indexOf("?")));
        } catch (IOException e) {
            e.printStackTrace();

        }
        return null;
    }
//5. Initializing the ADFLogger

private static ADFLogger _logger = 
            ADFLogger.createADFLogger(YourClassName.class); 
//6. Clear the ADF table filter
    public static void removeFilter(RichTable tableBind,String processQueryName) {
        FilterableQueryDescriptor queryDescriptor =
            (FilterableQueryDescriptor)tableBind.getFilterModel();
        if (queryDescriptor != null &&
            queryDescriptor.getFilterCriteria() != null) {
            queryDescriptor.getFilterCriteria().clear();
//processQueryName can found in queryListner of table eg:- #{bindings.Employee1Query.processQuery}
            FacesUtils.invokeMethodExpression(processQueryName,
                                              Object.class, QueryEvent.class,
                                              new QueryEvent(tableBind,
                                                             queryDescriptor));
        }
    }
// 7.Implementing like type filter in ADF table filter
public static void likeFilter(RichTable tableBind,String processQueryName) {
        FilterableQueryDescriptor queryDescriptor =
            (FilterableQueryDescriptor)tableBind.getFilterModel();
        if (queryDescriptor != null &&
            queryDescriptor.getFilterCriteria() != null) {
            Map m=queryDescriptor.getFilterCriteria();
           
            Set keys = m.keySet();
           Map modified=new HashMap();
            for (Iterator i = keys.iterator(); i.hasNext();) {
                  String key = (String) i.next();
                  String value = (String) m.get(key);
                if(value!=null && !value.equals("")){
                    value="%"+value+"%";
                   
                }
                    modified.put(key,value);
                  System.out.println(key + " = " + value);
                }
            queryDescriptor.getFilterCriteria().clear();
            FacesUtils.invokeMethodExpression(processQueryName,
                                              Object.class, QueryEvent.class,
                                              new QueryEvent(tableBind,
                                                             queryDescriptor));
            queryDescriptor.setFilterCriteria(modified);
            FacesUtils.invokeMethodExpression(processQueryName,
                                              Object.class, QueryEvent.class,
                                              new QueryEvent(tableBind,
                                                             queryDescriptor));
        }
    }
// 8. Launching / Invoking a PopUp from Bean. [popupBind is binding of popup inside the bean]
RichPopup.PopupHints hints = new RichPopup.PopupHints();
                    popBind.show(hints);

Tuesday, 30 December 2014

Merge two Columns into one column while showing data Seperately

Use case scenario:  You may need to show your two column header as well as data into a single ADF Table column. 
Please refer the below image for use case:

ADF has made this use case very simple.
You have just wrap your existing(required) Columns into a single column and its done.

Here is the required code sample:
 <af:column headerText="Emplyee Name"  id="c5" align="center">
          <af:column headerText="First Name" id="c8">
                     <af:outputText value="F_Name #{vs.index+1} " id="ot6"/>
          </af:column>
          <af:column headerText="Last Name" id="c9">
                    <af:outputText value="L_Name #{vs.index+1}" id="ot5"/>
          </af:column>
 </af:column>

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

Useful shortcut keys for Jdeveloper and Oracle ADF

Here are few Jdeveloper shortcuts that can come handy while development [ mostly for Jdev 12c }
  1. Surround with popUp :  ALT+Shift+Z
  2. System.out.println(); : sop+Ctrl+Enter

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"

Wednesday, 18 June 2014

ADF Custom converter for Input/Output Text

As we have already covered most widely used ADF custom validators , now its time to have some hands on ADF custom converters.

 Let's take simple task of displaying a text in upperCase.
 Here goes the sample code of our class
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

public class UpperCaseConverter implements Converter {
    public UpperCaseConverter() {
        super();
    }
    public String getAsString(FacesContext fc, UIComponent uIComponent, Object  obj) {

    return obj.toString().toUpperCase();

    }

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

    return string.toString().toUpperCase();

    }

    }
Now we will register this class in our faces-config.xml in the converters section.
And we can apply this converter simply by giving its ID.

  <af:inputText value="#{row.bindings.FirstName.inputValue}"
                                label="#{bindings.EmployeesView1.hints.FirstName.label}"
                                required="#{bindings.EmployeesView1.hints.FirstName.mandatory}"
                                columns="#{bindings.EmployeesView1.hints.FirstName.displayWidth}"
                                maximumLength="#{bindings.EmployeesView1.hints.FirstName.precision}"
                                shortDesc="#{bindings.EmployeesView1.hints.FirstName.tooltip}"
                                id="it3" converter="UpperCase"/>       
           

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>

Monday, 3 February 2014

HTML Formatting / Styling in ADF outputText

HTML Formatting in outputText (Escape Attribute)


For applying styling to some of the content, outputText's escape attribute could be used. Example:-

<af:outputText value="&lt;h2>ADF Tips and Tricks&lt;/h2>"/>
<af:outputText value="&lt;h2>ADF Tips and Tricks&lt;/h2>"
               escape="false"/>

Output
<h2>ADF Tips and Tricks</h2>
ADF Tips and Tricks

Note: You should avoid setting the escape attribute to false unless absolutely necessary. outputFormatted  component is more recommended in such cases.


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///