Oct 25, 2013

IP tracking of Remote address in ADF


To trace IP address of system which is opening page on its web browser following code is used.

      import javax.faces.context.ExternalContext;
      import javax.faces.context.FacesContext;


     FacesContext ctx = FacesContext.getCurrentInstance();

     HttpServletRequest request = (HttpServletRequest)ctx.getExternalContext().getRequest();

     request.getRemoteAddr();

If there is a need to get server IP address then code will be as follows
    
      FacesContext ctx = FacesContext.getCurrentInstance(); 

      HttpServletRequest request = (HttpServletRequest)ctx.getExternalContext().getRequest();

      request.getLocalAddr();

May 26, 2013

Image upload in ADF

In this post we will see how to upload images in Oracle ADF application.

 To upload a file don't forget to set UsesUpload property of form of jspx page to true.








Lets start with uploading a image/file from client to the server.
ADF rich faces provide the tag af:inputFile to allow uploading of data.
Define a variable Type UploadedFile and create its accessors

private UploadedFile _file;

public void setFile(UploadedFile _file) {
     this._file = _file;
}

public UploadedFile getFile() {
      return _file;
    }
And bind it with inputFile component's value property

<af:inputFile label="Upload Image" id="if1" value="#{ImageUploadBean.file}" />



 In this we will see 2 places where we can uploading image depending on our requirement :-
1.)In Database(BLOB) :-
In this part, we will see how to upload a image/file from the client to and store image in a blob column in a database.

We have used button action to upload file

Following are codes to upload Image in database blob column

    public String UploadImageAction() {
        UploadedFile myfile = this.getFile();
       
      
        if (myfile != null) {
           
            if (myfile.getContentType().equalsIgnoreCase("image/jpeg") ||                 myfile.getContentType().equalsIgnoreCase("image/png")  || myfile.getContentType().equalsIgnoreCase("image/gif")
                ){

                AppImageAMImpl am = (AppImageAMImpl)resolvElDC("AppImageAMDataControl");
                ViewObjectImpl v = am.getAppImgAdd();
                AppImgAddVORowImpl currRow = (AppImgAddVORowImpl)v.getCurrentRow();
                                                             
                try {
                   
                   
                    //to save image in Blob column in database directory..............

                                      
                    currRow.setImgBlob(createBlobDomain(getFile()));                                     


                } catch (Exception ex) {
                   
                }
            }
        }
        setFile(null);
        return null;
    }


    private BlobDomain createBlobDomain(UploadedFile file) {

        InputStream in = null;
        BlobDomain blobDomain = null;
        OutputStream out = null;

        try {
            in = file.getInputStream();

            blobDomain = new BlobDomain();
            out = blobDomain.getBinaryOutputStream();
            byte[] buffer = new byte[8192];
            int bytesRead = 0;

            while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {
                out.write(buffer, 0, bytesRead);
            }

            in.close();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.fillInStackTrace();
        }

        return blobDomain;
    }

2.)In Actual path in server :-

 In this part, we will see how to upload a image/file from the client to actual location in server.

        public String UploadImageAction() {
        UploadedFile myfile = this.getFile();      
      
        if (myfile != null) {
           
            if (myfile.getContentType().equalsIgnoreCase("image/jpeg") ||  myfile.getContentType().equalsIgnoreCase("image/png")
                || myfile.getContentType().equalsIgnoreCase("image/gif")
                ){

                String path = "D:\\Images\\";

                 if(myfile.getContentType().equalsIgnoreCase("image/jpeg")){
                   
                    TypeVal=".jpeg";
                }
                else if(myfile.getContentType().equalsIgnoreCase("image/png")){
                    
                     TypeVal=".png";
                }
               
                else if( myfile.getContentType().equalsIgnoreCase("image/gif")){
                   
                    TypeVal=".gif";
                }
               
                AppItemImageAMImpl am = (AppItemImageAMImpl)resolvElDC("AppItemImageAMDataControl");
                ViewObjectImpl v = am.getAppItmImgAdd();
                AppItmImgAddVORowImpl currRow = (AppItmImgAddVORowImpl)v.getCurrentRow();

                String ImgId = currRow.getImgId();
               
                try {
                   
                    InputStream inputStream = myfile.getInputStream();
                    BufferedImage input = ImageIO.read(inputStream);

                    //to save image in another directory..............

                    File outputFile = new File(path + ImgId + TypeVal);
                    ImageIO.write(input,type, outputFile);                                     
                  
                } catch (Exception ex) {
                    // handle exception
                
                }
            }
        }
        setFile(null);
        return null;
    }



May 25, 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(new FacesMessage(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)




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