Monday 25 February 2013

Code to find an UI Component in an Oracle ADF Application

## Find an UI Component in the page

Hello all,
There are cases where you have to find a component on Page by id in the bean. Here is the method.


private UIComponent findComponentOnPage(String id){    
    String comp = id;
   //see ADF Code Corner sample #58 to read about the code
//used in the search below
FacesContext fctx = FacesContext.getCurrentInstance();
UIViewRoot root = fctx.getViewRoot();            
   root.invokeOnComponent(fctx,comp,
new ContextCallback(){
      public void invokeContextCallback(FacesContext facesContext,UIComponent uiComponent) {
       lookupComponent = uiComponent;
     }         
  });
return lookupComponent;
}

ADF: Decimal Number validator



## Decimal Number validator


public void Number_validatorDecimal(FacesContext facesContext, UIComponent uIComponent, Object object)
{
       BigDecimal value =(BigDecimal)object;
       if (value == null) {
           return;
       }
       if(value.floatValue()<0.00){
           String error = "Value should be greater than zero.";
           throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, error, null));
       }

   }

Friday 22 February 2013

ADF : Phonenumber validator

## Phonenumber validator


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"));
           }

       }
   }

ADF : Name validator

## Name validator

public void NameValidation_Normal(FacesContext facesContext, UIComponent uIComponent, Object object) {
       String value = (String)object;
       if ((value == null) || value.length() == 0) {
           return;
       }
       

       String expression = "[A-Za-z0-9]*";
       CharSequence inputStr = value;
       Pattern pattern = Pattern.compile(expression);
       Matcher matcher = pattern.matcher(inputStr);
       String error = "Special character not allowed";
       if (matcher.matches()) {
       } else {

           throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, error, null));
       }
   }
























































Thursday 21 February 2013

ADF: Show inline messege

## Show inline messege

public void showMessageButton(ActionEvent actionEvent) {

FacesMessage msg=new FacesMessage("This is a FacesMessage that+
"shows Fatal Error.");
msg.setSeverity(FacesMessage.SEVERITY_FATAL);
FacesContext fctx=FacesContext.getCurrentInstance();
fctx.addMessage(null, msg);

}









ADF: Using groovy expression (sample format)

## Using groovy expression (sample format)

1)When used to calculate many fields of an VO and show the sum in the same VO.

object.getRowSet().sum("Salary")

2)Sample format to use Groovy expression for transient object

CommissionPct==null? Salary:Salary+Salary*CommissionPct
   (Condition)    ?  (When true) : (When false)

Java code for email validation in ADF

## Code for email validation

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

ADF: Code to use popup

## Code to use popup

Note: For using this code, first you have to make binding of the popup which is displayed on your webpage.
And here in the code I have variable pop to bind the popup.



1)showPopup method to call popup
private void showPopup(RichPopup pop, boolean visible) {  
    try {  
      FacesContext context = FacesContext.getCurrentInstance();  
      if (context != null && pop != null) {  
        String popupId = pop.getClientId(context);  
        if (popupId != null) {  
          StringBuilder script = new StringBuilder();  
          script.append("var popup = AdfPage.PAGE.findComponent('").append(popupId).append("'); ");  
          if (visible) {  
            script.append("if (!popup.isPopupVisible()) { ").append("popup.show();}");  
          } else {  
            script.append("if (popup.isPopupVisible()) { ").append("popup.hide();}");  
          }  
          ExtendedRenderKitService erks =  
            Service.getService(context.getRenderKit(), ExtendedRenderKitService.class);  
          erks.addScript(context, script.toString());  
        }  
      }  
    } catch (Exception e) {  
      throw new RuntimeException(e);  
    }  
  }

2)And import these packages

import org.apache.myfaces.trinidad.event.SelectionEvent;
import org.apache.myfaces.trinidad.render.ExtendedRenderKitService;
import org.apache.myfaces.trinidad.util.Service;
import javax.faces.context.FacesContext;

3)Use to show or hide popup in the page
private RichPopup pop;
showPopup(pop, true);

** incase you want to hide the popup, use

showPopup(pop, false);

ADF: Code to use rowIterator

Hi,
Here is the method to use iterator in ADF Applications.

1)To get iterator object populated with the view rows
RowsetIterator itr=view.createRowsetIterator(null);
*dont use view.getIterator
2)To iterate within the iterator
itr.hasNext();
its.next();

If you have any questions regarding this or in ADF. I will be happy if i can help. :)

ADF: Code to validate duplicate record in Java Bean.

Hi,

Here am posting the code for applying Duplicate validation in ADF Applications through Java Bean. This can be used to check duplicate records in the oracle ADF Application.


    public void empIdValidator(FacesContext facesContext, UIComponent uIComponent, Object object) {
        if (object != null) {
            // 'am' is the applcation module
            ViewObjectImpl vo = am.getVo();
            // To get current Row off the Vo
            Row cRow = vo.getCurrentRow();
            // Create a Iterator to Iterate Over the ViewObject Vo
            // There is a also a method called vo.getRowSetIterator() but it is advised to use vo.createRowSetIterator(null)
            Integer count = 0;
            RowSetIterator rsi = vo.createRowSetIterator(null);
            while (rsi.hasNext()) {
                Row rw = rsi.next();
                if (rw != cRow) {
                    if (rw.getAttribute("EmpId") != null) {
                        Integer empId = (Integer) rw.getAttribute("EmpId");
                        if (empId = (Integer) object) {
                            count = 1;
                        }
                    }
                }
            }
            // Closing the iterator is advised after the use
            rsi.closeRowSetIterator();
            if (count == 1) {
                FacesMessage message2 = new FacesMessage("Duplicate EmpId !");
                message2.setSeverity(FacesMessage.SEVERITY_ERROR);
                throw new ValidatorException(message2);
            }
        }
    }

If you have any Questions regarding the above code. Feel free to ask. :)

ADF: Code to get bindings to make custom buttons

## Code to get bindings to make custom buttons

1)Use in the code.

BindingContainer bindings = getBindings();
OperationBinding operationBinding =bindings.getOperationBinding("Commit");
operationBinding.execute();


2)Definetion of getBindings method


public BindingContainer getBindings() {
return BindingContext.getCurrent().getCurrentBindingsEntry();
}

OR

** We can use directly in one line**

BindingContext.getCurrent().getCurrentBindingsEntry().
getOperationBinding("CreateInsert")
.execute();

_______________________________________________________________________________
If you have any Questions about ADF. Feel free to ask. I will be happpy to help. :)


ADF: Code to show error msg in page

## Code to show error msg  in page


throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,”msg”,null));


Note: This code works only in the validator block