Sunday, December 11, 2016

Input LOV,,AutoSuggest Behavior , default action for enter button in adf

HI folks,

today i am going to show some ADF features in this application with example application, Which was attached at end of this post.

Scenarios :
Input LOV,
AutoSuggest Behavior ,
Default action for enter button,
Programatic ViewCriteria creation.


Step 1 : create LOV on firstName in side the EmployeesView.





Step 2: creating LOV




Add form on jspx page and add autosuggest behavior to input text.



Add method for autosuggetbehavior to show auto suggestion feature, as shown below.




and then add code for searching the filtered item as shown below.

    public void searchEvent(ActionEvent actionEvent) {
        String name = this.firstNameBnd.getValue().toString();
        DCBindingContainer bc = (DCBindingContainer)getBindings();
        DCIteratorBinding iter = bc.findIteratorBinding("Emp_View1Iterator");
        ViewObject vo = iter.getViewObject();
        ViewCriteria vc = vo.createViewCriteria();
        ViewCriteriaRow vcrow = vc.createViewCriteriaRow();
        vcrow.setAttribute("FirstName", name);
        vc.addRow(vcrow);
        vo.applyViewCriteria(vc);
        vo.executeQuery();
    }
    public BindingContainer getBindings(){
        return BindingContext.getCurrent().getCurrentBindingsEntry();}
   
Thanks :)


Sunday, October 23, 2016

Calling Method for every request upon clicking the selected row second time. (Selection Listener/Client Listener/ Server Listener)

Scenario : Suppose there is an af:table with one row. On selecting the row for the first time you want some custom logic to be executed. On selecting the same row for the second time, you want the same custom logic to be executed again.
Selection Listener : We cannot achieve the above scenario by using Selection Listener. Selection Listener is called only once for each row selection. When we try to select the same row for the second time the Selection Listener is not called.
Client and Server Listener : The above scenario can be achieved by using the Client and Server Listener. For each client request the server method in bean is called. Custom logic can be written in the server listener method.

Solution : 
  • Create EO, VO for a table
  • Drag and drop the table from data control on to the page
  • For the table provide the client listener and server listener as below
<table>
.....
<af:clientListener type="click" method="cancelSelection"/>
 <af:serverListener type="selectEvent" method="#{DemoBean.cancelEvent}"/>
..... 
</table>



Server Listener 

Property
Value
type
The event name which is queued in the java script method
method
Provide the bean method name
  
Client Listener 

Property
Value
type
click (In our case we execute on click of table row)
method
Provide the Java Script method name

  • Write the following Java Script in the jspx page (or create a new java script file and include it in the jspx page by using  <af:resource type="javascript" source="<JavaScriptFileName.js>"/>)
 <af:resource type="javascript">
      function cancelSelection(e) {
      var source=e.getSource();
      AdfCustomEvent.queue(source,"selectEvent",{},true);
}</af:resource>



To fire a custom event from the client, use the AdfCustomEvent.queue() Javascript method. The Javascript having AdfCustomEvent.queue() should be called by the ClientListener, and AdfCustomEvent.queue() method is calling the server side action defined in ServerListener.

AdfCustomEvent.queue() method that takes the event source, the string selectEvent as the custom event type, a null parameter map, and true/false value for the immediate parameter.

By giving the client and server listener, the logic in #{DemoBean.cancelEvent} method is executed every time the user clicks on the row. 


Post from  : http://adf-tips-neetika.blogspot.in/2014/09/client-and-server-listener.html

Thanks Neetika Sharma

Selecting a particular tab in panel tabbed based on selection in dropdown(select one choice)

Programatically render input text on UI based on the number entered in the spin box

  • Drag and drop a spin box from the component palette on the page.
  • Give the value change listener to the spin box
  • we can also set min,max and default values for Spin Box.
  • Write the following code in the value change listener
  •         private List<String> numList= null;

  • @demo method 

  •         public void numOfInput(ValueChangeEvent vc) {
  •                Object answer=vc.getNewValue();
  •                BigDecimal a = (BigDecimal)answer;
  •                numList= new ArrayList<String>();
  •          for(int i=1;i<=a.intValue();i++) {
  •               numList.add("krt"+i);
  •          }
  • numList is an array list and iterates as many number of times as specified in the spin box.


  • Drag and drop the input text from component palette beneath the spin box. 
  • Surround the input text with an iterator
  • Give the value to the iterator as 
  •  #{viewScope.sampleBean.numList}  (The value property of the iterator takes an array list. In our case numList is an array list)
  • Set the auto submit property for spin box to true and give the id of spin box in the partial trigger property of input text.


Thus depending upon the number entered in the spin box, input text are rendered on the UI. 

Thursday, July 7, 2016

BufferReader with Validation Using Pattern

package GeneralDemos;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BufferReaderDemo {

public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
PrintWriter out = new PrintWriter("R:\\workspace Java\\textfiles\\output.txt");
Pattern p = Pattern.compile("(0/91)?[789][0-9]{9}");
BufferedReader br = new BufferedReader(new FileReader("R:\\workspace Java\\textfiles\\input.txt"));
String line = br.readLine();
while(line!=null){
Matcher m = p.matcher(line);
while(m.find() && m.group().equals(line)){
out.println(m.group());
}
line = br.readLine();
}
out.flush();
}

}

Wednesday, July 6, 2016

RegularExpressionsDemo

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegularExpressionsDemo {
public static void main(String[] args) {
Pattern p = Pattern.compile("12");
Matcher m = p.matcher("1234512812789");
int count = 0;
while(m.find()){
count++;
System.out.println(m.start()+".."+m.end()+".."+m.group());
}
System.out.println("total no of occurances "+count);
}
}
---------------------------------------------------------------------------------
package GeneralDemos;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegularExp2 {

public static void main(String[] args) {
// TODO Auto-generated method stub

ArrayList<String> emails = new ArrayList();
emails.add("NANI.103@gmail.com");
emails.add("Chinna.A103@gmail.com");
emails.add("@abcdef@gmail.com");
emails.add("#32n#$%ani@gmail.com");
emails.add("vijay@gmail.com");
emails.add("vikram@gmail.com");
emails.add("anil@gmail.com");

// String regex ="^[A-Za-z+.][a-z0-9]@[a-z]";

String regex ="^[A-Za-z0-9+.]+[0-9]@[a-z]+(\\.[A-Za-z]{2,})$";

// String regex = "^(.+)@(.+)$";
// String regex = "^([A-Z.+])@(.+)$";
/* Regex : ^[A-Za-z0-9+_.-]+@(.+)$
In this regex, we have added some restriction osn username part of email address. Restrictions in above regex are:

1) A-Z characters allowed
2) a-z characters allowed
3) 0-9 numbers allowed
4) Additionally email may contain only dot(.), dash(-) and underscore(_)
5) Rest all characters are not allowed*/

Pattern p =Pattern.compile(regex);
for(String email:emails){
Matcher m = p.matcher(email);
if(m.matches()){
System.out.println(email+" valid mail id ");
}else{
System.out.println(email+" not a valid mail id ");
}
}

}

}
--------------------------------------------------------------------------------
package GeneralDemos;

import java.util.regex.Pattern;
public class SplitDemo {
public static void main(String[] args) {
// String regx = "\\s";  // ex for space
// String regx = "a";  // example for char
// String regx = "\\."; // . considered as Symbol
String regx = "[.]";  //. considered as Symbol
// Using String class Split
String trgString = "Raviteja.kotha.from kodad";
System.out.println("before split: "+trgString);
String[]s2 = trgString.split("[.]");
for(String s3 : s2){
System.out.println("Using String Class : "+s3);
}
//Using Pattern class Split
Pattern p = Pattern.compile(regx);
String[] s = p.split(trgString);
for(String s1 : s){
System.out.println(s1);
}

}

}

--------------------------------------------------------------------------------
package GeneralDemos;

import java.util.StringTokenizer;

public class StringTokenizerDemo {

public static void main(String[] args) {
// no pattern (default space used)
StringTokenizer st = new StringTokenizer("Hello Ravi How are you");
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}
// "-" pattern
StringTokenizer st1 = new StringTokenizer("2016-july-07","-"); // date 'targetString' - 'R expsn/pattern'
while(st1.hasMoreTokens()){
System.out.println(st1.nextToken());
}

}

}

--------------------------------------------------------------------------------
package GeneralDemos;

import java.io.InputStream;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ValidationDemo {

public static void main(String[] args) {
System.out.println("Enter mobile number : ");
Scanner sc = new Scanner(System.in);
long l = sc.nextLong();
String value = String.valueOf(l);
String regex = "(0/91)?[7-9][0-9]{9}";

Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(value);
// if we use only m.find  it will check the part of target String according to pattern
//if pattern matches prints valid number but below expression checks entire target String with pattern
if(m.find() && m.group().equals(value)){
System.out.println(value+" is a valid number");
}else{
System.out.println(value+" is not a valid number");
}
}

}


Tuesday, July 5, 2016

Shuttle Component in ADF

Prepare EO,VO,AM
drag Table from DC to Page as Shuttle Component(Multiple Selection)
Select fields to show in Shuttle panel for shuffling 
Create button to get Selected Values(Use below code on Button).


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.getBindings();
     //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]);
        }
    }
- See more at: http://www.awasthiashish.com/2012/11/shuttle-component-in-oracle-adf-allow.html#sthash.rucCulFt.NJ3uluXL.dpuf

Monday, July 4, 2016

Programatic Approach of Validation

  • 1. select the input field in form
  • now goto property inspector and select validator and create custom method of validator in bean.
  • and write the below code...

  • 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));
  •             }
  •         }
  •     }
  • - See more at: http://www.awasthiashish.com/2012/11/custom-validator-in-oracle-adf-jsf_20.html#sthash.75VcsYR5.dpuf

    To Show Pop Up using JavaScript

    showPopup(Addpop, true);
    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 
    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); } } - 



    See more at: http://www.awasthiashish.com/2012/11/popup-component-in-oracle-adf.html#sthash.5bExH7EZ.dpuf

    Refresh Page and UI components

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

    //Method to reload full 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); 


    import oracle.adf.view.rich.context.AdfFacesContext; AdfFacesContext.getCurrentInstance().addPartialTarget(UIComponentBinding);

    instead  of UI component binding ,If we pass parent Panel GroupLayout binding we can do total page refresh

    How to set row Key on table after rollback/commit operation

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


    Using Custom messages defined in XML to ADF Application

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

    Select af:messages and go to property inspector and set Inline-true to show message in the current window

    This post is from :
    - See more at: http://www.awasthiashish.com/2012/10/passing-parameter-in-xml-resource-and.html#sthash.iZpHP6Oi.x5yKBgyl.dpuf

    ViewAccessor

    ViewAccessor : by using it we can access one VO in another VO
    Ex : inside EmployeeVO i will create DepartementVO accessor
    it is required to fetch data in LOV
    it contains tuning property also
    In side VO under general section also we have Tuning property.

    af:ConverNumber

    af:ConverNumber placed in InputText and then
    it has properties like Locale (to set the language)and type (to set percent,number,currency)
    we can set min and max fractions
    and also min and max IntegerDigits

    To call Client Listener from ActionListener use below code

    // To call Client Listener from ActionListener use below code
    FacesContext fctx = FacesContext.getCurrentInstance();
    ExtendedRenderKitService service = Service.getRenderKitService(fctx, ExtendedRenderKitService.class);
    service.addScript(fctx, "showMyTable();");
    --------------------------------------------------------------------------------------------
    
    

    Handling Keyboard keys Using java code

    import java.awt.Toolkit;
    import java.awt.event.KeyEvent;

    public class KeyLocksDemo {

    public static void main(String[] args) {
    KeyLocksDemo lc = new KeyLocksDemo();
    lc.onAllKeys();
    //              lc.offAllKeys();
         
     //this is an infinite loop that will make all 3 buttons contineous on-off
           /* int i = 0;
     // while(;;){SYSo();} --> Infinity loop
            while (i < 1) {
                lc.onAllKeys();
                lc.offAllKeys();
            }*/


    }

    public boolean capsLock(boolean cp) {
            Toolkit tk = Toolkit.getDefaultToolkit();
            tk.setLockingKeyState(KeyEvent.VK_CAPS_LOCK, cp);
            System.out.println("capsLock");
            return true;
           
        }
        public boolean numLock(boolean np) {
            Toolkit tk = Toolkit.getDefaultToolkit();
            tk.setLockingKeyState(KeyEvent.VK_NUM_LOCK, np);
            System.out.println("numLock");
            return true;
        }
        public boolean scrollLock(boolean sp) {
            Toolkit tk = Toolkit.getDefaultToolkit();
            tk.setLockingKeyState(KeyEvent.VK_SCROLL_LOCK, sp);
            System.out.println("scrollLock");
            return true;
        }
    //This method on all three buttons
        public boolean onAllKeys() {
            return capsLock(true) & numLock(true) & scrollLock(true);
        }
        //This method off all three buttons
        public boolean offAllKeys() {
            return capsLock(false) & numLock(false) & scrollLock(false);
        }


    }