Please disable your adblock and script blockers to view this page

Search this blog

Showing posts with label Jdeveloper 11g. Show all posts
Showing posts with label Jdeveloper 11g. Show all posts

Saturday 1 June 2013

Using JQuery in Oracle ADF

JQuery is advance javascript library to support client side scripting of HTML, it is free and Opensource software licensed under MIT.
Jquery is designed to make it easier to create animations, enhance look feel of component, smooth navigation.
Read about Jquery- http://jquery.com/ , https://jquery.org/
here i am showing you, how to add Jquery in oracle ADF application.

  • First add Jquery library to your fusion web application, download library file Download
  • Add this file to javascript resources, see image
  • Now create a javascript(Jquery) file to change color of af:inputText, here is javascript code is given




  • function changeColor() {
        if ($("input[name=it1]").val() != null) {
           if (($("input[name=it1]").val().length > 0) && ($("input[name=it1]").val().length < 3)) {
                $("input[name=it1]").css("color", "magenta");
            }
          else if (($("input[name=it1]").val().length > 3) && ($("input[name=it1]").val().length < 6)) {
                $("input[name=it1]").css("color", "red");
            }
            else if (($("input[name=it1]").val().length >= 6) && ($("input[name=it1]").val().length < 9)) {
                $("input[name=it1]").css("color", "yellow");
            }
             else if (($("input[name=it1]").val().length >= 9) && ($("input[name=it1]").val().length < 12)) {
                $("input[name=it1]").css("color", "maroon");
            }
             else if (($("input[name=it1]").val().length >= 12) && ($("input[name=it1]").val().length < 15)) {
                $("input[name=it1]").css("color", "teal");
            }
             else if (($("input[name=it1]").val().length >= 15) && ($("input[name=it1]").val().length < 18)) {
                $("input[name=it1]").css("color", "blue");
            }
            else {
                $("input[name=it1]").css("color", "green");
            }
        }
    }
    

  • Now create a jspx page , and call this JS file as a resource in jspx page, and also add Jquery Lib to jspx page as Resource

  • Now add a input text in page, and call javascript resource using af:clientListener

  • See the code of jspx page-

  • <?xml version='1.0' encoding='UTF-8'?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1" xmlns:f="http://java.sun.com/jsf/core"
              xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
        <jsp:directive.page contentType="text/html;charset=UTF-8"/>
        <f:view>
            <af:document title="JqueryADF.jspx" id="d1">
             <af:resource type="javascript" source="/javascript/libs/jquery-1.4.4.js"/>
             <af:resource type="javascript" source="/resources/js/inputText.js"/>
                <af:form id="f1">
                <af:inputText label="Chck JQ" id="it1" contentStyle="font-weight:bold;">
                            <af:clientListener type="keyDown" method="changeColor"/>
                        </af:inputText>
                
                </af:form>
            </af:document>
        </f:view>
    </jsp:root>
    

  • Now Run this application and enter value in input text field and see how color is changing with length




  • You can use this , with your password field, for any kind of alert, to make 'Find and Enter' games
  • One more thing , it is difficult to use Jquery with pagefragments because in page fragments component id's are like :t1:cb1, r1:t1:it2. and jquery does not support ':' so you can easily use this with .jspx page
  • Sample ADF application -Download

Thursday 30 May 2013

Add Custom Flash Chat in Oracle ADF Application

In this tutorial i am going to show that how can you add a custom flash chat in your ADF application, and use it to chat with friends.
this is very much simple, as no code required to do this.
  • Go to http://www.everywherechat.com/ , this site provides free custom flash chat rooms, get html code of your custom chat from here
  • Create an html page using that code




  • <html>
    <body>
    <!-- Begin Everywherechat Room Code -->
        
          <br />
         <script src="http://www.everywherechat.com/e.php?defaultRoom=Lobby&roomList=true&fontSize=12&width=600&height=500&theme=night"></script> 
    
    <!-- End Everywherechat Room Code --> 
    </body>
    </html>
    

  • Now create a Fusion Web Application and create a page in it, call this HTML page in an inlineFrame (af:inlineFrame)

  • <?xml version='1.0' encoding='UTF-8'?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1" xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
      <af:panelGroupLayout id="pgl1">
        <af:inlineFrame id="if1" source="/chat.html" inlineStyle="height:700px;width:700px;"/>
      </af:panelGroupLayout>
    </jsp:root>
    

  • Now Run your application and see your flash chat room is ready - Happy Coding

    Download Sample Application-Sample ADF Application

Tuesday 21 May 2013

Generate Barcode Image in Oracle ADF using OnBarcode API

In this tutorial we will learn how to generate Barcode Image for any Number(Barcode) in ADF using OnBarcode API, this API provides barcode SDK(Software Development Kit) to generate Barcode. This is paid.
You can get it from http://www.onbarcode.com/  , click on Download to get barcode SDK.
  • Now create a fusion web application and add barcode.jar to project libraries, you will get this JAR , when you download SDK
  • Good thing about this API is that it is very simple to use, not much code required to generate a simple barcode image
  • You can generate multiple type of Barcode as Code 39, Code 128, EAN-8, EAN-13, UPC-A, UPC-E
  • Suppose i have to generate a Code128 type of Barcode for any barcode number, so for this write this simple code and you are done




  • Code128 barcode = new Code128();
    
    barcode.setData("122322311");
    barcode.drawBarcode();  
     
  • Download sample application that integrates this API with Oracle ADF Download Sample ADF Application 
  • Unzip and Run this application

     
  • I have used a servlet in order to show image on page fragment

Monday 20 May 2013

Set and Get Value from Taskflow parameter (pageFlowScope variable) from Managed Bean- ADF

Hello All

This post is about getting and setting value in taskFlow parameter using Java Code so for that we have created a application with bounded taskFlow

Let's see how to do this -

We have bounded taskflow having Input Parameter defined in it named GLBL_PARAM_TEST

Bounded Taskflow Input Parameters

and we have to set its value from managed bean.
this is very simple -see how to do that
  • Get pageFlowScope Map and put parameter 's value in it

  •         Map paramMap = RequestContext.getCurrentInstance().getPageFlowScope();
            paramMap.put("GLBL_PARAM_TEST", "Ashish"); 

  • And get Value from taskFlow parameter in managed bean



  •     public String resolvEl(String data){
                   FacesContext fc = FacesContext.getCurrentInstance();
                   Application app = fc.getApplication();
                   ExpressionFactory elFactory = app.getExpressionFactory();
                   ELContext elContext = fc.getELContext();
                   ValueExpression valueExp = elFactory.createValueExpression(elContext, data, Object.class);
                   String Message=valueExp.getValue(elContext).toString();
                   return Message;
                 }
    
    
    String param=resolvEl("#{pageFlowScope.GLBL_PARAM_TEST}");
    

Wednesday 15 May 2013

Beauty of ADF- Taskflow, Difference b/w Facelets and JSP XML fragments in bounded taskflow

Oracle ADF framework support modular architecture for enterprize application development. Multiple small module can be bound together to form a large module .
The greatest advantage of ADF controller over core JSF navigation model is that it splits a single bulky module to multiple reusable and interconnected modules known as Taskflows.

i am not going deeper in Taskflows as every ADF developer know about it ,so the important part is page fragment.
  • When  we create taskflow as bounded taskflow , and check it to create fragment in taskflow.
  • Now when we create pagefragment in bounded taskflow, there is 2 option for creating fragment




Create fragment as Facelets
Create fragment as JSP XML 

Page Fragment Type - Facelets or JSPX

Facelets- is default and official view handler for JSF pages, priviously JSP was used to view JSF pages but it didn't support all component so Facelets comes in picture under APACHE open source license. It supprts all UI component used by JSF (Java Server Faces).
Facelets was developed by Jacob Hookom in 2005.
If you create Facelets fragment in bounded taskflow, then taskflow must be dropped in a JSF page (parent page) not in .jspx (JSP XML ) page.
if you try to drop it into JSP XML page-


JSP XML- jspx is XML variant of JSP(Java Server Pages) to support XML document . JSP XML fragments are used in ADF inorder to support XML document and more powerful page validation techniques.
If you create jsp xml fragments in bounded taskflow, then taskflow must be dropped in a JSP XML(.jspx) page(parent page) not in JSF page.

Tuesday 14 May 2013

Using Contextual Event in Oracle ADF (Region Communication)

Contextual event ,in simple terms is a way to communicate between taskflows.
Sometimes we have taskflow open in a region and have to get some values from that taskflow .
This scenario can be achieved by contextual event.

 
Contextual Event have two parts-
  1. Publisher Event (Producer)- As button or any component that can raise event 
  2. Handler Event (Customer)- that listens and process event published by producer
This tutorial is based on example developed on default HR schema of Oracle DB 11g
I have created two application and called first one in secod application as region.
  • Create first application using Department table of HR schema and drag Department Name on page fragment, now create publisher event (follow steps) for Department Name .
  • Select Department Name field in structure window and go to property Inspector select ContextualEvent
    click on green add icon and select event type and name for publisher event

  • Select field value from Iterator Binding
  • here you are done with publisher event or producer create a jar of this application in order to use it in second application.
  • Now start Second Application that will handle and process this event, create a page and put an output text and set its value from managed bean


  • Now create a event handler class to process published event and to make it available to page binding level , we have to create DataControl for this class.





  • Right click on event class and Click on CreateDataControl.
  • Now add this method binding to page so that it can be accessible from page binding
  • Now drag and drop taskflow from jar library on page as region by this published event will also be available to page
  • Now go to page binding and goto ContextualEvents tab ,click on subscribers tab and click on add icon this will open a popup window ,click on search button , it will show available publisher event, now select event and goto handler search option and select function that you have previously added in page binding
  • Give consumer parameter name same as event handler function

Now Run your Application - Download ADF Sample Application

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");

    }

    }

Thursday 11 April 2013

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

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

Sunday 3 March 2013

'filterFeatures' in ADF table column, caseInsensitive search in af:table filter

Quite small but useful trick-

In ADF table column when we apply search using filter it matches case (A-Z,a-z), means by default search is case sensitive, to change it you can change a property in column.



When you select a column and go to propertyInspector ,change 'filterFeatures' to 'caseInsensitive'
and It will search data in table without matching case

filterFeature property of table column to handle case sensitive search