Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Thursday, 3 April 2014

Java Collections , Map Interface

Map is the most important Data Structure in Java. It is used to store Key & Value pairs.
There are commonly 4 implementations of Maps :

  1. HashMap ( No Ordering on Keys or Values )
  2. TreeMap ( Ordered on the basis of Key )
  3. HashTable ( Implemented same as HashMap, except that HashTable is Synchronised . )
  4. LinkedHashMap ( It preserves the order of insertion of elements. )
  1. HashMap

    HashMap is used to store Key and Value pairs in the collection. Here is a very simple example.    


    import java.util.HashMap;
    import java.util.Map.Entry;
    
    public class SimpleHashMapTest {
        public SimpleHashMapTest() {
            super();
        }
    
        public static void main(String[] args) {
            //Create a hash map
            HashMap<Integer, String> map = new HashMap<Integer, String>();
            //add key value pairs in the hashMap
            map.put(1, "First");
            map.put(2, "Second");
            map.put(4, "Fourth");
            map.put(3, "Third");
            map.put(5, "Fifth");
            map.put(6, "Sixth");
            map.put(7, "Seventh");
            
            System.out.println("The key value pairs in HashMap are :");
            for(Entry<Integer,String> e : map.entrySet()){
                System.out.println("Key : "+e.getKey()+"        Val : "+e.getValue());
            }
            //get(key) is used to get the value at the given key
            System.out.println("Value at key : "+3+" is :"+map.get(3));
            //These methods can be used to check if the map contains the particular key or not. 
            //They return boolean
            map.containsKey(1);
            map.containsValue("Sixth");
        }
    }
    

       And the output on the console is as below.



  2. TreeMap

    TreeMap is sortedd on the basis of Key. i.e. if you want to make a key-value pair that need to be sorted on the basis of the key, then you gotta use TreeMap. Let us take an example and try to understand.
    I am taking a self-defined class Animal.class as key and will make a TreeMap. So to make a self-made class a key we need to define implement following interface.
    • Comparable ( This helps in Sorting the keys by comparing them. )
       

    public class Animal implements Comparable{
        String name;
        Integer size;
        public Animal(String name, Integer size) {
            this.name = name;
            this.size = size;
        }
    
        @Override
        public int compareTo(Object o) {
            return ((Animal)o).size - this.size;
        }
        
        public String toString(){
            return size+". "+name;
        }
    }
    
    public class TreeMapTest {
      
        public static void main(String[] args) {
            TreeMap<Animal,Integer> map = new TreeMap<Animal,Integer>();
            map.put(new Animal("Elefant", 10), 1);
            map.put(new Animal("Cat", 3), 2);
            map.put(new Animal("Tiger", 7), 1);
            map.put(new Animal("Lion", 8), 1);
            map.put(new Animal("Deer", 5), 1);
            
            //map.entrySet() gets you a sorted list of key - value pairs
            System.out.println("Sorted list :");
            for(Entry<Animal,Integer> e : map.entrySet()){
                System.out.println("Key is : "+e.getKey()+ " value : "+e.getValue());
            }
            
            // If you want a sorted in descending order you can use map.descendingMap()
            System.out.println("Descending order list :");
            for(Entry<Animal,Integer> e : map.descendingMap().entrySet()){
                System.out.println("Key is : "+e.getKey()+ " value : "+e.getValue());
            }
            
        }
    }
    

    output is  :
  3. HashTable

    HashTable and HashMap are almost same. The little difference between them is that
    • HashTable is synchronised
    • HashMap is unsynchronised
    That means HashTable is Thread safe and HashMap is not. That simply means that if so many threads are modifying a HashTable then locking is handeled by HashTable itself whereas in case of HashMap synchronisation needs to be done.
  4. LinkedHashMap

    LinkedHashMap is similar to HashMap except for the fact that LinkedHashMap maintains the insertion order of the elements in the LinkedHashMap.
    Let us take an example and try to understand.      
    public class Animal implements Comparable{
        String name;
        Integer size;
        public Animal(String name, Integer size) {
            this.name = name;
            this.size = size;
        }
    
        @Override
        public int compareTo(Object o) {
            return ((Animal)o).size - this.size;
        }
        
        public String toString(){
            return size+". "+name;
        }
    }
    
    import java.util.LinkedHashMap;
    import java.util.Map.Entry;
    import java.util.TreeMap;
    
    public class LinkedHashMapTest {
        public static void main(String[] args) {
            LinkedHashMap<Animal,Integer> map = new LinkedHashMap<Animal,Integer>();
            map.put(new Animal("Elefant", 10), 1);
            map.put(new Animal("Cat", 3), 2);
            map.put(new Animal("Tiger", 7), 1);
            map.put(new Animal("Lion", 8), 1);
            map.put(new Animal("Deer", 5), 1);
            
            //map.entrySet() gets you a list of key - value pairs
            System.out.println("List :");
            for(Entry<Animal,Integer> e : map.entrySet()){
                System.out.println("Key is : "+e.getKey()+ " value : "+e.getValue());
            }
            
           
        }
    }
    

  5. OutPut is : 

    Here you can eaisly see that the values are stored in the LinkedHashMap in the order they are inserted.                   

Thursday, 20 June 2013

ADF : Refresh issues in Oracle ADF Application

During the application development in ADF, the most common problem that we encounter when our application is deployed on server is the problem of refresh. That means you expect a component to refresh on some action but still it doesn't happens.

This problem comes into picture in a big size application that uses many other applications or many taskflows are being called into it.I dont exaclty know why this problem comes into focus, but its some kind of 'id' problem of UIcomponent. 

So, here are some of the solution if the above problem comes into picture.


  1. The easiest way to give partial trigger to a UIComponent is to go into the properties menu in the property inspector and simply choose the component id you want to select. So whenever the selected UIcomponents will have a change, the UIComponent on which partial refresh is given is refreshed.



     
  2. Sometimes it happens that even after giving partial trigger on the UIComponent the Component is not been refreshed.So, you can try to refresh the component from the bean using java code.
    AdfFacesContext.getCurrentInstance().addPartialTarget(UIComponent);


    Here 'UIComponent' is the binding of the UIComponent on the page into the bean.
  3. Sometimes the above two methods fail.After using the above two techniques also the field is not being refreshed. Then you can use the ResetUtil class for resetting the fields.

    For using ResetUtil you have to import the given class:
    import oracle.adf.view.rich.util.ResetUtils;
    

    And to use it on the page :

    ResetUtils.reset(UIComponent); 
      
  4. After using the above methods if Still the problem exists. Then if you are using model in your application, then you have to perform "execute" on the used ViewObject.
  5. Still if the problem persists, then perform "Rollback" after the "Commit" operation.
  6. Still if the problem exists, please drop your case in the comment box.. :) 

Tuesday, 11 June 2013

ADF : Running or calling javascript from java bean

In the other post of mine I wrote about the steps to call Java method from a javascript code. Now I am gonna tell you how we can call a Javascript code from Java code. This is the easiest method I found on the internet.
  1. For calling Javascript you have to use the following method in the java bean :

    public static void runJavaScriptCode(String javascriptCode) { 
             FacesContext facesCtx = FacesContext.getCurrentInstance(); 
             ExtendedRenderKitService service =
    Service.getRenderKitService(facesCtx, ExtendedRenderKitService.class); 
             service.addScript(facesCtx, javascriptCode); 
           } 



    You have to import the following packages :
    import javax.faces.context.FacesContext;
    import org.apache.myfaces.trinidad.render.ExtendedRenderKitService;
    import org.apache.myfaces.trinidad.util.Service;
  2.  And to call the javsccript from the java code :
    runJavaScriptCode("alert(\"My name is Java\");");

Thursday, 16 May 2013

ADF | Button Action or ActionListener queuing through bean programatically.

During development sometimes we have to call several button events at a time. In ADF Button event listeners or we can say Action or ActionListeners can be called programmatically. There is a concept of action queuing in ADF. But i found a much easier and better way of doing it. As we call methods in java, we can call the Action or ActionListener too by passing the suitable parameters. In the given example I am simply using print statements to demonstrate. Follow the simple steps :


  1. Create an ADF application in JDeveloper and define a task flow and then create a view and add 3 buttons on the view. Nae them differently so that you can identify them. Here I have used names "Button 1" , "Button 2" , "Button 3". I have defined ActionListeners for all three buttons.
     
  2. Now go to bean and just write print statements in the actionListeners just to make sure that the control came to it.
  3. Now run the application and click on the "Button 3". Now look on the console, the print statements off the other two actionListeners are also printed. Thus our task is complete.
  4. Am attaching the sample application for this, You can download by clicking here.QueueingDemo.rar
  5. Note: This procedure will not work if you are using the ActionEvent's object i.e. passed in the method. If you are using the ActionEvent then you have to call the method by initializing the ActionEvent with the appropriate button.
    • First, create a binding of the component in the bean whose actionLister is to be called.
    • And then use :
      ActionEvent event = new ActionEvent(this.componentBinding);

      ** Here "componentBinding" is the binding of the button component in the bean.
      To initialize the ActionEvent and then use the object " event " to call the ActionListener

Friday, 12 April 2013

how to populate data in ADF table from Bean using POJO | Populating af:table using ArrayList

Hi,

This post is about populating af:table from a POJO from the bean.

Suppose we have to show information related to books to the user.
So first we have to understand how we populate a table from a List.
  1. For this we have to create a dataType for storing the data of the book.
  2. For the same, we have created a Class named BookInfo. Here is the code for on the BookInfo class.

    package edittableonpojo.view.dc;
    
    public class BookInfo {
        private String bookDesc;
        private String bookAuthNm;
        private String bookSrNo;
        
        public BookInfo(String bookSrNo,String bookDesc,String bookAuthNm) {
            super();
            this.bookSrNo = bookSrNo;
            this.bookAuthNm = bookAuthNm;
            this.bookDesc = bookDesc;
        }
    
        public void setBookDesc(String bookdesc) {
            this.bookDesc = bookdesc;
        }
    
        public String getBookDesc() {
            return bookDesc;
        }
    
        public void setBookAuthNm(String bookAuthNm) {
            this.bookAuthNm = bookAuthNm;
        }
    
        public String getBookAuthNm() {
            return bookAuthNm;
        }
    
        public void setBookSrNo(String bookSrNo) {
            this.bookSrNo = bookSrNo;
        }
    
        public String getBookSrNo() {
            return bookSrNo;
        }
        
        public String getKey(){
            return this.getBookSrNo();
        }
        
        public String toString(){
            return bookSrNo+"_"+bookAuthNm+"_"+bookDesc;
        }
    }
    

  3. Then we have to create a Bean from which data will be provided to the table. In the constructer of the Bean the code is written to populate the data in the ArrayList. Here is the code of the Bean.

    package edittableonpojo.view.bean;
    
    import edittableonpojo.view.dc.BookInfo;
    
    import java.util.ArrayList;
    
    public class BookBean {
        private ArrayList<BookInfo> bookDtls = new ArrayList<BookInfo>();
    
    
        public BookBean() {
            bookDtls.add(new BookInfo("1A", "The Alchemist", "Paulo Cohelo"));
            bookDtls.add(new BookInfo("2A", "Game Of Thrones", "George R. R. Martin"));
            bookDtls.add(new BookInfo("3A", "Five Point Someone", "Chetan Bhagat"));
            bookDtls.add(new BookInfo("4A", "Harry Potter", "J.K.Rowling"));
            bookDtls.add(new BookInfo("5A", "Wings of Fire", "A.P.J Abdul Kalam"));
        }
    
        public ArrayList<BookInfo> getBookInfo() {
            return bookDtls;
        }
    }
    

  4. Now we have to create a Page where we can show the data of the List. For this, I have created a jspx page and dropped an af:table in which we will show the data and done some styling ;).
  5. The table contains three Columns
    1. Book SrNo.
    2. Author Name.
    3. Book Description
  6. In the Value attribute of the Table from the Property inspector, select the value of the attribute from the bean-like   
<af:table var="row" rowBandingInterval="0" id="t1" value="#{viewScope.BookBean.bookInfo}"
                                  rowSelection="none"
                                  inlineStyle="line-Height: 15px;">

  1. In the Columns drop af:outputText and in the value of the outputText put the value like value="#{row.bookAuthNm}" for showing the Author name , and similarly you have to put values in other rows.
  2. Here is the code of the jspx page.

    <?xml version='1.0' encoding='UTF-8'?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1" xmlns:f="http://java.sun.com/jsf/core"
              xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
        <jsp:directive.page contentType="text/html;charset=UTF-8"/>
        <f:view>
            <af:document title="untitled1.jspx" id="d1">
                <af:form id="f1">
                    <af:panelBox text="Book Details" id="pb1">
                        <f:facet name="toolbar"/>
                        <af:panelCollection id="pc1" styleClass="AFStretchWidth">
                            <f:facet name="menus"/>
                            <f:facet name="toolbar"/>
                            <f:facet name="statusbar"/>
                            <af:table var="row" rowBandingInterval="0" id="t1" value="#{viewScope.BookBean.bookInfo}"
                                      rowSelection="multiple"
                                      inlineStyle="line-Height: 15px;">
                                <af:column sortable="true" headerText="Book SrNo." id="c1">
                                    <af:outputText value="#{row.bookSrNo}" id="ot1"/>
                                </af:column>
                                <af:column sortable="false" headerText="Author Name" id="c2">
                                    <af:outputText value="#{row.bookAuthNm}" id="ot2"/>
                                </af:column>
                                <af:column sortable="true" headerText="Book Description" id="c3" width="300">
                                    <af:outputText value="#{row.bookDesc}" id="ot3"/>
                                </af:column>
                            </af:table>
                        </af:panelCollection>
                    </af:panelBox>
                </af:form>
            </af:document>
        </f:view>
    </jsp:root>
    

  3. The jspx page looks like this.
  4. Now simply run the application.
  5. After the screen that comes up is something like this.
Here is the sample application : TableOnPOJO.rar

ADF : Facebook chat implementation

I had a task in my organisation to implement facebook chat in ADF. After a lot of search on internet and found that chat for facebook can only be inplemented through smacks api. It is available at http://www.igniterealtime.org/downloads/source.jsp .

Download the sample zip application here : Facebookchat.rar


There are three java classes used for the same:



  1. "CustomSASLDigestMD5Mechanism.java" to perform the authentication.
  2. "FBMessageListener.java" to listen to the messages that comes to you from facebook.
  3. "FBConsoleChatApp.java" is the java class that contatins main method i.e. this is the class used for running the program.
GoodLuck.

Thursday, 21 February 2013

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)

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. :)