Please disable your adblock and script blockers to view this page

Search this blog

Saturday 27 April 2013

Auto dismiss popup component with dialog- Oracle ADF

af:popup is container component for noteWindow, dialog, panelWinow, contextMenus, when we use popup with af:noteWindow, there is property autoDismissalTimeout is responsible for closing poup after some specific time.
But if we are using af:dialog in af:popup , how to close popup in this situation ?

Steps to do-

  • Create a fragment in bounded taskFlow and drag a button on which we have to open popup.
  • Drag a popup in page and showPopupBehavior inside button, pass id of popup and set trigger type to action to open poup on button click
af:popup in Oracle ADF
  •  Now drag a af:poll  component inside af:dialog
poll component delivers poll event to server at  fixed intervals, so we can use this property to fulfil our requirement .
  
Drop poll component inside popup

  • Select poll component in structure window and go to propertyInspector ,create poll listener  in managed bean and set Interval and Timeout to 4000 & 4001 (Timeout slightly greater than Interval time)-It means poll event delivers to server after 4000 ms or 4second




Create a poll listener in managed bean to deliver poll event at fixed interval

  • Now bind popup component to your managed bean, inorder to control poup properties
Create Component Binding for popup in managed bean
  • Close poup in pollListener(), means when after 4sec when poll event invoke server, it will close popup dialog automatically.

Sample ADF Application- Download

Thursday 25 April 2013

Memory Scope For ADF Managed Beans-As per Fusion Developer guide

Scope of managed bean is a very important aspect while developing applications, so it is necessary to clearly understand memory scope of managed bean-
As per Fusion Developer's Guide for Oracle Application Development Framework 11g Release 1 (11.1.1)-

Application Scope-

The application scope lasts until the application stops. Values that you store in a managed bean with this scope are available to every session and every request that uses the application.
Avoid using this scope in a task flow because it persists beyond the life span of the task flow.

Session Scope-

The session scope begins when a user first accesses a page in the application and ends when the user's session times out due to inactivity, or when the application invalidates the session.
Use this scope only for information that is relevant to the whole session, such as user or context information. Avoid using it to pass values from one task flow to another. Instead, use parameters to pass values between task flows. Using parameters gives your task flow a clear contract with other task flows that call it or are called by it. Another reason to avoid use of session scope is because it may persist beyond the life span of the task flow.

Pageflow Scope-




Choose this scope if you want the managed bean to be accessible across the activities within a task flow. A managed bean that has a pageFlow scope shares state with pages from the task flow that access it. A managed bean that has a pageFlow scope exists for the life span of the task flow.If another task flow's page references the managed bean, the managed bean creates a separate instance of this object and adds it to the pageFlow scope of its task flow.

View Scope-

Use this scope for managed bean objects that are needed only within the current view activity and not across view activities. It defines scope for each view port that ADF Controller manages, for example, a root browser window or an ADF region.
The life span of this scope begins and ends when the current viewId of a view port changes. If you specify view, the application retains managed bean objects used on a page as long as the user continues to interact with the page. These objects are automatically released when the user leaves the page.

Request Scope-

Use request scope when the managed bean does not need to persist longer than the current request.

Backing Bean Scope-

A backing bean is a convention to describe a managed bean that stores accessors for UI components and event handling code on a JSF page. It exists for the duration of a request and should not be used to maintain state.
Use this scope if it is possible that your task flow appears in two ADF regions on the same JSF page and you want to isolate each instance of ADF region.

Tuesday 23 April 2013

ADFC-00024-oracle.adf.controller.ControllerException:: No ExternalContext could be found.

 ADFC-00024- No ExternalContext could be found.
this is the exception, i have faced while working on my new ADF application and due to this exception application crashed(Internal Server Error-500)
After lot of googling and searching on OTN, i found a solution for this exception- but really don't understand that how it works-
log of ADFC-00024 problem-



 oracle.adf.controller.ControllerException: ADFC-00024: No ExternalContext could be found.  
      at oracle.adfinternal.controller.util.JsfInterfaceImpl.getExternalContext(JsfInterfaceImpl.java:394)  
      at oracle.adfinternal.controller.util.JsfInterfaceImpl.getRequestMap(JsfInterfaceImpl.java:143)  
      at oracle.adfinternal.controller.state.AdfcContext.getCurrentInstance(AdfcContext.java:219)  
      at oracle.adfinternal.controller.ControllerContextImpl.getViewPortByClientId(ControllerContextImpl.java:121)  
      at oracle.adf.controller.internal.binding.DCTaskFlowBinding.getGuardingPermission(DCTaskFlowBinding.java:204)  
      at oracle.adf.model.binding.DCBindingContainer.getGuardingPermission(DCBindingContainer.java:3849)  
      at oracle.adf.model.binding.DCBindingContainer.internalIsViewable(DCBindingContainer.java:3855)  
      at oracle.adf.model.binding.DCBindingContainer.isViewable(DCBindingContainer.java:3826)  
      at oracle.adf.model.binding.DCBindingContainer.resetSuspendedExecutables(DCBindingContainer.java:3490)  
      at oracle.adf.model.binding.DCBindingContainer.resetSuspendedExecutables(DCBindingContainer.java:3492)  
      at oracle.adf.model.binding.DCBindingContainer.internalRefreshControl(DCBindingContainer.java:3365)  
      at oracle.adf.model.binding.DCBindingContainer.refresh(DCBindingContainer.java:2911)  
      at oracle.adf.controller.v2.lifecycle.PageLifecycleImpl.prepareModel(PageLifecycleImpl.java:115)  
      at oracle.adf.controller.v2.lifecycle.Lifecycle$2.execute(Lifecycle.java:149)  
      at oracle.adfinternal.controller.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:197)  
      at oracle.adfinternal.controller.faces.lifecycle.ADFPhaseListener.access$400(ADFPhaseListener.java:23)  
      at oracle.adfinternal.controller.faces.lifecycle.ADFPhaseListener$PhaseInvokerImpl.startPageLifecycle(ADFPhaseListener.java:238)  
      at oracle.adfinternal.controller.faces.lifecycle.ADFPhaseListener$1.after(ADFPhaseListener.java:274)  
      at oracle.adfinternal.controller.faces.lifecycle.ADFPhaseListener.afterPhase(ADFPhaseListener.java:75)  
      at oracle.adfinternal.controller.faces.lifecycle.ADFLifecyclePhaseListener.afterPhase(ADFLifecyclePhaseListener.java:53)  
      at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl._executePhase(LifecycleImpl.java:439)  
      at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:204)  
      at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)  
      at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)  
      at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)  
      at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:300)  
      at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:26)  
      at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)  
      at oracle.adf.model.servlet.ADFBindingFilter.doFilter(ADFBindingFilter.java:173)  
      at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)  
      at oracle.adfinternal.view.faces.webapp.rich.RegistrationFilter.doFilter(RegistrationFilter.java:122)  
      at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl$FilterListChain.doFilter(TrinidadFilterImpl.java:468)  
      at oracle.adfinternal.view.faces.activedata.AdsFilter.doFilter(AdsFilter.java:60)  
      at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl$FilterListChain.doFilter(TrinidadFilterImpl.java:468)  
      at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl._doFilterImpl(TrinidadFilterImpl.java:293)  
      at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl.doFilter(TrinidadFilterImpl.java:199)  
      at org.apache.myfaces.trinidad.webapp.TrinidadFilter.doFilter(TrinidadFilter.java:92)  
      at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)  
      at oracle.adf.library.webapp.LibraryFilter.doFilter(LibraryFilter.java:180)  
      at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)  
      at oracle.security.jps.ee.http.JpsAbsFilter$1.run(JpsAbsFilter.java:111)  
      at java.security.AccessController.doPrivileged(Native Method)  
      at oracle.security.jps.util.JpsSubject.doAsPrivileged(JpsSubject.java:313)  
      at oracle.security.jps.ee.util.JpsPlatformUtil.runJaasMode(JpsPlatformUtil.java:413)  
      at oracle.security.jps.ee.http.JpsAbsFilter.runJaasMode(JpsAbsFilter.java:94)  
      at oracle.security.jps.ee.http.JpsAbsFilter.doFilter(JpsAbsFilter.java:161)  
      at oracle.security.jps.ee.http.JpsFilter.doFilter(JpsFilter.java:71)  
      at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)  
      at oracle.dms.servlet.DMSServletFilter.doFilter(DMSServletFilter.java:136)  
      at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)  
      at weblogic.servlet.internal.RequestEventsFilter.doFilter(RequestEventsFilter.java:27)  
      at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)  
      at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3715)  
      at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3681)  
      at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)  
      at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)  
      at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2277)  
      at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2183)  
      at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1454)  
      at weblogic.work.ExecuteThread.execute(ExecuteThread.java:209)  
      at weblogic.work.ExecuteThread.run(ExecuteThread.java:178)  

In my case this was due to Application Module configuration, in adf application we have two configuration .
  1. AMLocal
  2. AMShared
For local configuration ,in Pooling and Scalability there is Maximum Pool Size is 4096 but for shared it is only 1
i am not getting why this is so, then i have set Maximum Pool Size for shared configuration to 4096 and it is working-

Saturday 20 April 2013

Currency Conversion - Google Calculator API integration in ADF using GSON

First ,thanks to this post http://blog.caplin.com/2011/01/06/simple-currency-conversion-using-google-calculator-and-java/ .
I was looking for any API, webservice for retrieving live currency fluctuation, finally i came to this solution that integrates Google Calculator with Java to calculate currenct currency rates and i have integrated this with my Oracle ADF Application

I have created an application using bounded taskflow -
  • Created a .jsff page with two input text , to get value of Base and Term currency and a button, on which rate is calculated

  •  In order to use Goolge Calculator, we have to use GSON (open source java library (API) to convert JSON objects in POJO (pure java object)) 
  • To access GSON library we have to add google-gson-stream-2.2.1.jar in our project library - Download Gson Jar
  • this trick uses google calculator for calculating converion rate, as we all know Google Calculator is very smart, whenever we search like 1 USD ,it always shows results according to locale
As 1 USD searched in India-
As 1 USD searched in UK- 






  • this is also hidden benefit for our application , we can pass locale to get changed values also- now see what is the code that get values from Google Calculator

  •    public void calculateFluctuationButton(ActionEvent actionEvent) throws Exception {  
         String google = "http://www.google.com/ig/calculator?en=hi&q=";  
         /**Get values from page component binding*/  
         String baseCurrency = baseCurrencyBind.getValue().toString();  
         String termCurrency = termCurrencyBind.getValue().toString();  
         String charset = "UTF-8";  
         /**Replace url using your values-*/  
         URL url = new URL(google + baseCurrency + "%3D%3F" + termCurrency);  
         /**Go to url directly to see you result*/  
         System.out.println(url);  
         Reader reader = new InputStreamReader(url.openStream(), charset);  
         Result result = new Gson().fromJson(reader, Result.class);  
         System.out.println(result);  
         // Get the value without the term currency.  
         String amount = result.getRhs().split("\\s+")[0];  
         System.out.println(amount);  
         resultBind.setValue(amount);  
       }  
    

  • See in code i have passed currency notation from page (INR,USD ) to bean and passed it in url of google calculator and this url returns results
Download Complete Application -Sample ADF Application

Thursday 18 April 2013

Gmail Integration with Oracle ADF using Java Mail API

Gmail is a free secure webmail provided by google, can be accessed by using POP3 or IMAP4 protocol
we have option to integrate Gmail with Java using Java Mail API and I have tried same in Oracle
ADF.
I have developed an application that can send mail (with Attachements) using Gmail in Oracle ADF,
using bounded TaskFlow.

  • First , in bounded taskflow ,a login page is created, and a page to send mail is created
  • Now you can get values from page and use in bean- So I am not going to write these things
  • Integration points starts when you get mail server properties- Managed Bean Code
  • You have to use 2 JAR ,inorder to use Java Mail API
  1.mail.jar 2. Activation.jar- Download
    Properties emailProperties;

    public void setMailServerProperties() {
    String emailPort = "587"; //gmail's smtp port
    emailProperties = System.getProperties();
    emailProperties.put("mail.smtp.port", emailPort);
    emailProperties.put("mail.smtp.auth", "true");
    emailProperties.put("mail.smtp.starttls.enable", "true");

    }

  • Now you have to create your message (With or Without attachments)--
     

  • public void createEmailMessageWidtAtchmnt() throws AddressException, MessagingException {
    toWhom = toBind.getValue().toString();
    subject = subjectBind.getValue().toString();
    messagae = messageBind.getValue().toString();
    String[] toEmails = { toWhom };

    String emailSubject = subject;
    String emailBody = messagae;

    mailSession = Session.getDefaultInstance(emailProperties, null);
    emailMessage = new MimeMessage(mailSession);

    for (int i = 0; i < toEmails.length; i++) {
    emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmails[i]));
    }

    emailMessage.setSubject(emailSubject);

    //1) create MimeBodyPart object and set your message content
    BodyPart messageBodyPart1 = new MimeBodyPart();
    messageBodyPart1.setText(emailBody);

    emailMessage.setContent(emailBody, "text/html"); //for a html email


    }
  • here I am getting values from page component binding so don't get confused by this- toBind
    subjectBind, messageBind are component binding of page




  • Code snippet to create mail with attachements, you have to do little change in createEmailMessageWidtAtchmnt() to add files in mail . This code browse files from D drive
    of system .

  • //1) create MimeBodyPart object and set your message content
    BodyPart messageBodyPart1 = new MimeBodyPart();
    messageBodyPart1.setText(emailBody);

    //2) create new MimeBodyPart object and set DataHandler object to this object
    MimeBodyPart messageBodyPart2 = new MimeBodyPart();

    String filename = "D://" + file_name; //change accordingly
    System.out.println("Exact path--->" + filename);
    DataSource source = new FileDataSource(filename);
    messageBodyPart2.setDataHandler(new DataHandler(source));
    messageBodyPart2.setFileName(filename);


    //5) create Multipart object and add MimeBodyPart objects to this object
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart1);
    multipart.addBodyPart(messageBodyPart2);

    //6) set the multiplart object to the message object
    emailMessage.setContent(multipart);
  • To add files in mail in ADF you have to use af:inputFile component, and create a ValueChangeListener on component that get fileName when you browse any file from D drive of your system .

  • private String file_name;

    public void uploadedFileAttachmentVCE(ValueChangeEvent valueChangeEvent) {
    UploadedFile file = (UploadedFile)valueChangeEvent.getNewValue();
    file_name = file.getFilename();
    }
  • From login page you will get login emailId and password, that is set in managed bean code to authenticate user- and send mail

  • public void sendEmail() {

    String emailHost = "smtp.gmail.com";
    String fromUser = emailId; //just the id alone without @gmail.com
    String fromUserEmailPassword = pwd;
    Transport transport = null;
    try {
    transport = mailSession.getTransport("smtp");
    } catch (NoSuchProviderException e) {
    System.out.println("No such Provider Exception");
    }
    try {
    transport.connect(emailHost, fromUser, fromUserEmailPassword);
    transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
    transport.close();
    StringBuilder msgEmail = new StringBuilder("Email Sent");
    FacesMessage msg = new FacesMessage(msgEmail.toString());
    msg.setSeverity(FacesMessage.SEVERITY_INFO);
    FacesContext.getCurrentInstance().addMessage("No Network Error !", msg);
    System.out.println("Email sent successfully.");
    } catch (MessagingException e) {
    System.out.println("somthing went wrong-->Messaging Exception");

    }

    }

Monday 15 April 2013

Creating and Executing ViewCriteria Programmatically

Sometimes you need dynamic ViewCriteria that you can handle at runtime ,
here is the solution ,you can create and apply ViewCriteria Programmatically-



Sample UseCase-
  • Suppose you have Department VO
  • You want to filter this VO for DepartmentId 10
  • Do this using this code snippet

  • /**Get ViewObject*/
    ViewObject vo = getAm().getDepartments1();
    /**Create ViewCriteria on ViewObject*/
    ViewCriteria vc = vo.createViewCriteria();
    /**Create ViewCriteriaRow for that Criteria*/
    ViewCriteriaRow vcRow = vc.createViewCriteriaRow();
    /**Set the values for ViewCriteriaRow*/
    vcRow.setAttribute("DepartmentId", 10);
    /**Add row to ViewCriteria*/
    vc.addRow(vcRow);
    /**Apply Criteria on ViewObject*/
    vo.applyViewCriteria(vc);
    /**Execute ViewObject*/
    vo.executeQuery();

    public pcAMImpl getAm() {
    pcAMImpl am = (pcAMImpl)resolvElDC("pcAMDataControl");
    return am;
    }

Thursday 11 April 2013

Invoking Button Action Programmatically,Queuing ActionEvent

Sometimes we need to invoke any button's action in bean without pressing that button,
as you have to call button action on any component's value change Listener- So how to do this in ADF managed bean.
ADF provides facility to queue action one after another, means you can perform multiple action by queuing 

I am using bounded task flow with page fragments(.jsff)-

  • Create a button in page fragment and define ActionListener in managed bean
  • Now I have created a input text and its valueChangeListener in managed bean
  • I wish to call button' ActionListener in my input text valueChangeListener .




  • we can do this by writing this code snippet on valueChangeListener 

  • public void callAceVCE(ValueChangeEvent vce) {
    if (vce.getNewValue() != null) {
    //Code to call ActionEvent
    FacesContext facesContext = FacesContext.getCurrentInstance();
    UIViewRoot root = facesContext.getViewRoot();
    /**Pass cb1(buttonId) if page is not in taskflow, else if page is inside region then pass rgionid:buttonId*/
    RichCommandButton button = (RichCommandButton)root.findComponent("r1:cb1");
    ActionEvent actionEvent = new ActionEvent(button);
    actionEvent.queue();
    }
    }

  •  Now run your page and when you will change input text value - button actionListener will be called

Global Exception Handler for ADF Task Flow Method Calls

Exception Handler is the central point for handling unexpected Exceptions that are thrown during the Faces lifecycle.
ADF Task Flow provides this facility, using this you can handle all exception that raised in TaskFlow methods.
here i am using ADF bounded TaskFlow with page fragments(.jsff) .
Developers must use this facility to avoid unexpected exception inside taskflows.

This is very simple approach , you have to do nothing more but create a method in Task Flow and mark it as Exception Handler and write your code inside this method , that you want to show when any exception is caught in TaskFlow.

To implement this i have implemented this scenario-

  • Create a method that throw an Exception and add it to taskFlow, and on page call this method on button click

  • public void exception() {
    throw new JboException("Failded to load");
    }
Control Flow Case in Bounded taskFlow
  • When we click on button that call exception() method ,JboException is raised inside TaskFlow and look like this- Your page crashed

  • Now create a method that will behave as ExceptionHandeler  and add it to TaskFlow and mark as Exception Handeler (Symbol in Jdev toolbar for marking)

  • public void exceptioHandeler() {
    System.out.println("Inside Handeler");
    FacesMessage message = new FacesMessage("This is custom Message for Jbo Exception-Exception Handeler");
    message.setSeverity(FacesMessage.SEVERITY_WARN);
    FacesContext fc = FacesContext.getCurrentInstance();
    fc.addMessage(null, message);

    }

Drop a method as Exception Handler in Bounded Taskflow
  • Use this sign to mark method as Exception Handeler in bounded Task Flow




There is a red icon to mark method as exception handler

  • Now Run your page and click on button that call exception() method, your page never crash, as there is handler
Customised Message appears in case of any exception in taskflow
Find Sample application Download Sample ADF Application

Thursday 4 April 2013

Currency- A Java Utility, Get currency code , symbol using Locale in Java

Java provides utility classes inside java.util package.
java.util.Currency is very interesting class in this package,it represents currencies defined in ISO 4217 by 
their currency codes.
You can get currency codes, its symbol, default fraction digits using its method.




java.lang.Object
  extended by java.util.Currency 


see this short example , how we use Currency Class in Java,You can also get 
live currency fluctuation in java using Currency Converter API
 
package practiceJava;

import java.util.Currency;
import java.util.Locale;

public class CurrencyDemo {

    public static void main(String[] args) {
        // create a currency object with  locale
        Locale locale = Locale.US;
        Currency curr = Currency.getInstance(locale);
        System.out.println("Locale's currency code:" + curr.getCurrencyCode());
        // Get symbol for Currecny
        String symbol = curr.getSymbol();
        System.out.println("Symbol is :" + symbol);
        // Get default fraction digit for Currecny
        int frDigit = curr.getDefaultFractionDigits();
        System.out.println("Default fraction digit : " + frDigit);

    }
}


Output look like this

Wednesday 3 April 2013

Inline PopUp with noteWindow (Excellent feature) in Oracle ADF

A very good and flexible component in adf is af:popup. we can use popup in various ways.
Suppose sometimes we need to show short description or some detail about any text ,button on Mouse Hover, then we can use inline PopUp (excellent look and feel)

For this you have to follow these steps-
  • Create a page in your bounded taskflow, drag an output text in page for that we are going to show Short Description.
  • Drag n drop a pop component in page in which we show description for that output text


Drop an af:popup component on page


  • Now drop a noteWindow under popup component 
Drop af:noteWindow component under popup





  •  and write your description in source of .jsff page in notewindow component
<af:popup childCreation="deferred" autoCancel="disabled" id="p1">
      <af:noteWindow id="nw1" inlineStyle="width:200px;" autoDismissalTimeout="5">
                       <p><b>Penguins</b> <b><font color="maroon">(order Sphenisciformes, family Spheniscidae)
                       are a group of aquatic, flightless birds living almost
                       exclusively in the southern hemisphere, especially in
                       Antarctica.</font></b> <b><font color="Green"> adapted for life in the water, penguins
                       have countershaded dark and white plumage, and their wings
                       have evolved into flippers</font></b></p>
      </af:noteWindow>
    </af:popup>
  • Drag showPopupBehavior inside output text for that you have to show that popUp
Use showPopupBehavior to show popup on mouse hover event

  • Now pass popup id in showPopupBehavior and set trigger type to mouseHover 
Set triggerType property of af:showPopupBehavior



  • Run your page and see how it look-- It is just awesome

    And this is very good that you can show graphs, tables and other information on this type of inline popUp 
    You can find sample application here- Download Sample Application