Please disable your adblock and script blockers to view this page

Search this blog

Showing posts with label af:image. Show all posts
Showing posts with label af:image. Show all posts

Friday 2 January 2015

Using captcha with ADF Faces (Integrate Kaptcha project with Oracle ADF)



First of all wishing a very Happy New Year to all of you, learn more n more ADF this year :)


This post is about using captcha challenge in ADF Faces, captcha is used to determine whether user is a human or not
CAPTCHA stands for-Completely Automated Public Turing test to tell Computers and Humans Apart
Frank Nimphius posted about 'captcha with ADF Faces' using "Simple Captcha" project.
You can read complete article- http://www.oracle.com/technetwork/developer-tools/jdev/captcha-099103.html



For this post I am using modern version of simplecaptcha project called Kaptcha, project provides a servlet that is responsible for generating captcha image and there are various configuration parameters to change look n feel of captcha image
See project documentation - https://code.google.com/p/kaptcha/
Download jar file- https://code.google.com/p/kaptcha/downloads/list

Now see the steps to integrate Kaptcha project with Oracle ADF
  • Create a FusionWeb Application, attach kaptcha-2.3.2 jar to viewController project, also see How to use "Kaptcha"-https://code.google.com/p/kaptcha/wiki/HowToUse


  • Next step is to add kaptcha servlet reference in web.xml file

  •  <servlet>
            <servlet-name>Kaptcha</servlet-name>
            <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>Kaptcha</servlet-name>
            <url-pattern>/kaptchaimage</url-pattern>
        </servlet-mapping>
    

  • Add an af:image on page to show captcha, image source is referenced from servlet mapping

  • <af:image id="i1" partialtriggers="l1" shortdesc="Captcha" source="/kaptchaimage">
    

  • Default configuration for captcha image is completed , I have added an af:inputText and button on page to enter captcha result .

  • <af:panelBox text="Captcha Demo- www.awasthiashish.com" id="pb1" showDisclosure="false"
                                     inlineStyle="width:350px;">
                            <f:facet name="toolbar"/>
                            <af:spacer width="0" height="10" id="s3"/>
                            <af:panelFormLayout id="pfl1">
                                <af:panelGroupLayout id="pgl1" layout="horizontal">
                                    <af:image source="/kaptchaimage" id="i1" partialTriggers="l1" shortDesc="Captcha"/>
                                    <af:spacer width="10" height="0" id="s4"/>
                                    <af:link id="l1" icon="#{resource['images:reload.png']}" shortDesc="Refresh Captcha"/>
                                </af:panelGroupLayout>
                                <af:inputText label="Enter text" id="it1" binding="#{ReadCaptchaBean.entrdCaptchaBind}"
                                              contentStyle="font-weight:bold;"/>
                                <af:button text="Submit" id="b1" actionListener="#{ReadCaptchaBean.readCaptchAction}"/>
                            </af:panelFormLayout>
                        </af:panelBox>
    

  • Run application and see how captcha image is appearing on page


  • It looks good :-), now see the managed bean code written in submit button's action. This code checks actual captcha value with entered value

  •     //Binding of inputText to get entered value
        private RichInputText entrdCaptchaBind;
    
        public void setEntrdCaptchaBind(RichInputText entrdCaptchaBind) {
            this.entrdCaptchaBind = entrdCaptchaBind;
        }
    
        public RichInputText getEntrdCaptchaBind() {
            return entrdCaptchaBind;
        }
        
        /**Method to check whether entered value is correct or not
         * @param actionEvent
         */
        public void readCaptchaAction(ActionEvent actionEvent) {
            FacesContext fctx = FacesContext.getCurrentInstance();
            ExternalContext ectx = fctx.getExternalContext();
            HttpServletRequest request = (HttpServletRequest) ectx.getRequest();
            //KAPTCHA_SESSION_KEY- The value for the kaptcha is generated and is put into the HttpSession. This is the key value for that item in the session.
            String kaptchaExpected =
                (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
            //Get entered value of captcha using inputText binding
            String kaptchaReceived = entrdCaptchaBind.getValue().toString();
            System.out.println("Entered Value-" + kaptchaReceived + " Expected Value-" + kaptchaExpected);
            if (kaptchaReceived == null || !kaptchaReceived.equalsIgnoreCase(kaptchaExpected)) {
                FacesMessage errMsg = new FacesMessage("Invalid Value");
                errMsg.setDetail("Incorrect captcha value- Not Human");
                errMsg.setSeverity(FacesMessage.SEVERITY_ERROR);
                fctx.addMessage(entrdCaptchaBind.getClientId(), errMsg);
            } else {
                FacesMessage errMsg = new FacesMessage("Correct Value");
                errMsg.setDetail("Hello this is the right guess");
                errMsg.setSeverity(FacesMessage.SEVERITY_INFO);
                fctx.addMessage(entrdCaptchaBind.getClientId(), errMsg);
            }
        }
    

  • Again run this application and enter value for captcha



  • So it is working , now to change captcha image added a link with partialSubmit=false and set partial trigger property on af:image.


  • Kaptcha integration with Oracle ADF is complete and it is working properly  now if you want to modify captcha look n feel then add some init-param (configuration parameter) in web.xml file.
    See complete list of configuration parameters- https://code.google.com/p/kaptcha/wiki/ConfigParameters
    I have changed some parameters value in web.xml , see changed source of web.xml and captcha output

  • <servlet>
            <servlet-name>Kaptcha</servlet-name>
            <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
            <init-param>
                <param-name>kaptcha.border</param-name>
                <param-value>yes</param-value>
            </init-param>
            <init-param>
                <param-name>kaptcha.border.color</param-name>
                <param-value>red</param-value>
            </init-param>
            <init-param>
                <param-name>kaptcha.border.thickness</param-name>
                <param-value>1</param-value>
            </init-param>
            <init-param>
                <param-name>kaptcha.image.width</param-name>
                <param-value>250</param-value>
            </init-param>
            <init-param>
                <param-name>kaptcha.image.height</param-name>
                <param-value>60</param-value>
            </init-param>
            <init-param>
                <param-name>kaptcha.textproducer.font.size</param-name>
                <param-value>35</param-value>
            </init-param>
            <init-param>
                <param-name>kaptcha.textproducer.font.color</param-name>
                <param-value>red</param-value>
            </init-param>
            <init-param>
                <param-name>kaptcha.background.clear.from</param-name>
                <param-value>orange</param-value>
            </init-param>
            <init-param>
                <param-name>kaptcha.textproducer.char.length</param-name>
                <param-value>7</param-value>
            </init-param>
        </servlet>
        <servlet-mapping>
            <servlet-name>Kaptcha</servlet-name>
            <url-pattern>/kaptchaimage</url-pattern>
        </servlet-mapping>
    

    again run this application and check output

    Thanks, Happy Learning :)
    Download-Sample ADF Application

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 8 December 2014

Show animated Image Caption using jQuery in ADF Faces

This is another post about using jQuery in ADF Faces, see previous posts on jQuery

Using JQuery in Oracle ADF 
Image zoom (power zoomer) effect using Jquery in ADF Faces

This post talks about - how to add mouse hover caption to images? Caption means a brief explanation of picture/image. Normally 'alt' attribute of HTML page is used as Image Caption
But in ADF Faces af:image doesn't has 'alt' property , there is a property called 'shortdesc' and this property is used as 'alt' attribute for image when jsf page is loaded at client browser
you can check this in html source of your page in browser (inspect element)




<af:image shortDesc="Black Horse running or flying" id="FirstImage"
                                  inlineStyle="height:300px;width:500px;"
                                  source="#{resource['images:Best-Wild-Animal-Photos-of-2012-307-black-horse-running.jpg']}"/>


JSF page is converted to html for client side presentation, see in HTML source 'shortdesc' is used as 'alt' property


jQuery is used for client side scripting of HTML so jQuery script makes use of this 'alt' attribute to show animated caption for image
There are lots of jQuery and JavaScript available for showing different types of captions , here i am using jQuery Capty - A Caption Plugin (Download jQuery script and respective css file from link)

Now follow steps to use this jQuery plugin with ADF Faces
  • Create Fusion Web Application and a page in viewController, added jQuery script and css in viewController project (Jdev 12.1.3)


  • Add jQuery library and script file reference to page, also add css file reference to page

  •  //jQuery library reference
                <af:resource type="javascript" source="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></af:resource>
                //jQuery file reference that will be used to show caption
                <af:resource type="javascript" source="js/jquery.capty.js"/>
                <af:resource type="javascript" source="js/jquery.capty.min.js"/>
                //CSS file to style Caption
                <af:resource type="css" source="css/jquery.capty.css"/>
    

  • Next step is to execute jQuery function on pageload to show caption

  • //Function to show default sliding caption
    
    $('#ImageId').capty();
    
    //Change default fucntion to change animation type , speed and height of caption
    
    $('#ImageId').capty({
    animation: 'fade',
    speed:     1000
    }) 
    

  • So here i am using both function for two different images (for first image animation type is slide (default) and for second it is fade), add clientListener to document tag and set it's type to 'load' (to execute jQuery function on pageload)

  •  <af:clientListener method="jQuery(document).ready(function($){ $('#FirstImage').capty(); $('#SecondImage').capty({animation: 'fade',   speed:     1000}) })" type="load"/>
    

  • Run application and see magic of jQuery

  • Image Caption (animation:slide)-

    Image Caption (animation:fade)-

  • you can change style (color,font etc) of caption box by modifying css sheet and size can be increased or decreased from jQuery function. for example i have changed color, font and size of caption box. see this

  • @CHARSET "UTF-8";
    
    div.capty-caption {
     background-color: red;
     color: #FFF;
     font: bold 11px cursive;
     padding-left: 10px;
     padding-top: 7px;
     text-shadow: 1px 1px 0 #222;
    }
    
    div.capty-caption a {
     color: #318DAD;
     font: bold 11px verdana;
     text-decoration: none;
     text-shadow: none;
    }
    

    jQuery function to increase size-

    jQuery(document).ready(function($){ $('#FirstImage').capty(); $('#SecondImage').capty({animation: 'fade',   speed:1000,height:50}) })
    

    See output-
Thanks, Happy Learning :)
Download Sample ADF Application

Tuesday 2 December 2014

Image zoom (power zoomer) effect using Jquery in ADF Faces

Jquery is most popular javascript library ,it is used to provide better ui design, animations and client side events
This is another post about using jquery in ADF Faces, see previous post
Using JQuery in Oracle ADF

In this post i am using a jquery script to zoom (enlarge) image on hover , you have seen this in many e-commerce websites as they provide power zoom feature to enlarge product image for better customer experience



I have taken this jquery script from Dynamic Drive, see the documentation
To implement this in ADF Application follow these steps
  • Create a Fusion Web Application and a page in viewController project (Jdev 12.1.3)


  • Downloaded jquery script file from above link -ddpowerzoomer.js, add this jquery file to viewController project


  • Now add jquery library reference in page in order to use jquery functions

  • <af:resource type="javascript" source="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></af:resource>
                <af:resource type="javascript" source="js/ddpowerzoomer.js"/>
    

  • Next step is to add an image to page , so added an af:image to page and set path of image to display


  • Now i have to execute jquery function that will add power zoom feature to this image (See jquery code that will be executed on pageload)

  • jQuery(document).ready(function($){
     $('#i1').addpowerzoom({
      defaultpower: 2,  powerrange: [2,5],  largeimage: null,  magnifiersize: [75,75]  }) 
    })
    

    here i1 is the id of image, default zoom power and magnifier size is configured here
  • So to execute this jquery function on pageload , added a clientListenr to pagelike this

  • <af:clientListener type="load"
                                   method="jQuery(document).ready(function($){   $('#i1').addpowerzoom({  defaultpower: 2,  powerrange: [2,5],  largeimage: null,  magnifiersize: [75,75]  }) })"/>
    

  • Now run this application and check it, magnifier is on deer :)


  • Now i am increasing size and power of magnifier - Power is 3 and size is 200x200
Thanks, Happy Learning :)
Download 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