Please disable your adblock and script blockers to view this page

Search this blog

Showing posts with label Custom. Show all posts
Showing posts with label Custom. Show all posts

Tuesday 5 January 2016

Get selected slice of dvt:pieChart using custom selection listener in ADF

First of all wishing a very Happy New Year to all of you, New Year is like a blank page , fill it with happiness and good memories


This post is about a simple requirement - How to get selected slice value of dvt:pieChart ?
So for this we have to create a custom selection Listener in managed bean that will be called whenever user selects any slice of pieChart
If you see documentation of pieChart it tells about two properties -

Saturday 8 August 2015

Set ADF Faces Component properties using custom javascript

This post is about using JavaScript in ADF Faces to change default properties , sometimes using JavaScript can make task easier and all scenarios covered in this post are based on very common requirement. One important point is - set clientComponent property of component to true when using JavaScript on that
Why this is important ? (Check what docs say)

whether a client-side component will be generated. A component may be generated whether or not this flag is set, but if client Javascript requires the component object, this must be set to true to guarantee the component's presence. Client component objects that are generated today by default may not be present in the future; setting this flag is the only way to guarantee a component's presence, and clients cannot rely on implicit behavior. However, there is a performance cost to setting this flag, so clients should avoid turning on client components unless absolutely necessary

Read more about clientComponent property - Understanding ADF Faces clientComponent attribute


Set panel group layout properties-


Use this JavaScript function to set panel group layout's layout and other properties

 <!--Function to set panelGroupLayout properties-->
              function changeGroupLayout(evt) {
                  var pgl = AdfPage.PAGE.findComponent('pgl1');
                  pgl.setProperty("layout", "vertical");
                  pgl.setProperty("inlineStyle", "background-color:red");
              }

I have called this function using client listener on a image that is inside my panel group layout

<af:panelGroupLayout id="pgl1" layout="horizontal" clientComponent="true">
                    <af:image source="#{resource['images:5-10.jpg']}" id="i1" inlineStyle="width:250px;height:200px;"/>
                    <af:image source="#{resource['images:13.jpg']}" id="i2" inlineStyle="width:250px;height:200px;">
                        <af:clientListener method="changeGroupLayout" type="dblClick"/>
                    </af:image>
                    <af:image source="#{resource['images:1.jpg']}" id="i3" inlineStyle="width:250px;height:200px;"/>
                </af:panelGroupLayout>

Initially group layout is horizontal-




After executing JavaScript on double click on second image-



Set input component property (inlineStyle, contentStyle, value etc)-


This function is same as previous one , this function sets value in input text , changes it's contentStyle

<!--Function to set af:inputText properties-->
              function changeInputText(evt) {
                  var iText = AdfPage.PAGE.findComponent('it1');
                  iText.setProperty("value", "Ashish Awasthi");
                  iText.setProperty("contentStyle", "background-color:red;color:white;font-weight:bold;");

              }

Called this function on double click event in inputText-

<af:inputText label="Label 1" id="it1" clientComponent="true" unsecure="disabled">
                        <af:clientListener method="changeInputText" type="dblClick"/>
              
                    </af:inputText>


Output is like this-
 on double click inside inputText

In same way we can set disabled property of component . It is a secure property of component , that should not be changed from a client side event normally but if this is a requirement then we have to set disabled in unsecure property of input component. Only disable property is supported as of now
Read more about this property -<af:inputText>


Set panelSplitter width according to browser window width-


This JavaScript function divides af:panelSplitter in equal parts to fit in browser

 <!--Function to set panel Splitter position-->
              function changePanelSpliterPosition(evt) {
                  var width = window.innerWidth;
                  var ps = AdfPage.PAGE.findComponent('ps1');
                  ps.setProperty("splitterPosition", width / 2);
              }

In same way try setting other properties of different components. Soon i will update this post with some more JavaScript functions and examples

Cheers :)  Happy Learning

Monday 9 February 2015

Custom selection listener for af:listView, Invoke selectionListener programmatically

In the last post (Better UI for data collection using af:listView, Enable selection in ADF Faces List component ) about af:listView, we saw that how can we present data collection in a better way using af:listView and enable selection using EL (same as used for af:table)

Now in this post i will describe about defining custom selection listener for af:listView
Suppose you have to do some task on selection of an item in list other than making it current row, for this you have to override default selection listener and define own custom selection listener in managed bean
So next step is to define a method in managed bean for handling selection event of af:list view



  • Select af:listView, goto properties and click on edit menu of selectionListener property and create a method in managed bean



  • now see what we have to do in custom selection listener, first invoke default selection listener EL (#{bindings.Departments1.collectionModel.makeCurrent}) to make selected row as current and then get current row from iterator as selected row is now current row
    See the managed bean code -

  • //Import these packages
    
    import javax.el.ELContext;
    import javax.el.ExpressionFactory;
    import javax.el.MethodExpression;
    import javax.el.ValueExpression;
    
    import javax.faces.application.FacesMessage;
    import javax.faces.context.FacesContext;
    
    import oracle.jbo.Row;
    
    import org.apache.myfaces.trinidad.event.SelectionEvent;   
    
    
     /**
         * Programmatic invocation of a method that an EL evaluates to.
         *
         * @param el EL of the method to invoke
         * @param paramTypes Array of Class defining the types of the parameters
         * @param params Array of Object defining the values of the parametrs
         * @return Object that the method returns
         */
        public static Object invokeEL(String el, Class[] paramTypes, Object[] params) {
            FacesContext facesContext = FacesContext.getCurrentInstance();
            ELContext elContext = facesContext.getELContext();
            ExpressionFactory expressionFactory = facesContext.getApplication().getExpressionFactory();
            MethodExpression exp = expressionFactory.createMethodExpression(elContext, el, Object.class, paramTypes);
    
            return exp.invoke(elContext, params);
        }
    
        /**
         * Programmatic evaluation of EL.
         *
         * @param el EL to evaluate
         * @return Result of the evaluation
         */
        public static Object evaluateEL(String el) {
            FacesContext facesContext = FacesContext.getCurrentInstance();
            ELContext elContext = facesContext.getELContext();
            ExpressionFactory expressionFactory = facesContext.getApplication().getExpressionFactory();
            ValueExpression exp = expressionFactory.createValueExpression(elContext, el, Object.class);
    
            return exp.getValue(elContext);
        }
    
        /**Custome Selection Listener for af:listView
         * @param selectionEvent
         */
        public void listSelectionListener(SelectionEvent selectionEvent) {
            //invoke this EL to set selected row as current row, if it is not invoked then first row will be current row
            invokeEL("#{bindings.Departments1.collectionModel.makeCurrent}", new Class[] { SelectionEvent.class }, new Object[] {
                     selectionEvent });
            // get the selected row , by this you can get any attribute of that row
            Row selectedRow = (Row) evaluateEL("#{bindings.Departments1Iterator.currentRow}");
            FacesMessage msg = new FacesMessage(selectedRow.getAttribute("DepartmentName").toString());
            msg.setSeverity(FacesMessage.SEVERITY_INFO);
            FacesContext.getCurrentInstance().addMessage(null, msg);
        }
    

  • Now run application and check

Download Sample ADF Application here
Thanks , Happy Learning :)

Wednesday 24 July 2013

Implementing custom search form in ADF programmatically (Without using af:query)

Sometimes we need to implement custom search instead of using adf query component.
To implement custom search form , i have used a quite beautiful way to handle search and reset functionality for a View Object.
In this post i am taking Employees Table (Default HR Schema) to search and reset af:table.

  • First create a Fusion Web Application and create model (EO,VO and AM) using Employees table
  • Now suppose we have to search on 4 fields (EmployeeId, FirstName, Email, Salary) , so for this i have created a new read only ViewObject from dual
  •  This VO from dual is created to be used as Search form on page
  •  Now to make search effective on Employees VO , i have created 4 bind variable for corresponding fields in Employees ViewObject



  •  Now i have created a ViewCriteria using these 4 bind variables to re-query ViewObject  data
  •  This ViewCriteria will be executed each time when value of bind variable is changed, now this is the time to set value of bind variables, so i have dragged dual vo as a form on page, and added 2 button for Search and Reset
  •  To View Search Result , Employees Table is there on page
  •  Now to get value from Form Field to bean , i have created binding for all 4 fields in bean
  •  Now i have created ActionListener for Search button- in this code i have get value from page using component bindings and passed in Employees ViewObject's bind variable in order to execute viewCriteria.

  •     public void searchButton(ActionEvent actionEvent) {
            searchAMImpl am = (searchAMImpl)resolvElDC("searchAMDataControl");
            ViewObject empVo = am.getEmployees1();
            empVo.setNamedWhereClauseParam("EmpIdBind", empIdPgBind.getValue());
            empVo.setNamedWhereClauseParam("FirstNmBind", firstNmPgBind.getValue());
            empVo.setNamedWhereClauseParam("EmailBind", emailPgBind.getValue());
            empVo.setNamedWhereClauseParam("SalaryBind", salaryPgBind.getValue());
            empVo.executeQuery();
        }
    

  • Once value is set in bind variable , view criteria is executed and Search result will be shown in resultant table- Run your application and see
  • To reset values in table and search form, see the managed bean code of Reset button

  •     public void resetButton(ActionEvent actionEvent) {
            searchAMImpl am = (searchAMImpl)resolvElDC("searchAMDataControl");
            ViewObject empVo = am.getEmployees1();
            ViewObject attrVo=am.getattr1();
            empVo.setNamedWhereClauseParam("EmpIdBind", null);
            empVo.setNamedWhereClauseParam("FirstNmBind", null);
            empVo.setNamedWhereClauseParam("EmailBind", null);
            empVo.setNamedWhereClauseParam("SalaryBind", null);
            empVo.executeQuery();
            attrVo.executeQuery();
          
        }
    

  • Click on reset button and page value are set to default

  • This is how we can implement custom search using ADF components, you can apply validations, auto suggest feature etc while using this custom search
          Cheers :-)  Download Sample App

Thursday 30 May 2013

Add Custom Flash Chat in Oracle ADF Application

In this tutorial i am going to show that how can you add a custom flash chat in your ADF application, and use it to chat with friends.
this is very much simple, as no code required to do this.
  • Go to http://www.everywherechat.com/ , this site provides free custom flash chat rooms, get html code of your custom chat from here
  • Create an html page using that code




  • <html>
    <body>
    <!-- Begin Everywherechat Room Code -->
        
          <br />
         <script src="http://www.everywherechat.com/e.php?defaultRoom=Lobby&roomList=true&fontSize=12&width=600&height=500&theme=night"></script> 
    
    <!-- End Everywherechat Room Code --> 
    </body>
    </html>
    

  • Now create a Fusion Web Application and create a page in it, call this HTML page in an inlineFrame (af:inlineFrame)

  • <?xml version='1.0' encoding='UTF-8'?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1" xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
      <af:panelGroupLayout id="pgl1">
        <af:inlineFrame id="if1" source="/chat.html" inlineStyle="height:700px;width:700px;"/>
      </af:panelGroupLayout>
    </jsp:root>
    

  • Now Run your application and see your flash chat room is ready - Happy Coding

    Download Sample Application-Sample ADF Application

Monday 13 May 2013

Phone Number custom validation using Regular Expression in ADF and Java




Regular Expression (REGEX) is the best method to validate phone number. emailId, name in Java.
Here I have written this validation code for phone number using Regular Expression and Java code to use this in an Oracle ADF Application.





public void phoneNoValidator(FacesContext facesContext, UIComponent uIComponent, Object object) {
        String msg2 = "";
        if (object != null) {
            String phnNo = object.toString();
            int openB = 0;
            int closeB = 0;
            boolean closeFg = false;
            char[] xx = phnNo.toCharArray();
            for (char c : xx) {
                if (c == '(') {
                    openB = openB + 1;
                } else if (c == ')') {
                    closeB = closeB + 1;
                }

                if (closeB > openB) {
                    closeFg = true; //closed brackets will not be more than open brackets at any given time.
                }
            }
            //if openB=0 then no. of closing and opening brackets equal || opening bracket must always come before closing brackets
            //closing brackets must not come before first occurrence of openning bracket
            if (openB != closeB || closeFg == true || (phnNo.lastIndexOf("(") > phnNo.lastIndexOf(")")) ||
                (phnNo.indexOf(")") < phnNo.indexOf("("))) {
                msg2 = "Brackets not closed properly.";
                FacesMessage message2 = new FacesMessage(msg2);
                message2.setSeverity(FacesMessage.SEVERITY_ERROR);
                throw new ValidatorException(message2);
            }
            if (phnNo.contains("()")) {
                msg2 = "Empty Brackets are not allowed.";
                FacesMessage message2 = new FacesMessage(msg2);
                message2.setSeverity(FacesMessage.SEVERITY_ERROR);
                throw new ValidatorException(message2);
            }
            if (phnNo.contains("(.") || phnNo.contains("(-") || phnNo.contains("-)")) {
                msg2 = "Invalid Phone Number.Check content inside brackets.";
                FacesMessage message2 = new FacesMessage(msg2);
                message2.setSeverity(FacesMessage.SEVERITY_ERROR);
                throw new ValidatorException(message2);
            }

            openB = 0;
            closeB = 0;
            closeFg = false;
            //check for valid language name.Allowed- brackets,dots,hyphen

            String expression = "([0-9\\-\\+\\(\\)]+)";
            CharSequence inputStr = phnNo;
            Pattern pattern = Pattern.compile(expression);
            Matcher matcher = pattern.matcher(inputStr);
            String error = "Invalid Phone Number";
            System.out.println("Index of plus is--->" + phnNo.lastIndexOf("+"));
            System.out.println("Bracket index--->" + phnNo.charAt(0));

            if (matcher.matches()) {
                if (phnNo.contains("++") || phnNo.contains("--")) {
                    throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, error,
                                                                  "Can not contain two hyphen(--) or plus(++)"));
                } else if (phnNo.lastIndexOf("+") > 1) {
                    throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, error,
                                                                  "Plus sign should be in proper place"));
                } else if (phnNo.lastIndexOf("+") == 1 && phnNo.charAt(0) != '(') {
                    throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, error,
                                                                  "Plus sign should be in proper place"));
                } else if (phnNo.startsWith(" ") || phnNo.endsWith(" ")) {
                    throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, error,
                                                                  "Space Not allowed at start and end"));
                }

            } else {
                throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, error,
                                                              "Only numeric character,+,() and - allowed"));
            }

        }
    }


Cheers:) Happy Learning

Wednesday 2 January 2013

Invoke ADF Table Selection Listener, custom selection listener for af:table


Sometimes we need to define our own selection listener for adf table, or we have to perform some operation on row selection in af:table.

We can do this by defining custom selection listener for table in Managed bean.
In this tutorial i am showing a popup on table row selection , Here i am using Employees table of HR Schema
  • Prepare model and ViewController for Employees table and drag table in your page. Now select table and go to property Inspector , you will see its default selection listener 

Selection Listener of af:table


  • Now define your own (custom) selection listener for this table in your managed bean
Create custom selection listener in managed bean to handle selection event on af:table

  • Now write this code snippet on that custom selection listener,this code invokes its default listener and get the selected row. first you have to invoke its default listener that is
#{bindings.Employees1.collectionModel.makeCurrent}




    public void empTableSelectionListener(SelectionEvent selectionEvent) {
        ADFUtil.invokeEL("#{bindings.Employees1.collectionModel.makeCurrent}", new Class[] {SelectionEvent.class},
                         new Object[] { selectionEvent });
        // get the selected row , by this you can get any attribute of that row
        Row selectedRow =
            (Row)ADFUtil.evaluateEL("#{bindings.Employees1Iterator.currentRow}"); // get the current selected row
        //to show popup, you can write your logic here , what you wanna do
        showPopup(empPopup, true);
    }

  • you have to import these packages in order to invoke selection listener

import org.apache.myfaces.trinidad.event.SelectionEvent;
import org.apache.myfaces.trinidad.render.ExtendedRenderKitService;
import org.apache.myfaces.trinidad.util.Service;


  • In above code snippet ADFUtil is an utility class that contains methods for invoking EL (Expression language), so you have to make a Java class named ADFUtil in same package as bean
import java.util.Map;

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.MethodExpression;
import javax.el.ValueExpression;

import javax.faces.context.FacesContext;

import oracle.adf.model.BindingContext;
import oracle.adf.model.DataControlFrame;


/**
 * Provides various utility methods that are handy to
 * have around when working with ADF.
 */

public class ADFUtil {

/**
* When a bounded task flow manages a transaction (marked as requires-transaction,.
* requires-new-transaction, or requires-existing-transaction), then the
* task flow must issue any commits or rollbacks that are needed. This is
* essentially to keep the state of the transaction that the task flow understands
* in synch with the state of the transaction in the ADFbc layer.
*
* Use this method to issue a commit in the middle of a task flow while staying
* in the task flow.
*/

public static void saveAndContinue() {
Map sessionMap =
FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
BindingContext context =
(BindingContext)sessionMap.get(BindingContext.CONTEXT_ID);
String currentFrameName = context.getCurrentDataControlFrame();
DataControlFrame dcFrame =
context.findDataControlFrame(currentFrameName);

dcFrame.commit();
dcFrame.beginTransaction(null);
}

/**
* Programmatic evaluation of EL.
*
* @param el EL to evaluate
* @return Result of the evaluation
*/

public static Object evaluateEL(String el) {
FacesContext facesContext = FacesContext.getCurrentInstance();
ELContext elContext = facesContext.getELContext();
ExpressionFactory expressionFactory =
facesContext.getApplication().getExpressionFactory();
ValueExpression exp =
expressionFactory.createValueExpression(elContext, el,
Object.class);

return exp.getValue(elContext);
}

/**
* Programmatic invocation of a method that an EL evaluates to.
* The method must not take any parameters.
*
* @param el EL of the method to invoke
* @return Object that the method returns
*/

public static Object invokeEL(String el) {
return invokeEL(el, new Class[0], new Object[0]);
}

/**
* Programmatic invocation of a method that an EL evaluates to.
*
* @param el EL of the method to invoke
* @param paramTypes Array of Class defining the types of the parameters
* @param params Array of Object defining the values of the parametrs
* @return Object that the method returns
*/

public static Object invokeEL(String el, Class[] paramTypes,
Object[] params) {
FacesContext facesContext = FacesContext.getCurrentInstance();
ELContext elContext = facesContext.getELContext();
ExpressionFactory expressionFactory =
facesContext.getApplication().getExpressionFactory();
MethodExpression exp =
expressionFactory.createMethodExpression(elContext, el,
Object.class, paramTypes);

return exp.invoke(elContext, params);
}

/**
* Sets a value into an EL object. Provides similar functionality to
* the <af:setActionListener> tag, except the from is
* not an EL. You can get similar behavior by using the following...

* setEL(to, evaluateEL(from))
*
* @param el EL object to assign a value
* @param val Value to assign
*/

public static void setEL(String el, Object val) {
FacesContext facesContext = FacesContext.getCurrentInstance();
ELContext elContext = facesContext.getELContext();
ExpressionFactory expressionFactory =
facesContext.getApplication().getExpressionFactory();
ValueExpression exp =
expressionFactory.createValueExpression(elContext, el,
Object.class);

exp.setValue(elContext, val);
}
}



Wednesday 21 November 2012

Custom Validator in Oracle ADF (JSF Validator), Email Validation Using Regex

Validation is very important part of any programming language, when we visit any website's registration form it says "This field is mandatory" or "Email id is not valid","Password doesn't match", these all are validations

What is a Validator-
A computer program or piece of code that checks syntax or value of any field according to a predefined condition is called Validator
Validators are used in every programming/scripting language.

How to Use Custom Validator in ADF Forms-
This is not complex to use validator in ADF forms, means in .jsff or in .jspx pages. Suppose we have a field of EmailId on form and we want to add custom email id validator on this field

To add validator in a field follow these steps

  • Select the field in Form
af:inputText to enter email id

  •  Now go to property inspector and Select Validator,it is empty by default
Create Validator method in managed bean
  • Now click on Validator edit in property inspector and create a validator in ManagedBean of taskflow




 
  • It will look like this- Default Custom Validator 
This validator method validates value of inputText

  •  Now we will add custom code to validate EmailId field in this validator

  1.     public void emailValidator(FacesContext facesContext, UIComponent uIComponent, Object object) {
  2.         if(object!=null){
  3.             String name=object.toString();
  4.             String expression="^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
  5.             CharSequence inputStr=name;
  6.             Pattern pattern=Pattern.compile(expression);
  7.             Matcher matcher=pattern.matcher(inputStr);
  8.             String msg="Email is not in Proper Format";
  9.             if(matcher.matches()){
  10.                
  11.             }
  12.             else{
  13.                 throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,msg,null));
  14.             }
  15.         }
  16.     }

  • Now when we run this page, we can see validation
Regex to check Email Id format and in case of failure it show validation message