Please disable your adblock and script blockers to view this page

Search this blog

Thursday 29 November 2012

Add Serial No. in Table in ADF, Auto Increment column in ADF table

ADF provides easy way to add a autoincrement column in table to make Serial No. or Sequence Column for table ,thats value autoincrements with no.of rows in table .
You have to follow these steps to do this.

  • Go to tabel properties (property Inspector) and set VarStatus to vs

set varStatus of af:table to vs
  •  Now add a column in table and drop an output text inside this new added column
Add new column to af:table to show serial number for each row
  • Select output text and Go to its property inspector and set value to #{vs.index+1} as it is selected in Expression Builder by going through- 
ExpressionBuilder----->JspObjects--->VS---->index




using varStatus we can access various built in function like index,count etc
  • You have done now run your page and you can see a serial no. column
af:table with serial number column

Tuesday 27 November 2012

GTalk (Google Talk) integration with Java


Hello All

Google Talk is most popular chat client that use your gmail login authentication, and after this tutorial you will be able to create your own Gtalk (if you use swing ), this tutorial shows how to integrate Gtalk with Java.

This example uses Smack API, Smack is an Open Source XMPP (Jabber) client library for instant messaging and presence. A pure Java library, it can be embedded into your applications to create anything from a full XMPP client to simple XMPP integrations such as sending notification messages and presence-enabling devices.



  • Code to integrate Google talk with java
 package chat_Server;
 import org.jivesoftware.smack.ConnectionConfiguration;
 import org.jivesoftware.smack.XMPPConnection;
 import org.jivesoftware.smack.XMPPException;
 import org.jivesoftware.smack.packet.Message;
 public class GtalkChat {
   private static String username = "ashishawasthi000@gmail.com";
   private static String password = "XXXXXXX";
   ConnectionConfiguration connConfig;
   XMPPConnection connection;
   public GtalkChat() throws XMPPException {
     connConfig = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
     connection = new XMPPConnection(connConfig);
     connection.connect();
     connection.login(username, password);
   }
   public void sendMessage(String to, String message) {
     Message msg = new Message(to, Message.Type.chat);
     msg.setBody(message);
     connection.sendPacket(msg);
   }
   public void disconnect() {
     connection.disconnect();
   }
   public static void main(String[] args) throws XMPPException {
     GtalkChat gtalkChat = new GtalkChat();
     gtalkChat.sendMessage("abcdefg@gmail.com",
                "Hii this message is send using Java and Google talk integration.");
     gtalkChat.disconnect();
   }
 }  
  • Change line 7 and line 8 with your username and password respectively



  • Chage line 27 with receiver's email id and type your message
  • Now download SMACK API from its website or click on link below
  • Extract Smack.rar and Add Smack.jar and Smackx.jar to your project
  • Now run the code
  • This code will only send chat , try to receive using your own code

Monday 26 November 2012

Tree Table Component in Oracle ADF(Hierarchical Representation)


Hello All

This post is about ADF Faces Tree Table component (about designing component and get selected value from tree table)

We have a simple sample application that shows how can we use tree table component in Oracle ADF.
Tree Table component represents  Hierarchical view of Master Deatil form of data
Here we take example from HR schema using Employees and Department table
Follow these steps -

  • Create EOs,VOs of Employees and Department table in HR Schema and create association and viewlink between Department To Employees considering Department Id
  • Now go to data control and select Department table and drop it on page as Tree table 

Drop ViewObject as ADF Tree Table
  •  Now we have to edit its bindings, it means you have to select attributes that you want to display in page, and below Department table you should add Employees table using "add" button on top, and select appropriate Iterator in EL picker
Edit tree binding in pageDef
  • Now go to page and select treetable in Structure window of Jdeveloper and Go to its selection listener and copy default value
Override default selection listener
  • And change selection listener set it to bean, click on edit and create new selection listener in Bean




Create custom selection listener in managed bean for af:treeTable
  •  Now go to Selection Listener and Use this code to get Value of selected node in treetable, if you will get value of node you can perform any operation on Tree Table
    public void treeTableSelectionListener(SelectionEvent selectionEvent) {
        String adfSelectionListener = "#{bindings.Department1.treeModel.makeCurrent}";

        FacesContext fctx = FacesContext.getCurrentInstance();
        Application application = fctx.getApplication();
        ELContext elCtx = fctx.getELContext();
        ExpressionFactory exprFactory = application.getExpressionFactory();
        MethodExpression me = null;
        me =
 exprFactory.createMethodExpression(elCtx, adfSelectionListener, Object.class, new Class[] { SelectionEvent.class });
        me.invoke(elCtx, new Object[] { selectionEvent });
       
        RichTreeTable tree = (RichTreeTable)selectionEvent.getSource();
        TreeModel model = (TreeModel)tree.getValue();
        //get selected nodes
        RowKeySet rowKeySet = selectionEvent.getAddedSet();
        Iterator rksIterator = rowKeySet.iterator();
        while (rksIterator.hasNext()) {
            List key = (List)rksIterator.next();
            JUCtrlHierBinding treeBinding = null;
            treeBinding = (JUCtrlHierBinding)((CollectionModel)tree.getValue()).getWrappedData();
            JUCtrlHierNodeBinding nodeBinding = treeBinding.findNodeByKeyPath(key);
            Row rw = nodeBinding.getRow();
            System.out.println("row: " + rw.getAttribute(0)); // You can get any attribute
            System.out.println("View Object name---->" + nodeBinding.getViewObject().getName());

        }
    }
  •  Now run your page and when you will click on any node you will find its value on Console---Cheers Happy Coding!
Sample ADF Application 

Most Used Codes in ADF (Iterate over ViewObject, get Value from pageFlow Scope variable)

Iterate Over View Object-


Some times we need to iterate in table to check for some validation as we have  to check for duplicate record, we want to delete all data of table with one click.
then we have to get all rows of table- this is a very common use case in ADF, so you can use following snippet of code to do this






1. Using AllRowInRange method to get rows available in range

  ViewObject vo=am.getViewObject();


   // Get All Rows in range of ViewObject in an Array
    Row[] rArray=vo.getAllRowsInRange();
    
    //Loop over array of Rows
    for(Row r:rArray){

       /*your operation code*/

       }


2. Using RowSetIterator-


  ViewObject vo = this.getViewObject();
       
       //Create RowSetIterator
        RowSetIterator rsi = vo.createRowSetIterator(null);
       //Iterate Over this to get all rows
        while (rsi.hasNext()) {
            Row nextRow = rsi.next();
            
        }
        rsi.closeRowSetIterator();


Get Value from taskFlow parameter(Using pageFlow Scope)-

we can get value from TaskFlow parameter using pageflow scope and can use it in Our Bean.
Suppose we have defined a parameter in page to pass Session_Id.
We can get it using pageflow scope




Integer sessionId = Integer.parseInt(resolvEl("#{pageFlowScope.Session_Id}"));

 Code For resolvEl-


    public String resolvEl(String data) {
        FacesContext fc = FacesContext.getCurrentInstance();
        Application app = fc.getApplication();
        ExpressionFactory elFactory = app.getExpressionFactory();
        ELContext elContext = fc.getELContext();
        ValueExpression valueExp = elFactory.createValueExpression(elContext, data, Object.class);
        String Message = valueExp.getValue(elContext).toString();
        return Message;
    }
 

Friday 23 November 2012

ADF Basics: Set Default Values in Entity Object for every CreateInsert

Sometimes we have to set some same(default) values for each new row for this we use literal value option in EntityObject XML file or we can set that value in EO(EntityObject) Impl class.
EOImpl Class has a method named

 protected void create(AttributeList attributeList) {
        super.create(attributeList);
}

You can set default values there
For this we have to create Entity Impl class of EntityObject , Open EntityObject and select Java tab and click on edit icon


Check Accessors and Create Method checkbox


Now set values using accessors like this -


    /**
     * Add attribute defaulting logic in this method.
     * @param attributeList list of attribute names/values to initialize the row
     */
    protected void create(AttributeList attributeList) {
        //Setting default values
        setEmail("example@gmail.com");
        setPhoneNumber("99999999");
        super.create(attributeList);
    }


or can set in Literal Value of EO xml file

Set default value in Entity Object Literal Value

This is how you can set default values in Entity Object


Wednesday 21 November 2012

Shuttle Component in Oracle ADF (Allow Multiple Selection), Get Selected values from Shuttle Component



Hello All

Hope you all are doing well :) 

Shuttle component supports multiple selections at Runtime, when we need to select multiple records at runtime then we can use Shuttle Component.

Now we see how to use shuttle component (af:selectManyShuttle) in Oracle ADF

Shuttle Component in Oracle ADF

Follow these steps-

  • Prepare model for Employees table of HR Schema(Create EO,VO and AM)
  • Now drag Employees ViewObject from DataControl to page and select multiple selection-->ADF Select Many Shuttle-
Drop ViewObject as ADF Select Many Shuttle






  • Now edit binding for this Shuttle Component, choose attribute that you want to show and also base attribute-
    Edit Shuttle binding and select base and display attribute

     
  • Now it will look like this, drag a button to get selected attribute of this shuttle component
    af:selectManyShuttle
     
    Now write code on button's actionEvent to get selected value from Shuttle-


    import oracle.adf.model.BindingContext;
    import oracle.binding.BindingContainer;
    
        /*****Generic Method to get BindingContainer of current page, fragment or region**/
        public BindingContainer getBindingsCont() {
            return BindingContext.getCurrent().getCurrentBindingsEntry();
        }
    

     public void getSelectedValue(ActionEvent actionEvent) {
          //Get Binding Continer of Page
            BindingContainer bc = this.getBindingsCont();
         //Get shuttle binding from pagedef
            JUCtrlListBinding listBindings = (JUCtrlListBinding)bc.get("Employees1");
        //Get Selected Values
            Object str[] = listBindings.getSelectedValues();
        //Iterate over selected values
            for (int i = 0; i < str.length; i++) {
                System.out.println(str[i]);
            }
        }
    

    When you run this it should look like this and your Shuttle is ready
    Get selected value of shuttle component ADF

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. }