Please disable your adblock and script blockers to view this page

Search this blog

Showing posts with label showing. Show all posts
Showing posts with label showing. Show all posts

Monday 17 August 2015

Showing HashMap values in af:table using af:iterator

Previously i have posted about populating af:table programmatically using List Data Structure
Populate af:table programmatically from managead bean using POJO

This post covers same topic but this time requirement is different , we have a HashMap in managed bean and requirement is to show it's values on page in a table view
See Managed Bean code-


    //HashMap and it's accessors
    private HashMap<String, String> valMap = new HashMap<String, String>();

    public void setValMap(HashMap valMap) {
        this.valMap = valMap;
    }

    public HashMap getValMap() {
        return valMap;
    }
    // Object array to store key values of HashMap
    public Object[] getKeySet() {
        return getValMap().keySet().toArray();
    }


Added two inputText on page and a button to add new key and value to HashMap,




<af:panelFormLayout id="pfl1">
                    <af:inputText label="Key" id="it1" contentStyle="width:100px;"
                                  binding="#{viewScope.ShowHashMapAsTable.keyTextBind}"/>
                    <af:inputText label="Value" id="it2" contentStyle="width:100px;"
                                  binding="#{viewScope.ShowHashMapAsTable.valueTextBind}"/>
                    <af:button text="Add" id="b1" actionListener="#{viewScope.ShowHashMapAsTable.addValuesToMap}"/>
                </af:panelFormLayout>


Now code on button that get value of both inputText using component binding and add it to HashMap, at run time this form will be used to add new values to HashMap and table


    //Component Binding of inputText to get values
    private RichInputText keyTextBind;
    private RichInputText valueTextBind;

    public void setKeyTextBind(RichInputText keyTextBind) {
        this.keyTextBind = keyTextBind;
    }

    public RichInputText getKeyTextBind() {
        return keyTextBind;
    }

    public void setValueTextBind(RichInputText valueTextBind) {
        this.valueTextBind = valueTextBind;
    }

    public RichInputText getValueTextBind() {
        return valueTextBind;
    }

    /**Add new value to HashMap
     * @param actionEvent
     */
    public void addValuesToMap(ActionEvent actionEvent) {
        if (keyTextBind.getValue() != null && valueTextBind.getValue() != null) {
            valMap.put(keyTextBind.getValue().toString(), valueTextBind.getValue().toString());

        }
    }


Now Bean Part is done , see how to configure af:table to show HashMap values, table is mapped to array of keySet and an iterator is used inside table that derives value using key attribute -
#{cVal[row]}


<af:table var="row" rowBandingInterval="0" id="t1" value="#{viewScope.ShowHashMapAsTable.keySet}"
                              partialTriggers="::b1">
                        <af:iterator id="i1" value="#{viewScope.ShowHashMapAsTable.valMap}" var="cVal">
                            <af:column sortable="false" headerText="Key" id="c2">
                                <af:outputText value="#{row}" id="ot4" inlineStyle="font-weight:bold;color:darkblue;"/>
                            </af:column>
                            <af:column sortable="false" headerText="Value" id="c1">
                                <af:outputText value="#{cVal[row]}" id="ot3"/>
                            </af:column>
                        </af:iterator>
                    </af:table>


Now all done , run and check the application
 Add New Value (1)
  Add New Value (2)

Sample Application- Download (Jdev 12.1.3)
Cheers :) 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 15 September 2014

Showing all values instead of 'All' text in selectManyChoice using JavaScript -Oracle ADF

Happy Engineer's Day :)
This post is about overriding default text for select all feature in af:selectManyChoice
af:selectManyChoice supports multiple selection in ADF Faces and framework provides a default feature to select all values of list but after selecting all value it doesn't show values ,only show a String 'All'.
Like this-
but sometimes it is not clear that what are the values by just seeing this 'All' text or it is a requirement to show all values (if there is not much data) instead of this default text



So in this post i am going to override this default text using JavaScript and this is a quick overview that how we can play with JavaScript and try it in ADF Faces
see previous posts on JavaScript in Oracle ADF-

Show message (Invoke FacesMessage) using JavaScript in ADF Faces
Launching browser print dialog using simple javascript function in ADF
Using JQuery in Oracle ADF

So in this implementation i am using Departments table (HR Schema -Oracle) and Jdeveloper 12C (12.1.3)
  • Prepare model using Departments table and drop viewObject on page as af:selectManyChoice


  • Now  see when we select one -two values , it appears on component but in case of all only that 'All' string appears


  • Here i am changing this text on valueChange event of selectManyChoice , so created a valueChangeListener in managed bean. 

  • See what i am going to do in this listener is -
    1. Get all selected values means DepartmentId
    2. Next is to get corresponding DepartmentName for DepartmentId 
    3. Add all DepartmentName into an String
    4. Call JavaScript method to set this String as value of selectManyChoice instead of 'All'

  • See code written in valueChangeListener , i have used enough comments to understand each line

  •     /**ValueChangeListener for SelectManyChoice (Executes Javascript to replace 'All' text)
         * @param vce
         */
        public void selectManyVCE(ValueChangeEvent vce) {
            //String to store all selected Departments Name
            String displayVal = "";
            //Get BindingContainer of current page
            BindingContext bctx = BindingContext.getCurrent();
            BindingContainer bindings = bctx.getCurrentBindingsEntry();
            //Get Iterator of SelectManyChoice
            DCIteratorBinding iter = (DCIteratorBinding) bindings.get("Departments1Iterator");
    
            if (vce.getNewValue() != null) {
                //Get all selected values in an Object array
                Object[] selectedVals = (Object[]) vce.getNewValue();
                //Iterate over array to get all selected DepartmentId
                for (int i = 0; i < selectedVals.length; i++) {
                    Integer val = (Integer) selectedVals[i];
                    //Create Key using DepartmentId to use furhter
                    Key key = new Key(new Object[] { val });
                    //Get ViewObject row using Key vlaue
                    Row row = iter.getViewObject().getRow(key);
                    // Get DepartmentName from row and add it to String
                    if (displayVal != "") {
                        displayVal = displayVal.concat(", ").concat(row.getAttribute("DepartmentName").toString());
                    } else {
                        displayVal = displayVal.concat(row.getAttribute("DepartmentName").toString());
                    }
                }
                //Write JavaScript code to change text of selectManyChoice as a StingBuilder Object
                StringBuilder jsString = new StringBuilder();
                //First Step-get clientID of component
                jsString.append("var elementId = '" + vce.getComponent().getClientId());
                //Second- add ::content to access it's value
                jsString.append("::content';");
                //Third- Check that current value is 'All' or not
                jsString.append("\n if (document.getElementById(elementId).value == 'All') {");
                //Forth- if yes then assign Department Name's string as value of selectManyChoice
                jsString.append("\n document.getElementById(elementId).value ='" + displayVal + "' \n};");
                System.out.println("JS File-" + jsString);
                //Call this JavaScript code using this Helper method
                writeJavaScriptToClient(jsString.toString());
    
            }
        }
    

    Method to call JavaScript from managed bean-

        /**Helper Method to call Javascript
         * @param javascriptCode
         */
        public static void writeJavaScriptToClient(String javascriptCode) {
            FacesContext facesCtx = FacesContext.getCurrentInstance();
            ExtendedRenderKitService service = Service.getRenderKitService(facesCtx, ExtendedRenderKitService.class);
            service.addScript(facesCtx, javascriptCode);
        }
    

    Import packages-

    import javax.faces.context.FacesContext;
    import javax.faces.event.ValueChangeEvent;
    
    import oracle.adf.model.BindingContext;
    import oracle.adf.model.binding.DCIteratorBinding;
    
    import oracle.binding.BindingContainer;
    
    import oracle.jbo.Key;
    import oracle.jbo.Row;
    
    import org.apache.myfaces.trinidad.render.ExtendedRenderKitService;
    import org.apache.myfaces.trinidad.util.Service;
    

  • Run application and check, on selecting all values it shows -


  • but this will happen only on value change event of selectManyChoice , you can call this JavaScript any time as per your requirement like on page load
Thanks , Happy Learning :-)

Tuesday 29 July 2014

Showing highlighted holiday calendar in af:inputDate date picker (ADF 12.1.3)

Hello All
This post is about showing highlighted days for holidays in af:inputDate and user must not be able to select these dates
here i am using Jdeveloper 12.1.3
you can do this using af:calendar
https://blogs.oracle.com/adf/entry/display_holiday_name_in_af
but i have a requirement to show holidays while user selects date using af:inputDate

so for this requirement first step is easy to do and there is lots of post about disabling specific days in calendar of af:inputDate

Step 1. Disable specific days -
  • you can see there is property in af:inputDate for setting disabled days, this filed takes a value of type List supported by DateListProvider interface




  • for this purpose i have created a bean that implements methods of DateListProvider , in Overridden method i have defined a list that contains dates of holidays that i want to disable in af:inputDate

  • package holiday.view.bean;
    
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.List;
    
    import javax.faces.context.FacesContext;
    
    import org.apache.myfaces.trinidad.model.DateListProvider;
    
    public class HolidayBean implements DateListProvider {
        public HolidayBean() {
        }
    
        @Override
        public List<Date> getDateList(FacesContext facesContext, Calendar calendar, Date date, Date date2) {
            List<java.util.Date> holiDay = new ArrayList();
            holiDay.add(new Date("27-July-2014"));
            holiDay.add(new Date("29-July-2014"));
            holiDay.add(new Date("10-Aug-2014"));
            holiDay.add(new Date("25-Dec-2014"));
            holiDay.add(new Date("01-Jan-2015"));
            holiDay.add(new Date("22-Oct-2014"));
            holiDay.add(new Date("23-Oct-2014"));
            holiDay.add(new Date("24-Oct-2014"));
    
            return holiDay;
            //return Collections.emptyList();
        }
    }
    

  • attached this bean to disabledDays property of af:inputDate


  • now first part is done we can see all holidays as disabled in calendar of af:inputDate

Step 2. Highlight disabled holidays -
  • but it is not easy to find holidays as all are in grey, so i have to highlight all disabled days , so for this requirement , create a skin in viewController project and write this

  • af|chooseDate::regular-day:disabled{
        background-color: red;
        color: ButtonFace;
    }
    

  • af:chooseDate is used because internally af:inputDate opens af:chooseDate as date picker so i have to change property of af:chooseDate, now run your application

Happy Learning :)

Tuesday 6 May 2014

ADF Basics : Selecting and showing time-stamp in ADF Faces using af:inputDate & af:convertDateTime

Hello All
This post is about a very common & basic requirement of developers ,
how to show & select time with date in ADF Faces ?
We use af:inputDate to show and select Date & Timestamp type of attributes, by default it looks like this



ADF provides a default converter (af:convertDateTime) to format date & timestamp field, we can define a pattern to change it's format & to show time selector in calendar box



Suppose pattern is- dd-MMM-yyy HH:mm:ss , now see there is a hour/minute/second selector appears in calendar box



you can change this pattern as per your format , suppose you want to show AM or PM after time just use dd-MMM-yyy HH:mm:ss a



see xml source of af:inputDate-


<af:inputDate label="Label 1" id="id1" contentStyle="width:250px;padding:5px;">
                        <af:convertDateTime pattern="dd-MMM-yyy HH:mm:ss a"/>
                    </af:inputDate>

this is how we can change format of Date & Timestamp - Cheers :-)

Tuesday 4 March 2014

Showing white-spaces properly in ADF table column- 11g & 12c

Hello All,
This posts talks about a requirement of showing white-spaces before any text/number in an af:table
Suppose i have , form and table of a ViewObject on page

Case 1- both table and form are editable , in this case you can see that white spaces are properly visible in both form and table

but normally in applications we have a read-only table and editable form so in this case you can see that white-spaces are not visible in table

But sometimes we need to show spaces in table same as in form so to do this select that field and go to property inspector and select component




Now set it's contentStyle (for input component as- af:inputText) or inlineStyle (for display component as- af:outputText)- white-space:pre;




now run your page and see-

 Cheers :-)