Monday, June 3, 2013

Some Important Code in ADF

بسم الله الرحمن الرحيم
اللهم علمنا ما ينفعنا وانفعنا بما علمتنا يا رب العالمين
---------------

Code to get AppModule in Java Bean class

To implement resolvEDIC method
    public Object resolvElDC(String data) {
           FacesContext fc = FacesContext.getCurrentInstance();
           Application app = fc.getApplication();
           ExpressionFactory elFactory = app.getExpressionFactory();
           ELContext elContext = fc.getELContext();
           ValueExpression valueExp =
                   elFactory.createValueExpression(elContext, "#{data." + data + ".dataProvider}",
           Object.class);
           return valueExp.getValue(elContext); 
       }

Use this in code to get  Application Module Impl class
       AppModuleAMImpl am =
       (AppModuleAMImpl)resolvElDC("AppModuleAMDataControl");

Code to show FacesMessege  in page

     FacesMessage message = new FacesMessage("Record Saved Successfully!");   
     message.setSeverity(FacesMessage.SEVERITY_INFO);   
     FacesContext fc = FacesContext.getCurrentInstance();   
     fc.addMessage(null, message);

Code to show error msg  in page

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

Code to get bindings to make custom buttons

BindingContainer bindings =BindingContext.getCurrent().getCurrentBindingsEntry();
OperationBinding operationBinding =bindings.getOperationBinding("Commit");
operationBinding.execute();
  
Code to use 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)To use in the page
Use binding property of Popup
private RichPopup pop;
Now use above showPopup method to show popup in any method or button action.
showPopup(pop, true);

 Popup Dialog listener

Place dialog in popup and use Dialog Listner event of dialog to perform action of used button of dialog.
For ex:-  we use ok button of Dialog .So to perform action of Ok button we have to bind DialogListner property of Dialog and use following code.

    public void dailogok(DialogEvent dialogEvent) {
       if(dialogEvent.getOutcome().name().equals("ok")){
           BindingContainer bindings = getBindings();
           OperationBinding operationBinding =bindings.getOperationBinding("Commit");
           operationBinding.execute();
       }

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(newFacesMessage(FacesMessage.SEVERITY_ERROR,msg,null));
           }
       }
   }

Code to validate duplicate record

    public void deptNameValidator(FacesContext facesContext, UIComponent uIComponent, Object object) {       
       DuplicateRecordValidationAMImpl am =  (DuplicateRecordValidationAMImpl)resolvElDC("DuplicateRecordValidationAMDataControl");
       DepartmentViewImpl departmentView1 = am.getDepartmentView1();
       Row[] filteredRowsInRange = departmentView1.getFilteredRows("DepartmentName", object.toString());
//        departmentView1.getAllRowsInRange();
       int i=filteredRowsInRange.length;
       String msg="Department with the same name found.Please enter any other name.";
       if(i>1){
           throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,msg,null));
       }
}
Phone Number validation

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

 Using groovy expression (sample format)

Groovy expressions can be placed in a number of different places in ADF Business
Components. For the main part, you will probably be applying them in entity and view object
attribute values and for entity object validations.
Mostly we can use groovy expression for Transient object

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)
  
Opening a Task flow from Backing within Same Window

private void launchWindow() {
FacesContext fctx = FacesContext.getCurrentInstance();

String taskflowId = “generic-task-flow”;
String taskflowDocument = “/WEB-INF/generic-task-flow.xml”;
Map<String, Object> params = new HashMap<String, Object>();
String taskflowURL = ControllerContext.getInstance().getTaskFlowURL(false, new TaskFlowId(taskflowDocument, taskflowId), params);
ExtendedRenderKitService erks = Service.getRenderKitService(fctx, ExtendedRenderKitService.class);
StringBuilder script = new StringBuilder();
  script.append(“window.open(\”"+taskflowURL+”\”").append(“,\”_self\”);”);
erks.addScript(FacesContext.getCurrentInstance(), script.toString());
}

 Refresh page through java code

protected void refreshPage() {
      FacesContext fc = FacesContext.getCurrentInstance();
      String refreshpage = fc.getViewRoot().getViewId();
 ViewHandler ViewH =
 fc.getApplication().getViewHandler();
      UIViewRoot UIV = ViewH.createView(fc,refreshpage);
      UIV.setViewId(refreshpage);
      fc.setViewRoot(UIV);
}


Partially refresh on any UI Component

 Here we use binding property of UI Component
AdfFacesContext.getCurrentInstance().addPartialTarget(UIComponent);



والسلام عليكم ورحمته الله وبركاته
<< سبحانك اللهم وبحمدك أشهد أن لا اله الا أنت أستغفرك وأتوب اليك >>

1 comment :

Related Posts Plugin for WordPress, Blogger...