Quantcast
Channel: Ashish Awasthi's Blog
Viewing all 165 articles
Browse latest View live

Add and delete values in POJO based selectOneListbox/selectOneChoice in ADF

$
0
0
Previously i have posted about populating selectOneChoice programmatically using POJO
Programmatically populate values in a af:selectOneChoice component in ADF

In same way we can populate values in selectOneListBox as both ADF Faces components are used for single selection and share same structure


Here i have used a List to populate values in selectOneListBox (For details read complete article in above link)
And to get selected value from af:selectOneListBox/selectOneChoice in bean- Used a String variable , created it's accessors

//List DataStrucutre to populate values in selectOneListBox
List<SelectItem> customList =new ArrayList<SelectItem>();

publicvoidsetCustomList(List<SelectItem> customList){
this.customList= customList;
}

public List<SelectItem>getCustomList(){
return customList;
}



//String variable to hold selectOneListBox value
private String selectedVal;

publicvoidsetSelectedVal(String selectedVal){
this.selectedVal= selectedVal;
}

public String getSelectedVal(){
return selectedVal;
}

And see here how both List and String variable are bound to af:selectOneListBox

<af:selectOneListboxid="sol1"contentStyle="width:150px;"size="10"value="#{viewScope.SelectOneListBoxBean.selectedVal}">
<f:selectItemsvalue="#{viewScope.SelectOneListBoxBean.customList}"id="si1"var="variable"/>
</af:selectOneListbox>

Now I have dropped an inputText and two buttons on page to add and delete values from selectOneListBox. Created component binding for inputText to get Value in managed bean


<af:panelGroupLayoutid="pgl1"layout="vertical">
<af:inputTextlabel="Enter value to add in Listbox"id="it1"
binding="#{viewScope.SelectOneListBoxBean.itBind}"/>
<af:buttontext="Add Record"id="b1"
actionListener="#{viewScope.SelectOneListBoxBean.addValueInList}"/>
<af:spacerwidth="0"height="10"id="s1"/>
<af:panelGroupLayoutid="pgl2"layout="horizontal">
<af:selectOneListboxid="sol1"contentStyle="width:150px;"size="10"
value="#{viewScope.SelectOneListBoxBean.selectedVal}"
partialTriggers="b1 b2">
<f:selectItemsvalue="#{viewScope.SelectOneListBoxBean.customList}"id="si1"/>
</af:selectOneListbox>
<af:buttontext="Delete"id="b2"
actionListener="#{viewScope.SelectOneListBoxBean.deleteSelectedValue}"/>
</af:panelGroupLayout>
</af:panelGroupLayout>


Now see code for add and delete buttons, Add button actionListener get value from inputText using component binding and add it to List  and Delete button finds and deletes selected value from List


/**Method to add Record in List
* @param actionEvent
*/
publicvoidaddValueInList(ActionEvent actionEvent){
//Get value from inputText using component binding
if(itBind.getValue()!=null){
//Add value in List
customList.add(new SelectItem(itBind.getValue().toString()));
}
}

/**Method that check for selected value in List
* @param items
* @param value
* @return
*/
public SelectItem getItem(List<SelectItem> items, String value){
for(SelectItem si : items){
System.out.println(si.getValue());
if(si.getValue().toString().equalsIgnoreCase(value)){
return si;
}
}
returnnull;

}

/**Method to delete selected record from List
* @param actionEvent
*/
publicvoiddeleteSelectedValue(ActionEvent actionEvent){
if(selectedVal !=null){
//Find and delete selected item from List
customList.remove(getItem(customList, selectedVal));
}
}

All Done :) Run and check application
Enter a value in inputText and click on Add button , It is added in ListBox


 Add 3 values and select second value to delete


 Click on delete button


Sample ADF Application - Download
Cheers :) Happy Learning

ADF Basics: Using setActionListener in ADF, Set pageFlowScope parameter without writing code

$
0
0
This post is about using setActionListener tag in ADF, this tag provides a simpler way to set values of other objects and makes use of EL
See What docs says-

The setActionListener tag is a declarative way to allow an action source (<commandButton>, <commandLink>, etc.) to set a value before navigation. It is perhaps most useful in conjunction with the "pageFlowScope" EL scope provided by ADF Faces, as it makes it possible to pass details from one page to another without writing any Java code. This tag can be used both with ADF Faces commands and JSF standard tags. More generally, it can be used with any component at all that implements the standard ActionSource interface.


It has two properties

fromObjectYesthe source of the value; can be an EL expression or a constant value
toObjectOnly ELthe target for the value; must be an EL expression

See how to use this component to set pageFlowScope parameters without writing any code

  • Created a Fusion Web Application using Employees table of HR Schema 

  • Created a bounded taskFlow and two page fragments in view controller project


  • Added two input parameters in BTF to hold Employee's First and Last Name


  • Dropped Employees View Object as form on page with navigation buttons and added one more button to navigate to second page after setting Employee's First and Last name in BTF input parameters


  • See the source of Go To Second Page button, dropped two setActionListener component under button to set First Name and Last Name. Here you can see from and to values of setActionListener, itdoes the job of setting pageDef values to BTF parameters

  • <af:buttontext="Go To Second Page"id="b1"action="goToSecondPage"
    inlineStyle="font-weight:bold;color:red;">
    <af:setActionListenerfrom="#{bindings.FirstName.inputValue}"to="#{pageFlowScope.FIRST_NAME}"/>
    <af:setActionListenerfrom="#{bindings.LastName.inputValue}"to="#{pageFlowScope.LAST_NAME}"/>
    </af:button>

  • In Second fragment added an output text that shows values of both BTF input parameters

  • <af:outputTextvalue="#{pageFlowScope.FIRST_NAME}#{pageFlowScope.LAST_NAME}"id="ot1"
    inlineStyle="font-size:medium;color:navy;font-weight:bold;"/>

  • All done :) Run and check application 

  • On First Page see Employee detail-

    On Second Page -

Sample ADF Application- Download
Cheers :) Happy Learning

ADF UI: Using dvt:sunburst to show hierarchical data in ADF

$
0
0
<dvt:sunburst> is one of fancy components to show multi level hierarchical data in form of circular rings in ADF application

It supports drilling up to n-level , consist of dvt:sunburstNode as it's child tag to show level wise detail . Sunburst supports multiple type of animations that makes a better UI
See What docs says -

Sunbursts are used to display hierarchical data across two dimensions, represented by the size and color of the sunburst nodes. The sunburst displays multiple levels of its hierarchy at once, with each ring corresponding to a level of the hierarchy

Here i am using Departments and Employees table of HR Schema to show 2-level of sunburst
  • Create a Fusion Web Application and prepare Model using Departments and Employees table 


  • Create view link between Departments and Employees viewObject using DepartmentId and add to Application Module


  • Create a page and open data control menu , drop Departments view object as sunburst on page



  • Configure sunburst to show Department and Employee detail


  • To enable single selection i have set nodeSelection to single and #{bindings.Departments1.treeModel.makeCurrent} in selectionListener (this will set selected node as current node and further we can get it programmatically)
    See sunburst XML code -

    <dvt:sunburstid="t1"value="#{bindings.Departments1.treeModel}"var="row"
    summary="Department-Employees"
    selectionListener="#{bindings.Departments1.treeModel.makeCurrent}"
    nodeSelection="single">
    <af:switcherfacetName="#{row.hierTypeBinding.name}"id="s1">
    <f:facetname="Departments11">
    <dvt:sunburstNodevalue="#{row.Salary}"label="#{row.FirstName}"id="sn1"
    shortDesc="Salary- #{row.Salary}"fillColor="#ff7435"/>
    </f:facet>
    <f:facetname="Departments10">
    <dvt:sunburstNodevalue="#{row.DepartmentId}"label="#{row.DepartmentName}"id="sn2"
    shortDesc="Department Id- #{row.DepartmentId}"drilling="insert"
    fillColor="#51a5ff"/>
    </f:facet>
    </af:switcher>
    </dvt:sunburst>

  • Run and check application


  • All good :) Now we can see that when we select any node in sunburst it sets as current row in Department table , this happens due to selection listener property. 

To get selected node in managed bean we can create custom selection listener for this sunburst same as this post Get selected slice of dvt:pieChart using custom selection listener in ADF 

Sample ADF Application (Jdev 12.1.3)- Download
Cheers :) Happy Learning

ADF Basics: Creating Bounded Task Flow Train using af:train component

$
0
0
This post is about using bounded task flow as train
A train presents a whole cycle and it's every stop presents a particular step of cycle
From the docs -

The train component presents a user with a series of stops, each stop representing a step in a multi-step process. The train walks the user through these steps, in a suggested order (the order being dictated by the underlying model). Each step is rendered as a train stop consisting of an image and a textual link indicating if they are in visited, current, unvisited and disabled states. Train can also be rendered in a vertical layout - the default being a horizontal layout. Trains are not rendered on printable pages. 


We can design bounded task flow as train flow , see how to configure this
  • Create a Fusion Web Application and a Bounded TaskFlow in view controller project
    File--->New---> From Gallery-->Web Tier--->JSF/Facelets-->ADF Taskflow


    Check Create Train checkbox-


  • Now drop two or more pages in BTF , i have dropped three view activities from component palette, these fragments will behave as train stops


  • Select a view and go to structure window , expand view node and right click on train stop select Insert Inside Train Stop --> Display Name

  • Put a name for that stop and follow same steps for all view activities, this name will appear on that stop when we run this



  • Next is to create fragment , double click on first view activity and create a jsp xml fragment , now drop af:train and af:trainButtonBar on page from component palette


  • Click on OK with default value


    Drop an output text on page and it's value is - First Stop, Now repeat these steps for each view activity and each fragment looks like this

  • Now drop this bounded task flow in a jspx page as region and run that page


  • On clicking Next button

All done :)
Now if we want to change train's default look then we can use af:navigationPane component , this component supports Apache Trinidad MenuModel ,that extends TreeModel and implemented by Train Model so we can directly use navigationPagewithout much efforts

af:navigationPane has af:commandNavigationItem as it's child component and it supports multiple UI hints as list, bar ,buttons, choice and tabs
Seexml code to use af:navigationPane-

<af:navigationPanehint="list"id="np1"value="#{controllerContext.currentViewPort.taskFlowContext.trainModel}"
var="train">
<f:facetname="nodeStamp">
<af:commandNavigationItemtext="#{train.textAndAccessKey}"id="cni1"visited="#{train.visited}"
disabled="#{train.disabled}"action="#{train.action}"/>
</f:facet>
</af:navigationPane>

And see how it looks on page -
Select navigationPane on page and see in property inspector and change it's hints to see different looks of train


 Bar -
 Choice-
Tabs-
Cheers :) Happy Learning

Show live progress of a long running task using af:progressIndicator in Oracle ADF

$
0
0
This post is about using af:progressIndicator to show live status of a particular task
af:progressIndicator state is tracked and maintained by it's value property that supports org.apache.myfaces.trinidad.model.BoundedRangeModel
This class has two methods

publicabstractlonggetMaximum(){}
returns Maximum value for Model

publicabstractlonggetValue(){}
returns value for Model (current state)

Now to see live progress on page we have to refresh progressIndicator component periodically and this can be achieved using af:poll component , poll component delivers poll events to server periodically and we can ppr (refresh) progress indicator after a particular interval


So I have created a page and dropped these ADF Faces components
af:button- to start processing (start a thread that loop up to 100 and sleeps for 100 milliseconds to make it long)
af:progressIndicator- to show live progress
af:outputText- to show text percentage completed
af:poll- to refresh progressIndicator after a fixed time interval


Next i have created a bean class that extends BoundedRangeModel and implements Runnable (For thread purpose)
See Managed Bean -

importjavax.faces.event.ActionEvent;

importoracle.adf.view.rich.context.AdfFacesContext;

importorg.apache.myfaces.trinidad.event.PollEvent;
importorg.apache.myfaces.trinidad.model.BoundedRangeModel;

publicclassProgressIndicatorBeanextends BoundedRangeModel implements Runnable {


publicProgressIndicatorBean(){
}
// An Integer value that presents current state of progress
int procVal =0;
//To set poll interval, on start button click it will start polling
privateint pollInterval =-1;

//Variable accessors to be used by ADF Faces Components on page
publicvoidsetPollInterval(int pollInterval){
this.pollInterval= pollInterval;
}

publicintgetPollInterval(){
return pollInterval;
}

publicintgetProcVal(){
return procVal;
}

publicvoidsetProcVal(int procVal){
this.procVal= procVal;
}

@Override
publiclonggetMaximum(){
return100;
}

@Override
publiclonggetValue(){
return procVal;
}

@Override
publicvoidrun(){
// Loop up to Maximum value of Progress Model
while(procVal < getMaximum()){
try{
//Sleeps for 100ms to make it long
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
//Increase current status of progress model
procVal++;
}
}

/**Method to process Action Event, starts polling and a thread that makes processing long
* @param actionEvent
*/
publicvoidprocessValueAction(ActionEvent actionEvent){
//Set poll interval to postive value to start polling
pollInterval =100;
//Set initial progrss to zero
procVal =0;
//Start a thread
Thread t =new Thread(this);
t.start();
}


/**Poll Listener to stop poll (set poll interval to -1) once task is done
* @param pollEvent
*/
publicvoidpollListnerEvt(PollEvent pollEvent){
//Check if processing is complete
if(procVal == getMaximum()){
//Setting poll interval to negative value to stop polling
pollInterval =-1;
//Refresh poll component
AdfFacesContext.getCurrentInstance().addPartialTarget(pollEvent.getComponent());
}
}
}

Now see page XML source - (How this bean is mapped on page)


<af:panelGroupLayoutid="pgl1"layout="vertical"halign="center">
<af:buttontext="Start"id="b1"
actionListener="#{viewScope.ProgressIndicatorBean.processValueAction}"/>
<af:spacerwidth="10"height="10"id="s1"/>
<af:pollid="p1"interval="#{viewScope.ProgressIndicatorBean.pollInterval}"partialTriggers="b1"
clientComponent="true"timeout="10000"
pollListener="#{viewScope.ProgressIndicatorBean.pollListnerEvt}"/>
<af:progressIndicatorid="pi1"value="#{viewScope.ProgressIndicatorBean}"partialTriggers="p1"/>
<af:outputTextvalue="Proceesing.. #{viewScope.ProgressIndicatorBean.procVal}% Done"id="ot1"
partialTriggers="p1"inlineStyle="color:blue;font-weight:bold;"/>
</af:panelGroupLayout>


All done :) Page looks like this

 Run and check application, Click on start button

Sample ADF Application (Jdeveloper 12.1.3) -Download
Cheers :) Happy Learning

Drag Drop in same table to reorder rows, Update Attribute value to make it persistent

$
0
0
This post is based on Frank's article on reordering table rows using drag drop functionality of ADF Faces, post uses iterator indexing to change order of rows and it works pretty good

Recently i came across a question on OTN forum asking about making this ordering persistent on base of some attribute value so for that we have to maintain a serial no attribute for each row and when user performs Drag n Drop , serial no. will be swapped and updated ordering of rows will be shown to user and it is persistent as updated attribute's value is saved in database

So for this use case i have added a Serial No. column in Departments table of HR Schema

Let's see how to implement this
  • Create a Fusion Web Application and prepare model using Departments table of HR Schema

  • Drop Departments view object as table on page, drop af:dragSource and af:collectionDropTarget as child of af:table in order to enable Drag n Drop functionality 


  • Define Drop Listener for drop target and set Model Name (this will be discriminant of drag source) and actions 

  •          Set properties of Drag Source


  • See Managed Bean code , Helper methods and Drop Listener Code
  • Required Packages

    importjava.util.Iterator;
    importjava.util.List;

    importoracle.adf.model.BindingContext;
    importoracle.adf.view.rich.component.rich.data.RichTable;
    importoracle.adf.view.rich.datatransfer.DataFlavor;
    importoracle.adf.view.rich.datatransfer.Transferable;
    importoracle.adf.view.rich.dnd.DnDAction;
    importoracle.adf.view.rich.event.DropEvent;

    importoracle.binding.BindingContainer;
    importoracle.binding.OperationBinding;

    importoracle.jbo.Row;

    importorg.apache.myfaces.trinidad.model.RowKeySet;


    Helper Methods

    /**Method to get BindingContainer of current viewPort
    * @return
    */
    public BindingContainer getBindingsCont(){
    return BindingContext.getCurrent().getCurrentBindingsEntry();
    }

    /**
    * Generic Method to execute operation
    * */
    public OperationBinding executeOperation(String operation){
    OperationBinding createParam = getBindingsCont().getOperationBinding(operation);
    return createParam;
    }


    Drop Listener (Gets dragged and drop rowsite and swaps serial no)

    /**Method to handle drop event
    * @param dropEvent
    * @return
    */
    public DnDAction reOrderDropListener(DropEvent dropEvent){
    //get the table instance. This information is later used

    RichTable table =(RichTable) dropEvent.getDragComponent();
    List dropRowKey =(List) dropEvent.getDropSite();//if no dropsite then drop area was not a data area
    if(dropRowKey ==null){
    return DnDAction.NONE;
    }
    //The transferable is the payload that contains the dragged row's
    //row key that we use to access the dragged row handle in the ADF
    //iterator binding
    Transferable t = dropEvent.getTransferable();
    //here "reorderrow" is the discriminant used in drag source
    DataFlavor<RowKeySet> df = DataFlavor.getDataFlavor(RowKeySet.class,"reorderrow");
    RowKeySet rks = t.getData(df);
    Iterator iter = rks.iterator();

    //for this use case the re-order of rows is one-by-one, which means
    //that the rowKeySet should only contain a single entry. If it
    //contains more then still we only look at a singe (first) row key entry
    List draggedRowKey =(List) iter.next();

    //Dragged Row
    Row dragRow =(Row) table.getRowData(draggedRowKey);

    //Drop Row
    Row dropRow =(Row) table.getRowData(dropRowKey);

    //Get Serial No from dragged row
    Integer dragSno =(Integer) dragRow.getAttribute("Sno");
    //Get Serial No of dropped row
    Integer dropSno =(Integer) dropRow.getAttribute("Sno");

    //Swap Values to change order in DB
    dragRow.setAttribute("Sno", dropSno);
    dropRow.setAttribute("Sno", dragSno);

    //Call Commit Operation to save chanes in database
    executeOperation("Commit").execute();

    //Call Execute operation to see updated records
    executeOperation("Execute").execute();
    return DnDAction.MOVE;
    }


  • Now run and check application. Dragged Purchasing department and dropped on Administration
       
         After calling drop listener -


Sample ADF Application (Jdeveloper 12.1.3)- Download
Cheers :) Happy Learning

    ADF Skinning: Increase width, Change color of a tab in af:panelTabbed

    $
    0
    0
    We can change appearance of ADF Application by applying CSS and changing style properties of ADF Faces Component
    Here i am writing a simple CSS to increase tab width of af:panelTabbed component

    I hope you all know how to create a skin for ADF Application , If don't know then look at this post
    ADF Basics: Using CSS to change appearance of application (Skins and Styles in ADF Faces) 


    af:panelTabbed looks like this (Using Alta UI Skin)

    Now to changes tab width , background color or font style we can use CSSlike this -


    //ToChangetextstyleofTab
    af|panelTabbed::tabaf|panelTabbed::tab-text-link {
    color:white;
    font-weight:bold;
    }

    //ToChangetabstyle
    af|panelTabbed::tab {
    background-color: Highlight;
    width:200px;
    }

    //Toincreasesizeoftabcontenttomatchwithtabwidth
    af|panelTabbed::tabaf|panelTabbed::tab-content {
    width:200px;
    }


    After applying Skin tab looks like this -

    Cheers :) Happy Learning

    Configure ADF Skin in Jdeveloper 11.1.1.7

    $
    0
    0

    In Jdeveloper 11.1.1.7 there is no option to create ADF Skin declaratively
    In order to apply skin we have to create a simple CSS file and then configure application to use this CSS file as skin. Jdeveloper doesn't do this for us :( we have to do it manually

    So first step is to enable Skin Selectors for ADF Faces, Without enabling this CSS editor doesn't show ADF Faces component tags
    CSS files by default supports HTML tags  only

    Go to Tools > Preferences > CSS Editor and set CSS level to level 3 and check the box to support ADF Faces Components


    Now create a CSS file -
    Right Click on View Controller project > Select New > Web Tier > HTML > CSS File 

     
    Provide a name for CSS file and click OK



    Created a page and dropped af:commandButton in that and added this code in CSS file

    @namespaceaf"http://xmlns.oracle.com/adf/faces/rich";

    af|commandButton{
    color:blue;
    font-weight:bold
    }

    But you'll see that there is no change in look of button , it means CSS is not working as of now


    This is because that there is no change in trinidad-config.xml file and we have to do it manually
    Replace trinidad-config.xml with this code

    <?xml version="1.0" encoding="windows-1252"?>
    <trinidad-configxmlns="http://myfaces.apache.org/trinidad/config">
    <skin-family>MyCss</skin-family>
    <skin-version>v1</skin-version>
    </trinidad-config>

    and create a new XML file called trinidad-skins.xml , thisfile manages skins in ADF Application


    <?xml version="1.0" encoding="windows-1252" ?>
    <skinsxmlns="http://myfaces.apache.org/trinidad/skin">
    <skin>
    <id>skin1.desktop</id>
    <family>MyCss</family>
    <extends>skyros-v1.desktop</extends>
    <style-sheet-name>css/skin1.css</style-sheet-name>
    </skin>
    </skins>

    <skin-family> of trnidad-config.xml and <family> attribute of trinidad-skins.xml should be same
    Now check again, CSS is now become ADF Skin ;)

    Cheers :) Happy Learning

    ADF Basics: Call PL/SQL Procedure with OUT parameter in ADF Application

    $
    0
    0
    Previously i have posted about calling pl/sql function in ADF Application

    This post is about calling stored procedure in ADF Application , a very basic requirement.
    Sometimes we need to call a procedure that has OUT parameters , these parameters are used to return value from procedure. There may be n- numbers of OUT parameters in a procedure 

    In this post i am discussing same so for demo purpose I have created a PL/SQL procedure  that takes EmployeeId as input parameter and return First Name and Last Name as OUT parameter (Using Oracle HR Schema)



    CREATEORREPLACEPROCEDURE PROC_GET_EMPNAME(EMP_NO INNUMBER, F_NAME OUT VARCHAR2,L_NAME OUT VARCHAR2) IS
    BEGIN
    SELECT FIRST_NAME INTO F_NAME FROM EMPLOYEES WHERE EMPLOYEE_ID=EMP_NO;
    SELECT LAST_NAME INTO L_NAME FROM EMPLOYEES WHERE EMPLOYEE_ID=EMP_NO;
    END;


    Now see code to call procedure from ADF Application



    /**Method to call Database function
    * @param stmt
    * @param bindVars
    * @return
    */
    protectedvoidcallStoredProcOut(String stmt, Object[] bindVars){
    CallableStatement st =null;
    try{
    //Creating sql statement
    st =this.getDBTransaction().createCallableStatement("begin "+ stmt +";end;",0);


    // Set the bind values of the IN parameters (Employee Id is Input parameter here)
    st.setObject(1, bindVars[0]);

    //Register out parameters and their types (In this case procedure has 2 out parameters)

    st.registerOutParameter(2, Types.VARCHAR);
    st.registerOutParameter(3, Types.VARCHAR);


    // Execute the statement
    st.executeUpdate();

    // Print Return Values of out parameters
    System.out.println("First Name-"+ st.getString(2)+" Last Name-"+st.getString(3));


    }catch(SQLException e){
    thrownewJboException(e.getMessage());

    }finally{
    if(st !=null){
    try{
    st.close();
    }catch(SQLException e){

    }
    }
    }
    }

    //Call PL/SQL procedure using this helper method
    publicvoidcallStoredProcedure(){

    //Here we will pass only input parameter but write procedure signature for all parameters (IN and OUT)
    callStoredProcOut("PROC_GET_EMPNAME(?,?,?)",new Object[]{110});

    }

    So this is how we can use procedure with OUT parameters , you can change code according to number of OUT and IN parameters your procedure has
    See output on console

    Cheers :) Happy Learning

    ADF Basics: Call PL/SQL Function with OUT parameter in ADF Application

    $
    0
    0
    Previous post was about calling PL/SQL Procedure with OUT parameters in ADF Application
    ADF Basics: Call PL/SQL Procedure with OUT parameter in ADF Application

    And this post is about calling PL/SQL Function with OUT parameters. Basic difference between a Function and Procedure is that Function must return a value but procedure may or may not return a value
    So there is always one OUT parameter in PL/SQL Function

    Here we are talking about a function that has OUT parameters other than default one, for demo purpose I have created a PL/SQL Function  that takes EmployeeId as input parameter and return First Name and Last Name as OUT parameter and returns Employee Email Id as it's default return value (Using Oracle HR Schema)

    CREAET ORREPLACEFUNCTION FN_GET_EMPNAME(EMP_NO INNUMBER, F_NAME OUT VARCHAR2,L_NAME OUT VARCHAR2) 
    RETURN VARCHAR2 IS
    EMAIL_V VARCHAR2(50) :='N';
    BEGIN
    SELECT FIRST_NAME INTO F_NAME FROM EMPLOYEES WHERE EMPLOYEE_ID=EMP_NO;
    SELECT LAST_NAME INTO L_NAME FROM EMPLOYEES WHERE EMPLOYEE_ID=EMP_NO;
    SELECT EMAIL INTO EMAIL_V FROM EMPLOYEES WHERE EMPLOYEE_ID=EMP_NO;
    RETURN EMAIL_V;
    END;

    Code to call this Function from ADF, A little difference in syntax of calling procedure and function

    /**Method to call PL/SQL function with OUT parameters
    */
    publicvoidcallStoredFunctionOutParam(){
    CallableStatement st =null;
    try{
    //Creating sql statement
    st =this.getDBTransaction().createCallableStatement("BEGIN ? := FN_GET_EMPNAME(?,?,?);END;",0);

    //Register out parameter for default return value of function
    st.registerOutParameter(1, Types.VARCHAR);

    //Set IN parameter's value, here 110 is EmployeeId
    st.setObject(2,110);

    //Register other out parameters of function
    //Here I have only one input parameter so I'll start out parameter index from 3

    //1 - Default return parameter of function
    //2 - Input parameter of function

    st.registerOutParameter(3, Types.VARCHAR);
    st.registerOutParameter(4, Types.VARCHAR);

    st.executeUpdate();

    System.out.println("\n\n\nEMAIL- "+ st.getObject(1)+" FIRST_NAME- "+ st.getObject(3)+" LAST_NAME- "+
    st.getObject(4));
    }catch(SQLException e){
    thrownewJboException(e.getMessage());

    }finally{
    if(st !=null){
    try{
    st.close();
    }catch(SQLException e){

    }
    }
    }
    }

    Output on Console
    Cheers :) Happy Learning

    ADF Skinning: Change Style of ADF Table, Column, Header, Data Cell

    $
    0
    0

    After a long vacation I'm back to work :)
    This post is about changing look n feel of ADF Faces af:table component

    I have seen many questions related to changing table column header style , selected row style, changing row banding styles etc


    So this post is all about af:table styling , how can we use ADF Skin to modify default look of table component
    Read Previous posts about- ADF Skinning

    By Default ADF Table looks like this

    Change Table Header Style-


    Use column-header-cell-content selector to style af:table column header

    af|column::column-header-cell-content {
    color:white;
    font-weight:bold;
    text-align:center;
    background-color:#3f5c9a;
    padding:3px;
    }

    And Output is this

    Change table data cell and banded data cell style -


    When we set RowBandingInterval property of table to greater than zero, it show different background color for rows . 
    To set background color of rows we have to set both data-cell and banded-data-cell styles

    af|column::data-cell {
    color:black;
    background-color:#aad8ef;
    }
    af|column::banded-data-cell {
    color:maroon;
    }


    And Output is this

    Change RowHeader column style and Highlighted Row Style


    To change style of RowHeader column - Use row-header-cell  selector and for highlighted row use 
    af|table::data-row:highlighted

    af|column::row-header-cell {
    color:#0080c0;
    font-weight:bold;
    }

    af|table::data-row:highlightedaf|column::data-cell,
    af|table::data-row:highlightedaf|column::banded-data-cell {
    color:brown;
    background-color:yellow;
    }


    And Output is this

    Change ADF Table selected Row Style


    Doing this a bit tricky ;) We have to apply style for all states (active, busy , inactive etc)


    af|table::data-row:selected:inactiveaf|column::data-cell,
    af|column::data-cell:selected,
    af|table::data-row:selected:busy,
    af|column::data-cell:focus,
    af|table::data-row:selected:focusedaf|column::banded-data-cell,
    af|table::data-row:selected:focusedaf|column::data-cell,
    af|table::data-row:selectedaf|column::data-cell {
    color:white;
    background-color: Red;
    }


    And Output is this

    Cheers :) Happy Learning

    Define WHERE Clause on dynamic ViewObject created on the fly

    $
    0
    0

    We all know there are different ways to define WHERE clause on a viewObject at runtime and previously I have posted about it
    Check -

    ADF Basics: Apply and Change WHERE Clause of ViewObject at runtime programmatically
    ADF Baiscs: Define and remove named bind variable in viewObject at runtime programmatically
    Setting view object bind variable (Override bindParametersForCollection, prepareRowSetForQuery, executeQueryForCollection )

    This post is about defining WHERE Clause on dynamic viewObject created at run time using SQL query

    So for this created a dummy view object using dual

    SELECT*FROM DUAL


    Now remove this dummy viewObject and create new ViewObject with same name using query

    //Get dummy viewObject
    ViewObject dynVo =this.getdynamic1();
    //Remove viewObject from Application Module
    dynVo.remove();
    //Creates a read-only View Object, given a query statement and a name for the View Object.
    this.createViewObjectFromQueryStmt("dynamic1","SELECT * FROM DEPARTMENTS");

    There is no difference in syntax of setWhereClause method but here we pass JDBC Positional bind variable using "?"symbol



    //Apply desired WHERE Clause and declare bind variable
    dynVo.setWhereClause("DEPARTMENT_NAME=?");

    //Pass Bind Variable value using index
    dynVo.setWhereClauseParam(0,"Finance");

    // Execute ViewObject to finally apply where clause
    dynVo.executeQuery();

    This is how we can apply WHERE clause on dynamic viewObjects
    Cheers :) Happy Learning

    ADF Basics: Get display and base value of POJO based SelectOneChoice

    $
    0
    0
    Previously I have posted about populating selectOneChoice programmatically using POJO
    and this post is about getting selected value of POJO base selectOneChoice (both display value and base value)

    We can get base value of selectOneChoice simply using value property but to get display value we have to iterate over list of items and find display value on basis of Base value
    So here I have created a POJO based selectOneChoice , for that declared a List in managed bean to populate list items and a String variable to hold selected value of choice list

    //String variable to hold selected value of selectOneChoice
    String selectedVal;

    publicvoidsetSelectedVal(String selectedVal){
    this.selectedVal= selectedVal;
    }

    public String getSelectedVal(){
    return selectedVal;
    }

    //List variable to populate selectOneCoice
    List<SelectItem> customList;

    publicvoidsetCustomList(List<SelectItem> customList){
    this.customList= customList;
    }

    public List<SelectItem>getCustomList(){
    if(customList ==null){
    customList =new ArrayList<SelectItem>();
    customList.add(new SelectItem("i1","Item 1"));
    customList.add(new SelectItem("i2","Item 2"));
    customList.add(new SelectItem("i3","Item 3"));
    customList.add(new SelectItem("i4","Item 4"));
    customList.add(new SelectItem("i5","Item 5"));
    }
    return customList;
    }

    and how this List and String variable is mapped on page-


    <af:selectOneChoicelabel="Select Value"id="soc1"
    value="#{viewScope.GetValuePojoListBean.selectedVal}"
    contentStyle="font-weight:bold;color:darkgreen;">
    <f:selectItemsvalue="#{viewScope.GetValuePojoListBean.customList}"id="si1"/>
    </af:selectOneChoice>

    Then dropped a button on page and created an actionListener in managed bean to get both values


    /**Method to get Selected Value in selectOneChoice
    * @param actionEvent
    */
    publicvoidgetDisplayAndBaseValueFromList(ActionEvent actionEvent){
    //Iterate over List to get Display Value
    for(SelectItem si : customList){
    if(si.getValue().toString().equalsIgnoreCase(selectedVal)){
    System.out.println("SELECTED VALUE IS- "+ selectedVal +" DISPLAY VALUE IS- "+ si.getLabel());
    }
    }
    }

    Now run and check application, Page looks like this-


    Select a value and click on button-


    Output on console-

    Sample ADF Application (Jdev 12.1.3)- Download
    Cheers :) Happy Learning

    Create ADF Choice List and apply selectItems to it programmatically

    $
    0
    0
    I hope we all know how to create selectOneChoice using Model layer and previously I have posted about populating selectOneChoice programmatically from bean using ArrayList

    Programmatically populate values in a af:selectOneChoice component in ADF

    But this post is slight different - It is about creating selectOneChoice component and applying selectItems to it programmatically
    There is nothing complicated in this , Just a piece of code is required
    Here I have used an ArrayList to set SelectItems and created component binding for af:form to add selectOneChoice as it's child 

    Packages used in bean-


    importjava.util.ArrayList;
    importjava.util.List;

    importjavax.faces.component.UISelectItems;
    importjavax.faces.event.ActionEvent;

    importjavax.faces.model.SelectItem;

    importoracle.adf.view.rich.component.rich.RichForm;
    importoracle.adf.view.rich.component.rich.input.RichSelectOneChoice;



    //af:form binding to add selectOneChoice as it's child
    private RichForm rootFormBind;

    publicvoidsetRootFormBind(RichForm rootFormBind){
    this.rootFormBind= rootFormBind;
    }

    public RichForm getRootFormBind(){
    return rootFormBind;
    }

    //List variable to populate selectOneCoice
    List<SelectItem> customList;

    publicvoidsetCustomList(List<SelectItem> customList){
    this.customList= customList;
    }

    public List<SelectItem>getCustomList(){
    if(customList ==null){
    customList =new ArrayList<SelectItem>();
    customList.add(new SelectItem("i1","Item 1"));
    customList.add(new SelectItem("i2","Item 2"));
    customList.add(new SelectItem("i3","Item 3"));
    customList.add(new SelectItem("i4","Item 4"));
    customList.add(new SelectItem("i5","Item 5"));
    }
    return customList;
    }

    Dropped a button  on page and created an ActionListener in managed bean , In this method I am creating selectOneChoice component and adding selectItems to it


    /**Method to create SelectOneChoice programmatically and add Items to it
    * @param actionEvent
    */
    publicvoidcreateSOCAction(ActionEvent actionEvent){
    //Create SelectOneChoice component using It's Java Class
    RichSelectOneChoice selectOneChoice =new RichSelectOneChoice();
    //Set required proprties of component
    selectOneChoice.setId("soc1");
    selectOneChoice.setLabel("Choice List");

    //Create SelectItems component
    UISelectItems selectItems =new UISelectItems();
    //Set Id
    selectItems.setId("si1");
    //Set SelectItems value, It'll be derived from an ArrayList of type javax.faces.model.SelectItem
    selectItems.setValue(getCustomList());

    //Add selectItems component as child of selectOneChoice
    selectOneChoice.getChildren().add(selectItems);

    //Finally add SelectOneChoice to any root component of page
    getRootFormBind().getChildren().add(selectOneChoice);
            AdfFacesContext.getCurrentInstance().addPartialTarget(rootFormBind);
    }

    Now run and check application- On click of button , SelectOneChoice is created :)

    Sample ADF Application (Jdev 12.1.3) - Download
    Cheers :) Happy Learning

    Get Selected records (Child/Parent) from POJO based ADF treeTable

    $
    0
    0
    Hello All
    Previously I have posted about creating af:treeTable programmatically using POJO and this the next post in series

    In this post I am talking about a very common requirement while using POJO based treeTable
    How can we get selected records (child/parent) from POJO based treeTable ?

    For this post I am extending same sample application, Till now we have seen that how can we create POJO based treeTable
    Now we'll see that how to get it's selected records



    Next is create af:treeTable component binding in managed bean


    importoracle.adf.view.rich.component.rich.data.RichTreeTable;

    //Component Binding of af:treeTable in bean
    private RichTreeTable treeTableBind;

    publicvoidsetTreeTableBind(RichTreeTable treeTableBind){
    this.treeTableBind= treeTableBind;
    }

    public RichTreeTable getTreeTableBind(){
    return treeTableBind;
    }

    Added a button on page and created it's ActionListener in managed bean,
    See code written in ActionListener to get selected records of af:treeTable


    importorg.apache.myfaces.trinidad.model.ChildPropertyTreeModel;
    importorg.apache.myfaces.trinidad.model.CollectionModel;
    importorg.apache.myfaces.trinidad.model.RowKeySet;
    importorg.apache.myfaces.trinidad.model.TreeModel;

    importjavax.faces.event.ActionEvent;



    /**Method to get Selected row value from POJO based treeTable
    * To Know about creation of POJO based tree
    * Check-http://www.awasthiashish.com/2014/07/populate-aftreetable-programatically.html
    * @param actionEvent
    */
    publicvoidgetSelectedRowAction(ActionEvent actionEvent){
    //Get Collection Model from treeTable binding
    CollectionModel treeModel =null;
    treeModel =(CollectionModel)this.getTreeTableBind().getValue();
    //Get selected row keys from treeTable
    RowKeySet selectedChildKeys = getTreeTableBind().getSelectedRowKeys();

    if(!selectedChildKeys.isEmpty()){
    List<Seasons> seasonList =(List<Seasons>) treeModel.getWrappedData();
    //Create iterator from RowKeySet
    Iterator selectedCharIter = selectedChildKeys.iterator();
    //Iterate over RowKeySet to get all selected childs of treeTable
    while(selectedCharIter.hasNext()){
    List val =(List) selectedCharIter.next();
    //Get Seasons (Parent) List of selected row
    Seasons s = seasonList.get(Integer.parseInt(val.get(0).toString()));
    //Get charaters list of selected seasons
    List<Seasons> characterList = s.getCharacters();
    //If selected record is child (Character)
    if(val.size()>1){
    Seasons character = characterList.get(Integer.parseInt(val.get(1).toString()));
    System.out.println("Charater Name-"+ character.getName());
    }else{
    System.out.println("Season Name-"+ s.getName());
    }
    }
    }
    }

    Run and check application , selected some records (both parent and child)


    On button click - selected records are printed on console

    Sample ADF Application - Download
    Cheers :) Happy Learning

    How to queue SelectionEvent programmatically, Call af:table Selection Listener programmatically

    $
    0
    0
    Hello All
    Hope you all are doing good :) 
    Previously I have posted about defining custom selection listener for af:table and perform desired operation on selection event of table row

    Selection Listener is fired when server receives a selection event from client means whenever user selects a row in table (Selection Event) then server process that event and execute selection listener defined in managed bean

    And this post is about creating selection event programmatically without user interaction with table.
    In ADF we can queue ActionEvent , ValueChangeEvent and in same manner we can create and queue SelectionEvent programmatically

    So for this I have Created a Fusion Web Application and prepared model using Departments table of HR Schema


    Dropped Departments ViewObject on page as af:table and defined custom selection listener of af:table in managed bean

    Packages Used-


    importjava.util.ArrayList;
    importjava.util.List;

    importjavax.el.ELContext;
    importjavax.el.ExpressionFactory;
    importjavax.el.MethodExpression;
    importjavax.el.ValueExpression;

    importjavax.faces.context.FacesContext;
    importjavax.faces.event.ActionEvent;

    importoracle.adf.model.BindingContext;
    importoracle.adf.model.binding.DCIteratorBinding;
    importoracle.adf.view.rich.component.rich.data.RichTable;

    importoracle.binding.BindingContainer;
    importoracle.binding.OperationBinding;

    importoracle.jbo.Key;
    importoracle.jbo.Row;

    importorg.apache.myfaces.trinidad.event.SelectionEvent;
    importorg.apache.myfaces.trinidad.model.RowKeySet;
    importorg.apache.myfaces.trinidad.model.RowKeySetImpl;


    Code for af:table Selection Listener-


    /**
    * Programmatic evaluation of EL.
    *
    * @param el EL to evaluate
    * @return Result of the evaluation
    */
    publicstatic Object evaluateEL(String el){
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ELContext elContext = facesContext.getELContext();
    ExpressionFactory expressionFactory = facesContext.getApplication().getExpressionFactory();
    ValueExpression exp = expressionFactory.createValueExpression(elContext, el, Object.class);

    return exp.getValue(elContext);
    }

    /**
    * Programmatic invocation of a method that an EL evaluates to.
    *
    * @param el EL of the method to invoke
    * @param paramTypes Array of Class defining the types of the parameters
    * @param params Array of Object defining the values of the parametrs
    * @return Object that the method returns
    */
    publicstatic Object invokeEL(String el, Class[] paramTypes, Object[] params){
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ELContext elContext = facesContext.getELContext();
    ExpressionFactory expressionFactory = facesContext.getApplication().getExpressionFactory();
    MethodExpression exp = expressionFactory.createMethodExpression(elContext, el, Object.class, paramTypes);
    return exp.invoke(elContext, params);
    }

    /**Custom Selection Listener for Department Table
    * @param selectionEvent
    */
    publicvoiddeptTabCustomSelectionListener(SelectionEvent selectionEvent){
    //To make selected row as Current
    invokeEL("#{bindings.Departments1.collectionModel.makeCurrent}",new Class[]{ SelectionEvent.class},new Object[]{
    selectionEvent });
    // Get the selected row , by this you can get any attribute of that row
    Row selectedRow =(Row) evaluateEL("#{bindings.Departments1Iterator.currentRow}");
    System.out.println("SELECTED DEPARTMENT IS- "+ selectedRow.getAttribute("DepartmentName"));
    }

    Dropped a button on page to call Next Operation and execute selection listener programmatically



    Here I am calling default Next operation on af:table to select next row in rowset programmtically
    and as user is not selecting row manually so selection listener will not execute that's why we have to create and queue selection event programmatically
    Now Bind af:table to managed bean and write code on button ActionListener to queue table selection listener


    //Component Binding of Department Table
    private RichTable deptTableBind;

    publicvoidsetDeptTableBind(RichTable deptTableBind){
    this.deptTableBind= deptTableBind;
    }

    public RichTable getDeptTableBind(){
    return deptTableBind;
    }

    publicQueueSelectionListenerBean(){
    }

    /**Method to return BindingContainer
    * @return
    */
    public BindingContainer getBindingsCont(){
    return BindingContext.getCurrent().getCurrentBindingsEntry();
    }

    /**
    * Generic Method to get OperationBinding
    * */
    public OperationBinding executeOperation(String operation){
    OperationBinding createParam = getBindingsCont().getOperationBinding(operation);
    return createParam;
    }

    /**Method to queue table selection listener programmatically
    * @param actionEvent
    */
    publicvoidcallSelectionListenerAction(ActionEvent actionEvent){
    executeOperation("Next").execute();
    try{
    DCIteratorBinding deptIter =(DCIteratorBinding) getBindingsCont().get("Departments1Iterator");
    Row currentRow = deptIter.getCurrentRow();
    //List to store table RowKey
    List rowKeyList =new ArrayList();
    if(currentRow !=null){

    //Add current row primary key to RowKeyList to form Old Key List
    Key jboKey =new Key(new Object[]{ currentRow.getAttribute("DepartmentId")});
    rowKeyList.add(jboKey);

    RowKeySet newRks =new RowKeySetImpl();
    newRks.add(rowKeyList);
    //Create SelectionEvent Object and put necessary values
    SelectionEvent selectionEvent =
    newSelectionEvent(deptTableBind.getSelectedRowKeys(), newRks, deptTableBind);
    //Queue Selection Event
    selectionEvent.queue();
    }
    }catch(Exception e){
    System.out.println(e);
    }
    }

    Now run and check application , Click on Move Next button and see current row is changed to Marketing

    and here custom selection listener prints selected Department Name


    Sample ADF Application -Download
    Cheers :) Happy Learning

    Traverse POJO based ADF treeTable, Get Child nodes of selected parent

    $
    0
    0

    Previosuly I have posted about populating af:treeTable programmatically and getting selected records from POJO based treeTable

    This post is next in that series and here I am extending same sample application that show a tree of Seasons and it's characters
    First we will see How to traverse a POJO based treeTable (Iterate through all nodes of treeTable)

    Basic idea is to get treeTable Collection Model and iterate over it to get all nodes value, To get CollectionModel created treeTable component binding in managed bean



    //Component Binding of af:treeTable in bean
    private RichTreeTable treeTableBind;

    publicvoidsetTreeTableBind(RichTreeTable treeTableBind){
    this.treeTableBind= treeTableBind;
    }

    public RichTreeTable getTreeTableBind(){
    return treeTableBind;
    }

    and POJO based treeTable looks like this


    Dropped a button page to traverse treeTable , Created ActionListener in Managed Bean

    Code to Traverse POJO based treeTable:


    /**Method to iterate through all nodes of treeTable (parent and child both)
    * @param actionEvent
    */
    publicvoidtraverseTreeTableAction(ActionEvent actionEvent){
    //Get TreeTable CollectionModel
    CollectionModel treeModel =null;
    treeModel =(CollectionModel)this.getTreeTableBind().getValue();
    //Creata an Object to RowKeys and collection model to it
    RowKeySet rks =new RowKeySetTreeImpl();
    rks.setCollectionModel(treeModel);
    rks.addAll();
    //Iterate Over RowKeySet to get all nodes
    for(Object o : rks){
    treeModel.setRowKey(o);
    //Here treeTable shows list of Seasons objects
    Seasons season =(Seasons) treeModel.getRowData();
    System.out.println(""+ season.getName());
    }
    }


    On button click, see output on console

    Output on Console-



















    Next is to traverse a selected parent node to get it's all child nodes

    Code to get all child of selected node:


    /**Method to iterate through all childs of selected node of treeTable
    * @param actionEvent
    */
    publicvoidtraverseSelectedNodeTreeTableAction(ActionEvent actionEvent){
    //Get Collection Model from treeTable binding
    CollectionModel treeModel =null;
    treeModel =(CollectionModel)this.getTreeTableBind().getValue();
    RowKeySet selectedChildKeys = getTreeTableBind().getSelectedRowKeys();
    if(!selectedChildKeys.isEmpty()){
    List<Seasons> seasonList =(List<Seasons>) treeModel.getWrappedData();
    //Create iterator from RowKeySet
    Iterator selectedCharIter = selectedChildKeys.iterator();
    //Iterate over RowKeySet to get all selected childs of treeTable
    while(selectedCharIter.hasNext()){
    List val =(List) selectedCharIter.next();
    //Check that selected node should be parent node
    if(val.size()==1){
    //Get Seasons (Parent) List of selected row
    Seasons s = seasonList.get(Integer.parseInt(val.get(0).toString()));
    //Get character(Child) list of Seasons
    List<Seasons> characters = s.getCharacters();
    //Iterate over character list
    Iterator iter = characters.iterator();
    while(iter.hasNext()){
    Seasons sp =(Seasons) iter.next();
    System.out.println(""+sp.getName());
    }
    }
    }
    }
    }


    On button click, see output on console

    Output on Console

    Sample ADF Application- Download
    Cheers :) Happy Learning

    Navigate to another page on value change event of ADF input component

    $
    0
    0
    Recently I have seen a thread on OTN forum in that user want to navigate from one page to another on valueChangeListener of input component.

    First Method-
    This is a simple piece of code to perform navigation to specific page , Use it in ValueChangeListener directly

     FacesContext facesContext = FacesContext.getCurrentInstance();
    facesContext.getApplication().getNavigationHandler().handleNavigation(facesContext,null,"controlFlowName");

    Second Method-
    ValueChangeListener fires when value of input component changes but it is not meant for navigation, For navigation we use buttons and links with Action property
    But for this requirement we have to be a bit tricky, We can queue button Action on value change listener of inputText to navigate to another page
    Now first value change listener will be executed and then it'll queue button action to execute and as final outcome user will be able to navigate


    See how to implement this scenario-

    I have created two pages in adfc-config.xml (default unbounded taskFlow)

    Dropped an af:inputText and a button on page1

    <af:inputTextlabel="Enter Value greater than 100 to Navigate"id="it1"
    valueChangeListener="#{viewScope.NavigateFromInputTextBean.inputTextVCE}"
    autoSubmit="true">
    <af:convertNumber/>
    </af:inputText>
    <af:buttontext="button 1"id="b1"action="goToPage2"
    binding="#{viewScope.NavigateFromInputTextBean.buttonBind}"/>

    Next is that I want to navigate to page2 when user enter a value greater than 100 in inputText, So for that created a value change listener in bean and queued this button action after checking condition

    importjavax.faces.component.UIViewRoot;
    importjavax.faces.context.FacesContext;
    importjavax.faces.event.ActionEvent;
    importjavax.faces.event.ValueChangeEvent;

    importoracle.adf.view.rich.component.rich.nav.RichButton;

    //Component Binding of af:inputText
    private RichButton buttonBind;

    publicvoidsetButtonBind(RichButton buttonBind){
    this.buttonBind= buttonBind;
    }

    public RichButton getButtonBind(){
    return buttonBind;
    }

    /**Method to navigate from page1 to page2 if input text value is greater than 100
    * @param valueChangeEvent
    */
    publicvoidinputTextVCE(ValueChangeEvent valueChangeEvent){
    if(valueChangeEvent.getNewValue()!=null){
    Integer val = Integer.parseInt(valueChangeEvent.getNewValue().toString());
    if(val >100){
    //Code to queue button ActionEvent
    FacesContext facesContext = FacesContext.getCurrentInstance();
    UIViewRoot root = facesContext.getViewRoot();
    //Pass component client id to find button
    RichButton button =(RichButton) root.findComponent(buttonBind.getClientId());
    //Create and queue ActionEvent
    ActionEvent actionEvent =new ActionEvent(button);
    actionEvent.queue();
    }
    }
    }

    All Done :) You can set visible false for button if you don't want it on page
    Run and check application
    Enter a value greater than 100-

     Control moves to second page-
    Sample ADF Application - Download
    Cheers :) Happy Learning

    Execute batch file from Java Code using Runtime class

    $
    0
    0
    We can call any exe file from Java code using Runtime class, Runtime class extends Object class and introduced in JDK1.0

    What docs says-

    Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method.
    An application cannot create its own instance of this class.

    Here we will see how to execute .exe and .bat file from javacode, for executable files we just pass file path and Runtime class will invoke it. But for batch file we have to first open supporting application i;e Command Promt and then provide path for batch file

    See Java Programs for both case:

    Execute .exe file from Java- 


    package client;

    importjava.io.IOException;


    publicclassOpenExeFile{
    publicOpenExeFile(){
    super();
    }

    /**Main Method
    * @param args
    */
    publicstaticvoidmain(String[] args){
    //Get Runtime object
    Runtime runtime = Runtime.getRuntime();
    try{
    //Execute specific exe file, Provide path as parameter
    runtime.exec("calc.exe");//To open calculator

    }catch(IOException e){
    System.out.println(e);
    }
    }
    }

    Execute Batch file from Java-


    For this I have created a Batch file that opens Notepad
    To create Batch File

    • Open a notepad and paste this line
      start "c:\windows\system32" notepad.exe


    • Click on File-- SaveAs





    I saved this file in D drive of my Windows Machine, Now see code to open it from java


    package client;

    importjava.io.IOException;


    publicclassOpenBatchFile{
    publicOpenBatchFile(){
    super();
    }

    /**Main Method
    * @param args
    */
    publicstaticvoidmain(String[] args){
    //Get Runtime object
    Runtime runtime = Runtime.getRuntime();
    try{
    //Pass string in this format to open Batch file
    runtime.exec("cmd /c start D:\\OpenNotepad.bat");
    }catch(IOException e){
    System.out.println(e);
    }
    }
    }

    Cheers :) Happy Learning

    ADF Basics: Count number of records in LOV using LOV Accessor

    $
    0
    0
    Hello All

    This post is about a simple requirement - How to count number of records in a LOV ?
    I have seen this type of threads on OTN forum so here I am writing about it

    We can make use of LOV Accessor to  count number of records in LOV as per selected source viewObject record, Here I am using Departments and Employees table of Oracle HR Schema

    I have created a transient attribute in Department viewObject to show Department wise Employees LOV, To filter Employees ViewObject using Department Id  created a viewCriteria to filter it


    Now applied LOV on transient attribute (Created in Departments ViewObject) and passed Department Id in Lov Accessor to filter Employees list


    LOV part is done, Now to count number of records in Lov I have added one more transient attribute in Departments viewObject and used LovAccessorName.count("KeyAttributeName") to populate transient value, this expression will calculate number of records in LOV as per selected Departments record


    Now dropped this viewObject as form on page and see output

    Moving to Next Record-

    Now suppose if you want to disable lov when there is no records in list , for this just put a condition on lov component
     disabled="#{bindings.NoOfEmployee.inputValue==0}"

    Cheers :) Happy Learning
    Viewing all 165 articles
    Browse latest View live