Please disable your adblock and script blockers to view this page

Search this blog

Showing posts with label Download. Show all posts
Showing posts with label Download. Show all posts

Monday 12 January 2015

Send eMail and attachement from any SMTP server using JavaMail in Oracle ADF


The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications- JavaMail API

This post is about sending eMail and attachments from any SMTP (Simple Mail Transfer Protocol) as Gmail or any other server (mail.awasthiashish.com)
You can read my previous post about mail integration with ADF that was specifically about using Gmail Server
Gmail Integration with Oracle ADF using Java Mail API 

So all basic configuration is described in previous post , now in this post i am only writing a java method to send mail and attachments


Don't forget to download these 2 jar files
  1.mail.jar 2. Activation.jar- Download
Add both jar files to project library path and then use this method 
Necessary packages to import -


import java.util.ArrayList;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;

import javax.activation.FileDataSource;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;


Helper method (JavaCode) to send simple eMail and eMail with attachment-

    /**Method to send mail from any SMTP server using JavaMail API
     * Provide Correct Parameters
     * @return
     * @param msg- Email Message Body
     * @parsm subject- Subject of Email
     * @param FromUser- Email Id of Sender
     * @param ToUser- Email Id of Reciever
     * @param pwd- Password of sender's email address
     * @param hostName- Host Name of Mail server (smtp.gmail.com)
     * @param isAnyAtchmnt- "Y" for yes there is an attachement and "N" for no attachment
     * @param fileNamePath- abolute path of file on server if there is any attachement
     */
    public String sendMail(String msg, String subject, String FromUser, ArrayList<String> ToUser, String pwd,
                           String hostName, String isAnyAtchmnt, ArrayList<String> fileNameNPath) {
        // Setting Properties
        Properties emailProperties = new Properties();
        emailProperties.put("mail.smtp.host", hostName);
        emailProperties.put("mail.smtp.auth", "true");
        emailProperties.put("mail.smtp.starttls.enable", "true");
        //Login Credentials
        final String user = FromUser; //change accordingly
        final String password = pwd; //change accordingly
        //Authenticating...
        Session session = Session.getInstance(emailProperties, new javax.mail.Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, password);
            }
        });

        //1) create MimeBodyPart object and set your message content
        MimeMessage message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(user));
            for (String email : ToUser) {
                System.out.println("Mail Id is-" + email);
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
            }
            message.setSubject(subject);

            BodyPart messageBody = new MimeBodyPart();

            messageBody.setContent(msg, "text/html");

            // If there is any attachment to send
            //5) create Multipart object and add MimeBodyPart objects to this object
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBody);

            if ("Y".equalsIgnoreCase(isAnyAtchmnt)) {
                //2) create new MimeBodyPart object and set DataHandler object to this object


                for (String path : fileNameNPath) {
                    MimeBodyPart messageBodyPart2 = new MimeBodyPart();
                    System.out.println("Exact path--->" + path);
                    DataSource source = new FileDataSource(path);
                    messageBodyPart2.setDataHandler(new DataHandler(source));
                    // System.out.println("FileName is-"+path.substring(path.lastIndexOf("//")+1, path.length()));
                    messageBodyPart2.setFileName(path.substring(path.lastIndexOf("//") + 2, path.length()));
                    multipart.addBodyPart(messageBodyPart2);
                }

                //6) set the multiplart object to the message object
                message.setContent(multipart);
                message.saveChanges();
            }
            //If there is plain eMail- No Attachment
            else {
                message.setContent(msg, "text/html"); //for a html email
            }
        } catch (MessagingException e) {
        }

        Transport transport = null;


        try {
            transport = session.getTransport("smtp");
        } catch (NoSuchProviderException e) {
            System.out.println("No such Provider Exception");
        }

        try {
            transport.connect(hostName, FromUser, pwd);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();

            System.out.println("Email sent successfully.");
            return "Y";
        } catch (MessagingException e) {
            System.out.println("Messaging Exception" + e);
            return "N";
        }

    }


Call this method in your ADF Application to send simple mail or mail with attachment, this is just like plug n play , provide correct parameters and use

Thanks :) Happy Learning

Monday 22 December 2014

Uploading and showing image file from absolute server path -Orace ADF

This is another post about file handling in ADF. Previous post was about uploading and downloading any type of file from absolute server path
See-
Uploading and downloading files from absolute server path in Oracle ADF (12.1.3)

This post is specifically about handling image files, uploading an image file to server path and immediately show it on page using af:image component
So here i am using Jdev 12C (12.1.3) , see step by step implementation
  • Create a fusion web application and a page in viewController



  • Now drop af:inputFile (to browse and select file), af:image (to show uploaded image) and a button to upload file


  • Bind af:inputFile value to managed bean variable, this variable is further used to read or write or process  file



  •     //To Store Value of selected file
        private UploadedFile imageFile;
    
        public void setImageFile(UploadedFile imageFile) {
            this.imageFile = imageFile;
        }
    
        public UploadedFile getImageFile() {
            return imageFile;
        }
    


  • Now see Managed Bean method to upload image file to absolute server path
  • Bean Method to Upload File-


        //To Store path of uploaded Image file
        String imagePath = null;
    
        public void setImagePath(String imagePath) {
            this.imagePath = imagePath;
        }
    
        public String getImagePath() {
            return imagePath;
        }
    
        /**Method to upload image file to absolute server path*/
        private String uploadImage(UploadedFile file) {
    
            UploadedFile myfile = file;
    
            if (myfile == null) {
    
            } else {
                if (myfile.getContentType().equalsIgnoreCase("image/jpeg") ||
                    myfile.getContentType().equalsIgnoreCase("image/png") ||
                    myfile.getContentType().equalsIgnoreCase("image/bmp") ||
                    myfile.getContentType().equalsIgnoreCase("image/gif")) {
    
                    //Path of folder on drive
                    String path = "D://ADF//";
                    String type = "PNG";
                    String TypeVal = ".png";
                    if (myfile.getContentType().equalsIgnoreCase("image/jpeg")) {
                        type = "JPEG";
                        TypeVal = ".jpeg";
                    } else if (myfile.getContentType().equalsIgnoreCase("image/png")) {
                        type = "PNG";
                        TypeVal = ".png";
                    } else if (myfile.getContentType().equalsIgnoreCase("image/bmp")) {
                        type = "PNG";
                        TypeVal = ".png";
                    } else if (myfile.getContentType().equalsIgnoreCase("image/gif")) {
                        type = "GIF";
                        TypeVal = ".gif";
                    }
    
                    InputStream inputStream = null;
                    try {
                        //Generate a unique name for uploaded image with date time
                        DateFormat dateFormat = new SimpleDateFormat("yyMMdd_HHmmss");
                        Date date = new Date();
                        String dtTime = dateFormat.format(date);
                        dtTime = dtTime.replace(" ", "_");
    
                        String name = "IMG" + "_" + dtTime;
                        System.out.println("File name is-" + name);
                        inputStream = myfile.getInputStream();
                        BufferedImage input = ImageIO.read(inputStream);
    
                        //Writing file to path
                        File outputFile = new File(path + name + TypeVal);
                        ImageIO.write(input, type, outputFile);
                        imagePath = outputFile.getAbsolutePath();
    
    
                    } catch (Exception ex) {
                        // handle exception
                        ex.printStackTrace();
                    } finally {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                        }
                    }
                } else {
                    imagePath = "NO";
                }
            }
            setImageFile(null);
            return imagePath;
        }
    


    ActionListener of Upload Button-


        /**Action Listener to Upload image File
         * @param actionEvent
         */
        public void uploadImageFileAction(ActionEvent actionEvent) {
            File directory = new File("D://ADF//");
            //get all the files from a directory
            File[] fList = directory.listFiles();
            for (File file : fList) {
                //Delete all previously uploaded files
                if (!"NoImage.png".equalsIgnoreCase(file.getName())) {
                    file.delete();
                }
    
            }
            //Upload Currently Selected File
            String flag = uploadImage(imageFile);
    
            if ("NO".equalsIgnoreCase(flag)) {
                FacesMessage msg =
                    new FacesMessage("This is not an Image file, Please upload supported file type (.jpg,.png etc)");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
            }
        }
    

  • set usesUpload to true for af:form component on page to support file upload


  • Now upload part is complete , next is to show uploaded image on page. So to do this create a servlet (this will process image file into bytes and then show using af:image component)



  • See Servlet code and how it is mapped with af:image component

  • import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class ViewImageServlet extends HttpServlet {
        private static final String CONTENT_TYPE = "text/html; charset=UTF-8";
    
        public void init(ServletConfig config) throws ServletException {
            super.init(config);
        }
    
        /**
         * @param request
         * @param response
         * @throws ServletException
         * @throws IOException
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String path = (request.getParameter("path"));
    
    
            OutputStream os = response.getOutputStream();
            //If path is null or file is not an image
            if (path.equalsIgnoreCase("No")) {
                path = "D:\\ADF\\NoImage.png";
            }
            if (request.getParameter("path") == "") {
                path = "D:\\ADF\\NoImage.png";
            }
            InputStream inputStream = null;
    
            try {
                File outputFile = new File(path);
                inputStream = new FileInputStream(outputFile);
                BufferedInputStream in = new BufferedInputStream(inputStream);
                int b;
                byte[] buffer = new byte[10240];
                while ((b = in.read(buffer, 0, 10240)) != -1) {
                    os.write(buffer, 0, b);
                }
    
    
            } catch (Exception e) {
    
                System.out.println(e);
            } finally {
                if (os != null) {
                    os.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
    
            }
    
        }
    }
    


  • Now run this application and check this (All uploaded files will be stored in D://ADF path)
Select an image and click upload (Image is immediately reflected on page)


Check in D://ADF folder, image file is uploaded there with a new name


Again upload another image-


Check that previous file is deleted from folder and current one is there-


Happy Learning :)

Monday 24 November 2014

Populate af:table programmatically from managead bean using POJO

This post is about a common question
How can we populate an af:table programmatically ?

It means that data in af:table is not populated through model layer (Using ViewObject) using binding layer. lets say I have some values in our managed bean and have to show records in tabular format on page

So what we have to do -
  • First you should know the number and data type of columns in table, suppose i have to populate a table for person details (name, mobile number and salary). to get and set value of columns i have created a java bean class , it has 3 variable for 3 columns



  • // Java Class to set and get value for table column
    public class PersonBean {
    
        public PersonBean(String name, String moNo, Integer salary) {
            this.Name = name;
            this.mobNo = moNo;
            this.salary = salary;
        }
        private String Name;
        private String mobNo;
        private Integer salary;
    
        public void setName(String Name) {
            this.Name = Name;
        }
    
        public String getName() {
            return Name;
        }
    
        public void setMobNo(String mobNo) {
            this.mobNo = mobNo;
        }
    
        public String getMobNo() {
            return mobNo;
        }
    
        public void setSalary(Integer salary) {
            this.salary = salary;
        }
    
        public Integer getSalary() {
            return salary;
        }
    }
    

  • Next step is to create a managed bean for referencing af:table , this managed bean makes use of person java bean class to add data in same format for all table rows. A List data structure is used to pass all values in af:table. See code of managed bean 

  • //ArrayList to poplate data in af:table
        List<PersonBean> personList = new ArrayList();
    
        //To Populate default row in table (Code in Constructor)
    
        public ProgTableBean() {
            personList.add(new PersonBean("Ashish Awasthi", "xxxxxxxxxx", 50000));
        }
    
        public void setPersonList(List<PersonBean> personList) {
            this.personList = personList;
        }
    
        public List<PersonBean> getPersonList() {
            return personList;
        }
    

  • Now just drop an af:table on page and set it's properties like value, column header and text values in columns

  •  As i have to show only 3 columns so deleted extra ones

     Set properties -
     value- from where table collection is populated
     columns values- take the var reference of table and refer variable name in List (here 'row' is table var and second is variable name in person bean class)


     See the XML source of af:table-

    <af:table var="row" rowBandingInterval="1" id="t1" value="#{viewScope.ProgTableBean.personList}"
                              partialTriggers="::b1">
                        <af:column sortable="false" headerText="Name" id="c1" width="150">
                            <af:outputText value="#{row.name}" id="ot1"/>
                        </af:column>
                        <af:column sortable="false" headerText="Mobile Number" id="c2">
                            <af:outputText value="#{row.mobNo}" id="ot2"/>
                        </af:column>
                        <af:column sortable="false" headerText="Salary" id="c3" align="right">
                            <af:outputText value="#{row.salary}" id="ot3"/>
                        </af:column>
                    </af:table>
    

  • Now run this application and see there will be one row in table as code is added in constructor of managed to populate one row


  • I have added a form and button in page to add new records in table , see the form source code

  • <af:panelFormLayout id="pfl1">
                        <f:facet name="footer"/>
                        <af:inputText label="Name :" id="it1" binding="#{viewScope.ProgTableBean.nameBind}"/>
                        <af:inputText label="Mobile Number :" id="it2" binding="#{viewScope.ProgTableBean.mobNumBind}"/>
                        <af:inputText label="Salary :" id="it3" binding="#{viewScope.ProgTableBean.salaryBind}">
                            <af:convertNumber/>
                        </af:inputText>
                        <af:button text="Add Record" id="b1" actionListener="#{viewScope.ProgTableBean.addNewRcord}"/>
                    </af:panelFormLayout> 
     

    Code in managed bean for button action-

        /**Method to add new record in table
         * @param actionEvent
         */
        public void addNewRcord(ActionEvent actionEvent) {
            //Get all values using compoenet binding as mobNumBind
            if (mobNumBind.getValue() != null && nameBind.getValue() != null &&
                salaryBind.getValue() !=
                null) {
                // Add new Record in List
                personList.add(new PersonBean(nameBind.getValue().toString(), mobNumBind.getValue().toString(),
                                              Integer.parseInt(salaryBind.getValue().toString())));
            }
        }
    

  • now run and check application- 


 More posts on POJO Based table -

Get selected row (single/multiple) from POJO based table in ADF
Apply sorting to POJO based af:table programmatically , Using custom sort listener in ADF

Thanks , Happy Learning :)
Download-Sample ADF Application

Wednesday 19 November 2014

Populate Dynamic table and form using af:dynamicComponent and dynamic viewObject - Oracle ADF

This post is about a common development requirement- Can we increase or decrease number of fields , type of fields (columns in case of table), data in fields at run time?

Suppose i have to show data of Departments and Employees table on page using only one af:table component. It means columns should be generated dynamically at run time depending on any defined condition
So for this requirement i am using dynamic viewObject in model layer and af:dynamicComponent in view layer
See previous post about creating dynamic viewObject-
Creating Dynamic View Object at Runtime programmatically - Oracle ADF

See step by step implementation-
  • Create Fusion Web Application and follow the link posted above to create dynamic viewObject, in short create a viewObject using dual and a method in AMImpl to create dynamic viewObject from sql query


  •     /**Method to create viewObject using SQL query
         * @param query
    
    
    
    
    
    
    
         */
        public void createNewViewObject(String query) {
            ViewObject dynVo = this.getdynamic1();
            dynVo.remove();
            this.createViewObjectFromQueryStmt("dynamic1", query);
            this.getdynamic1().executeQuery();
        }
    

  • Created a page and added an inputText to enter SQL query and a button to process that query and create dynamic viewObject at run time


  • See Managed Bean code to process query, value of inputText is passed using component binding

  •     private RichInputText sqlQueryBind;
    
        public DynamicTableBean() {
        }
    
        /*****Generic Method to call operation binding**/
        public BindingContainer getBindingsCont() {
            return BindingContext.getCurrent().getCurrentBindingsEntry();
        }
    
        /**
         * Generic Method to execute operation Binding
         * */
        public OperationBinding executeOperation(String operation) {
            OperationBinding createParam = getBindingsCont().getOperationBinding(operation);
            return createParam;
    
        }
    
        /**Method to create viewObject
         * @param actionEvent
         */
        public void createViewObjectAction(ActionEvent actionEvent) {
            if (sqlQueryBind.getValue() != null) {
                OperationBinding ob = executeOperation("createNewViewObject");
                ob.getParamsMap().put("query", sqlQueryBind.getValue().toString());
                ob.execute();
            }
        }
    
        public void setSqlQueryBind(RichInputText sqlQueryBind) {
            this.sqlQueryBind = sqlQueryBind;
        }
    
        public RichInputText getSqlQueryBind() {
            return sqlQueryBind;
        }
    

  • Now dropped this dual viewObject on page as dynamic form and dynamic table from Data Control (this snap is about creating form)



  • Next is to change pageDef entry for this dynamic component , open pageDef and goto treeBinding. there is an entry for nodeDefinition, there will be separate treeBinding for form and table both (you should change both)

  •  <tree IterBinding="dynamic1Iterator" id="dynamic1">
                <nodeDefinition DefName="dynamictableapp.model.view.dynamicVO" Name="dynamic10"/>
            </tree>
    

    Change this entry like this-

     <tree IterBinding="dynamic1Iterator" id="dynamic1">
                <nodeDefinition Name="dynamic10"/>
            </tree>
    

  • Now run this application and enter SQL query in box and press process button


 Thanks, Happy Learning :)
Download -Sample ADF Application