Thursday, March 27, 2014

Execute a client/javascript method on commandlink click in adf?

Sometimes we want to execute a client method which is present in the javascript on a button lick or a commandlink click in oracle ADF. This can be done in two ways

Method #1

Set the attribute <af:clientListener> for the command item as shown below

<af:commandLink text="Click me" id="cl1"
                immediate="true" partialSubmit="true" blocking="true"
    <af:clientListener type="action" method="javascriptMethod"/>
</af:commandLink>


Set the java script as shown below
 
<af:resource type="javascript">
  function disableUserInput(evt) {
      evt.cancel();
      evt.stopPropagation();
  }    

</af:resource> 

Method #2

Create and execute the javascript programmatically in backing bean or managed bean as shown below

import org.apache.myfaces.trinidad.render.ExtendedRenderKitService;
import javax.faces.context.FacesContext;
import org.apache.myfaces.trinidad.util.Service;


String myScript =
    "document.getElementById(clientId).tabIndex = \"-1\";";
ExtendedRenderKitService renderKitService =
    Service.getRenderKitService(FacesContext.getCurrentInstance(),
                                ExtendedRenderKitService.class);
renderKitService.addScript(FacesContext.getCurrentInstance(),
                           myScript);

 

Wednesday, March 26, 2014

How to put and get some data from Oracle Coherence Cache? Basic code snippets of Oracle Coherence

package javaapp;

import com.tangosol.coherence.transaction.OptimisticNamedCache;
import com.tangosol.net.CacheFactory;
import com.tangosol.net.NamedCache;
public class CoherenceClient {
    public static void main(String[] args) {
        CacheFactory.ensureCluster();
        // Get an instance of the coherence cache
        NamedCache cache = CacheFactory.getCache("hello-example");
       
        // Put some elements into cache
        putElementsinCoherence(cache);
       
        // Print all the existing elements in the coherence cache
        printCohrenceCacheElements(cache);
        removeAllElementsFromCoherenceCache(cache);
       
        // Destroy the cache
        cache.destroy();
       
        // Try to print the elements in the c
        printCohrenceCacheElements(cache);
        CacheFactory.shutdown();
    }
   
    public static void putElementsinCoherence(NamedCache cache) {
            for(int i=0;i <10; i++) {
                // Put some dummy elements in the cache
                cache.put(i, "Vinay " + i);
        }
    }

    public static void printCohrenceCacheElements(NamedCache cache) {
        // Check if the cache is active
        if(cache.isActive()) {
            System.out.println("Printing all the elements of " + cache.getCacheName());
            for(Object key : cache.keySet()) {
                // Print the elements fromt he cache
                System.out.println((String)cache.get(key));
            }      
           
        }
    }

    public static void removeAllElementsFromCoherenceCache(NamedCache cache) {
        // Remove all the elements from the cache
        cache.clear();
    }
}

Thursday, March 20, 2014

How to get the original value and modified value of an attribute before committing in Oracle ADF entity Object?

Sometimes we might need the attribute's modified value and the original value before committing the data to the database. We might need the data either to store the history of changes to a particular record or for any other purpose. We have to override the doDML() method of the EOImpl method and use the getPostedAttribute() to get the original value

Using the getPostedAttribute() method, your entity object business logic can consult the original value for any attribute as it was read from the database before the entity row was modified. This method takes the attribute index as an argument, so pass the appropriate generated attribute index enums that JDeveloper maintains for you.

Sample code is as below

protected void doDML(int operation, TransactionEvent e) {
    System.out.println("First Name old value: " + getPostedAttribute(AttributesEnum.FirstName.index()));

    // Or use the index directly
    System.out.println("First Name old value: " + getPostedAttribute(EMPLOYEEID));

    System.out.println("First Name new value: " + getFirstName());
    super.doDML(operation, e);

}

Effective use of getEntityState() and getPostState() methods in EOImpl class in Oracle ADF

You can use the getEntityState() and getPostState() methods to access the current state of an entity row in your business logic code.

The getEntityState() method returns the current state of an entity row with regard to the transaction

getPostState() method returns the current state of an entity row with regard to the database after using the postChanges() method to post pending changes without committing the transaction.

The sample code is as below

public void postChanges(TransactionEvent transactionEvent) {
    /* If current entity is new or modified */
    if (getPostState() == STATUS_NEW || getPostState() == STATUS_MODIFIED) {
    }
}

The possible outcomes of the getPostState() method are as follows
  • STATUS_UNMODIFIED - if this Entity Object has been queried from the database and is unchanged, or if it has been posted to the database.
  • STATUS_MODIFIED - if this Entity Object has been queried from the database and has changed.
  • STATUS_NEW - if this Entity Object is new and not yet posted to the database.
  • STATUS_INITIALIZED - if this Entity Object is new and the client code marks it to be temporary by calling Row.setNewRowState method.
  • STATUS_DELETED - if this Entity Object has been marked for deletion.
  • STATUS_DEAD - if this Entity Object is new, but has been deleted.

Wednesday, March 19, 2014

How to generate sample test client to test Facade from Session EJB in Oracle ADF Model?

I have explained in the previous post about how to create the session bean based on the JPAs created for EJB based entities.

In this post I shall show how to create a sample test client to test the same


























It will generate the client with sample methods to access the data from sessionEJB. Sample code is as below

public static void main(String [] args) {
    try {
        final Context context = getInitialContext();
        SessionEJB sessionEJB = (SessionEJB)context.lookup("EJBBasedADFAppli-Model-SessionEJB#model.SessionEJB");
        for (Departments departments : (List<Departments>)sessionEJB.getDepartmentsFindAll()) {
            printDepartments(departments);
        }
        for (Employees employees : (List<Employees>)sessionEJB.getEmployeesFindAll()) {
            printEmployees(employees);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}


How to create session bean that implements entities based on EJB in Oracle ADF?

In this blog post, I am showing the way to create the session bean for the entities based on JPA and EJB in Oracle ADF







Click next-> next and finish to see the session Facade create with all methods as per image #3. In the next blog I will explain about how to create a sample test client and test the session Facade

Tuesday, March 18, 2014

How to override the default sort behavior of the af:table in Oracle ADF?

When ever you set the sortable="true" for any column in the af:table, we get the two options to sort the column (ascending or descending) as shown below








In order to override the default behavior, we have to configure the sort listener as below in the table properties














Add the following code in the sort listener and plugin the bahavior as required

import java.util.ArrayList;
import java.util.List;
import oracle.adf.view.rich.component.rich.data.RichTable;
import oracle.adf.view.rich.context.AdfFacesContext;
import org.apache.myfaces.trinidad.event.SortEvent;
import org.apache.myfaces.trinidad.model.SortCriterion;

public void onSortingTableColumn(SortEvent sortEvent) {
    List sortList = sortEvent.getSortCriteria();
    SortCriterion sc = (SortCriterion)sortList.get(0);
    boolean order = sc.isAscending();

    System.out.println(sc.getProperty());    
    System.out.println(order);
    
    sortList = new ArrayList();    

    // In the sort criteria parameters set the column by 
    // which you would like to sort and the order (asc, desc)
    // pass true if you want to sort in the ascending order 
    // and false otherwise
    String sortCol  = sc.getProperty().toString();
    
    // Create the desired search criteria here
    SortCriterion sc2 = new SortCriterion(sortCol, order);
    sortList.add(sc2);
    getTestDepTable().setSortCriteria(sortList);

    // Refresh the table after applying the sort criteria
    AdfFacesContext.getCurrentInstance().addPartialTarget(getTestDepTable());
}

Monday, March 17, 2014

How to fire a entity level validation on an attribute change in ADF BC?


by default JDeveloper allows you to select the attributes that trigger validation, so that validation execution happens only when one of the triggering attributes is dirty.In previous releases of JDeveloper, an entity-level validator would fire on an attribute whenever the entity as a whole was dirty.

Specifying the attributes which when changed trigger the entity level validation
  1. Create the entity level validation with the required rule type
  2. Go to the Validation execution tab to select the condition when the rule should be fired. This is the place where we should select if changes to a particular attribute should fire the current business rule. 
  3. This is shown in the below image 

  1. We can select more then one attribute in the triggering attributes dialog.
  2. Firing execution only when required makes your application more performant.

Thursday, March 13, 2014

How to programmatically navigate in ADF?

Sometimes we might need to programmatically execute the navigation and redirect to another page in Oracle ADF. This can be done in two ways

Approach #1

Get the navigation handler handle from the application context and pass the appropriate arguments to that. A sample code to achieve the same is as below.

import javax.faces.context.FacesContext;
import javax.faces.application.Application;
import javax.faces.application.NavigationHandler;

public void handleNavigation() {
    FacesContext context = FacesContext.getCurrentInstance();
    Application app = context.getApplication();
    NavigationHandler handler = app.getNavigationHandler();
    handler.handleNavigation(context, null, "navigation-action");
}

If you see the signature of the handleNavigation method, it is as below
public abstract void handleNavigation(FacesContext context,
                                      String fromAction,
                                      String outcome)

Approach #2
  1. Have a command button with action set on it.
  2. Make the visible property of the button false. 
  3. Programmatically execute the action of the button to navigate to the required page. In this way we hide the button and achieve the navigation. The sample code for the same is as below

import javax.faces.context.FacesContext;
import javax.faces.component.UIViewRoot;
import javax.faces.event.ActionEvent;
import oracle.adf.view.rich.component.rich.nav.RichCommandButton;

public void handleNavigation() {
  FacesContext facesContext = FacesContext.getCurrentInstance();
  UIViewRoot root = facesContext.getViewRoot();
  RichCommandButton button = (RichCommandButton) root.findComponent("button-id");
  ActionEvent actionEvent = new ActionEvent(button);
  actionEvent.queue();
}

Wednesday, March 12, 2014

Get the button pressed on af:dialog in the managed bean in ADF?

For this scenario let us assume that we are handling a dialog with three buttons Yes, No and Cancel as shown below













Step1

In this step bind the DialogListener of the af:dialog to the managed bean method which will be executed on clicking any button on the dialog. This can be configured as shown below from the property inspector.








Step2

get the button pressed as shown in the below code and perform the respective action.

import oracle.adf.view.rich.event.DialogEvent.Outcome;
import oracle.adf.view.rich.event.DialogEvent;

public void onDialogButtonPress(DialogEvent dialogEvent) {
Outcome dialogOutcome = dialogEvent.getOutcome();

if(dialogOutcome == Outcome.yes) {

}
else if (dialogOutcome == Outcome.no) {

}
else if (dialogOutcome == Outcome.cancel) {

}
}

Note:  The cancel event is deprecated and should be handled at the client side or invoke the server side event from client side. I shall explain this in another post.