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.

How to get the view object instance in the managed bean from pagedef file in Oracle ADF?

Sometimes during the implementation of Oracle ADF applications we might need programmatic access to the underlying View Object. It is not advisable to create the instance of the ADF model business components directly.

We can get the view Object from the iterator in the pagedef file of the corresponding page or page fragment. If suppose the iterator is as shown in the below diagram.









The following code will get the view object from the Iterator.



Monday, March 10, 2014

How to get auto complete in editing css files for Oracle ADF skinning?

By default whenever we type anything in the editor, we get the auto complete option from the JDeveloper. It is not the case for editing the css files using the JDeveloper. We have to enable the supported components option as shown below to get the auto complete.

go to tools -> preferences -> CSS Editor. Enable the checkbox "ADF Faces Extension"


Once done we get the auto complete options in writing the skin selectors in the css file. This is a very useful tip and avoids the user to remember the skin selectors.


How to create deploy and reuse the taskflow/datacontrol as a library in Oracle ADF application? How to Reuse taskflow of one application in another in ADF?

Many a times we might need to use the taskflow or datacontrol of one ADF application in another. For example if there is an application module with much of business functionality then we might want to reuse the entire AM in another application. This can be achieved in many ways. One way is to create a library out of the ADF application and deploy it and reuse it as an artifact in another application. The following approach explains this.

Step1: Create the library out of ViewController project application

  1. Double click the view controller project
  2. In the project properties dialog, click the Deployment section
  3. Create a new deployment profile by clicking the New option
  4. In the archive type select the ADF library jar file as shown below



ADF libraries is a Java Archive (JAR) file concept in ADF that contains a specific manifest file that allow Oracle JDeveloper to detect and import reusable components so they show in the ADF Component palette.

Step2: Deploy the taskflow/UI project using the newly created deployment profile

Now that we have created the deployment profile, we will deploy the project and its artifacts as the ADF library so that it can be imported and used in another application. Deployment is done as below









Step3: Import the deployment in another application
  1. Create the file system connection in the resource palette to point to that directory as shown below. Give some connection name and in the directory path, point to the jar file deployed directory 
  2. Select the deployment and say add to the project as shown below.


  1.  
  2. On doing that we observe the new data control and the new connection are also imported to the current project. 
  3. We can thus use the service methods from the imported data control
  4. We can also observe in the below image about how to import the region from the imported library from the component palette




One important thing to note is the naming convention here. If the package names are same in the imported library and the current project then we will have the naming conflicts and the fucntionality will not work as expected. The better naming convention is to com.project_name.resource_package

Friday, March 7, 2014

How to implement skinning in Oracle ADF ?

In order to implement the skinning we need to configure three files in oracle ADF.


  1. trinidad-skins.xml by default this file is not present on creating the Oracle ADF fusion application. We have to create this file in the WEB-INF directory. This is the file where we register and configure all the available for this application. For each skin we have several properties to be configured. A sample trinidad-skins.xml looks as below.

      <?xml version="1.0" encoding="windows-1252" ?>
      <skins xmlns="http://myfaces.apache.org/trinidad/skin">
       <skin>
      <id>custom.skin.adf.app</id>
      <family>MyApplicationSkin</family>
      <extends>blafplus-rich.desktop</extends>
      <render-kit-id>org.apache.myfaces.trinidad.desktop</render-kit-id>
      <style-sheet-name>css/myapp-layout.css</style-sheet-name>
       </skin>
      </skins>



  2. trinidad-config.xml: If there are more than one skin defined in the trinidad-skins.xml, then we can choose one of them to be active on the current application. This is the file where we specify the skin that is applied in the current application.

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


  • css file: This is file where define the look and feel of each and every component. We have to use and identify various ADF skin selectors mentioned in this link.


  •  By default in the adf application we create, the fusion skin is applied and the look and feel is as below.



    After applying selectors and modifying the myapp-layout.css file the look may be as below.


    How to get Locale/Language in ADF BC, ADF Faces and using Expression language - Oracle ADF

    Many times we might need get the locale of the user and may be manipulate the skins or business logic based on that. By default, ADF Faces determines the locale of the end user by inspecting the browser language settings.

    Get the locale in ADF Business Components Java Class

    import java.util.Locale;
    import oracle.adf.share.ADFContext;

    Locale locale = ADFContext.getCurrent().adfctx.getLocale();

    Get the locale in ADF Managed Bean

    import java.util.Locale;
    import javax.faces.context.FacesContext;

    Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();

    Get the locale using expression language

    #{facesContext.ViewRoot.locale.language}

    Once we get the locale, we can get the user language using either of the below methods

    1. String userLang = locale.getLanguage();
    2. #{facesContext.ViewRoot.locale.language}


    Thursday, March 6, 2014

    javax.el.ELException: oracle.adfinternal.controller.savepoint.SavePointException: ADFC-08011: Oracle ADF

    Sometimes we get the following error when working with oracle ADF

    javax.el.ELException: oracle.adfinternal.controller.savepoint.SavePointException: ADFC-08011: The JNDI connection name is not specified in configuration file adf-config.xml.

    This is because the data source is not configured in the adf-config.xml which tells the framework the place the store the current snapshot of the application

    Wednesday, March 5, 2014

    oracle.jbo.JboException: JBO-34010: The "view/DataBindings.cpx" descriptor appears in the application classpath more than once:

    The above error occurs when the current project under development is including an external library (May be another ADF application). There can be package name conflicts which is causing this issue. The databindings.cpx is present in the same package (folder structure) in the imported library and the current package.

    Best practice is to use the unique names often starting the package name with the short form of the current application.