Please disable your adblock and script blockers to view this page

Search this blog

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