Tuesday Feb 27, 2007

New Tree Tutorial

We have yet another new tutorial, this one titled Building a Tree From Database Data. This tutorial shows how to build a two-page application, the first page of which includes a Tree component. You populate the first-level nodes in the Tree with names from a database, and the second-level nodes with the trips for that person. The trip nodes are links to a second page, which displays the details for that trip.

Sunday Dec 17, 2006

Using the Object Array Data Provider

A forum poster recently asked for the following information:

I have a table with 5 columns, (week_no, objective, date1, date2 and add report). How do I get the date for date1( example, today's date)? How do I set the week number as auto increment by 1( example, row 1, the week_no is 1, row 2, the week_no is 2 and so on)? Lastly, how to I set the add report button to link to another JavaServer Pages file?

This scenario gives me an excellent opportunity to show how to use an Object Array Data Provider (OADP). I usually use the Object List Data Provider (OLDP), but OLDPs take a bit more work. (See the Using Hibernate tutorial for an OLDP example.) If you have a simple array of data, the OADP might be the better choice, as in this case. The following steps create a table similar to the one requested in the forum.

  1. Create a web application named ArrayTableExample.

    (If using the Visual Web Pack, be sure to create a Visual Web Application.)

  2. Create a JavaBeans object for the array. In this example, I chose to put the week number, start date, and end date in the bean. In the Projects window, right-click Source Packages > arraytableexample, choose New > Java Class, name the class WeekBean, and click Finish.
  3. Replace the class definition with the following code shown in bold.
    /\*
     \* WeekBean.java
     \*
     \*/
    
    package arraytableexample;
    
    public class WeekBean 
            extends Object implements Serializable {
        
        private int weekNumber;
        private Calendar startDate;
        private Calendar endDate;
        private int dayOfWeek; 
        
        public WeekBean(int weekNumber) {
            this.weekNumber = weekNumber;        
            Calendar workingDate = Calendar.getInstance();
            workingDate.set(java.util.Calendar.HOUR_OF_DAY, 0);
            int offset = weekNumber - 1; 
            workingDate.add(
                Calendar.DAY_OF_YEAR, 
                + (offset \* 7));
            dayOfWeek = workingDate.get(Calendar.DAY_OF_WEEK);
            startDate = (Calendar) workingDate.clone();   
            startDate.add(
            Calendar.DAY_OF_YEAR, - (dayOfWeek - Calendar.SUNDAY));
            endDate = (Calendar) workingDate.clone();
            endDate.add(
                Calendar.DAY_OF_YEAR,
                + (Calendar.SATURDAY - dayOfWeek));
        }
        
        public WeekBean() {
            this(1);
        }
            
        public int getWeekNumber() {
            return this.weekNumber;
        }
        
        public void setWeekNumber(int weekNumber) {
            this.weekNumber = weekNumber;
        }
        
        public Calendar getStartDate() {
            return this.startDate;
        }
        
        public void setStartDate(Calendar startDate) {
            this.startDate = startDate;
        }
        
        public Calendar getEndDate() {
            return endDate;
        }
        
        public void setEndDate(Calendar endDate) {
            this.endDate = endDate;
        }
    }
    
  4. Right-click in the code and choose Fix Imports. Make sure the Fully Qualified Name for Calendar is java.util.Calendar, and click OK.

  5. Close and save the file.

  6. In this example, we want the table to show the same data throughout the session, so put the array property in the session bean. In the Projects window, double-click the Session Bean node to open SessionBean1.java in the source editor.

  7. Add the following code to the bottom of the class defintion, just before the ending brace. This code also adds properties for passing the selected start and end dates to other pages.
    
        /\*\*
         \* Holds value of property weeks.
         \*/
            WeekBean[] weeks = {
                new WeekBean(1),
                new WeekBean(2),
                new WeekBean(3),
                new WeekBean(4)
            };
    
        /\*\*
         \* Getter for property weeks.
         \* @return Value of property weeks.
         \*/
        public WeekBean[] getWeeks() {
            return this.weeks;
        }
        
        /\*\*
         \* Holds value of property reportStartDate.
         \*/
        private Calendar reportStartDate;
    
        /\*\*
         \* Getter for property reportStartDate.
         \* @return Value of property reportStartDate.
         \*/
        public Calendar getReportStartDate() {
    
            return this.reportStartDate;
        }
    
        /\*\*
         \* Setter for property reportStartDate.
         \* @param reportStartDate New value of property reportStartDate.
         \*/
        public void setReportStartDate(Calendar reportStartDate) {
    
            this.reportStartDate = reportStartDate;
        }
    
        /\*\*
         \* Holds value of property reportEndDate.
         \*/
        private Calendar reportEndDate;
    
        /\*\*
         \* Getter for property reportEndDate.
         \* @return Value of property reportEndDate.
         \*/
        public Calendar getReportEndDate() {
    
            return this.reportEndDate;
        }
    
        /\*\*
         \* Setter for property reportEndDate.
         \* @param reportEndDate New value of property reportEndDate.
         \*/
        public void setReportEndDate(Calendar reportEndDate) {
    
            this.reportEndDate = reportEndDate;
        }
    
  8. Right-click in the code and choose Fix Imports. Make sure the Fully Qualified Name for Calendar is java.util.Calendar, and click OK.

  9. Close and save SessionBean1.java.

  10. View Page1 in the Visual Designer.

  11. In the Palette, expand the Data Providers section.

  12. Drag the Object Array Data Provider node and drop it on Page1.

  13. If the properties for the OADP do not appear in the Properties window, select Page1 > objectArrayDataProvider1 in the Outline window to make its properties appear.

  14. In the Properties window, change the id to weekDataProvider.

  15. Here is where it starts getting kludgy. You should be able to choose weeks from the array drop-down list, but it propably is not appearing at this point. If weeks is not in the drop-down list, choose Clean and Build Main Project from the main menu. After the build completes, close and reopen the project.

  16. In the Outline window, select Page1 > weekDataProvider.

  17. In the Properties window, select weeks (SessionBean1) from the array drop-down list.

  18. Drag a Table component from the Palette and drop it on Page1.

  19. Right-click the Table component and choose Table Layout.

  20. In the Table Layout dialog box, choose weekDataProvider from the Get Table From drop-down list.

  21. Use the Up and Down buttons to put the values in the Selected list in the following order:
    weekNumber
    startDate
    endDate
    
  22. (Optional) Set the Header Text values for the columns to Week, Start Date, and End Date.

  23. Click New to add another column.

  24. In the new column, set the Header Text to blank, select Button from the Component Type drop-down list, and set the Value Expression to Show Me.

  25. Click OK to dismiss the dialog box.

    Again, it gets kludgy. Only one row appears, which says "No items found", and there is no button. Don't worry, it will work out in the end.

  26. In the Outline window, expand table1 > tableRowGroup1 > tableColumn4, right-click button1, and choose Edit Action Event Handler.

    Page1.java opens in the source editor and scrolls to the newly added button1_action method.

  27. Add the code shown in bold to the method.
      public String button1_action() {
            getSessionBean1().setReportStartDate(
              (Calendar)getValue("#{currentRow.value['startDate']}"));
            getSessionBean1().setReportEndDate(
              (Calendar)getValue("#{currentRow.value['endDate']}"));        
            return null;
      }
    
  28. Right-click in the code and choose Fix Imports. Make sure the Fully Qualified Name for Calendar is java.util.Calendar, and click OK.

  29. Typically, you would set up page navigation to go to another page to display the report. For simplicity, click Design and drop a Static Text component on the page to display the selected start date.

  30. Right-click the Static Text component and choose Bind to Data.

  31. Click Bind to an Object, select SessionBean1 > reportStartDate, and click OK.

  32. Click Run Main Project. When the page appears, click the button in each row to verify that the action method returns the right value.

Winston has many blog entries about the dataprovider. A good place to start is his blog titled What is this Data Provider in Sun Java Studio Creator anyway?. Another good resource is Joel Brown's Weblog.

Wednesday Sep 06, 2006

Using the dojo ComboBox in a Java Studio Creator Project

Note: See Using jMaki 9.3 With the NetBeans Visual Web Pack or the Sun Java Studio Creator IDE for updated instructions on how to add jMaki to a project.

Jennifer Ball just published two new jMaki tutorials, which you can read about in her blog. One of the tutorials shows how to use jMaki in JavaServer Faces projects, and it completes the information that I needed to figure out how to integrate a jMaki widget in a page built using the Java Studio Creator IDE. In particular, how to bind to a bean property, how to save off the widget's values, and how to make managed bean methods available for the AJAX requests.

So, here is a mini-tutorial on how to use jMaki to add a dojo AJAX combo box to a JavaServer Faces web page.

  1. Download version 4 of the jMaki zip from https://ajax.dev.java.net/. There is a newer version, but it might have changes that would break this tutorial. I will update this post after I have done some testing.

  2. Unzip the zip file, then unjar the JAR file and copy the following files to your project. To unjar the JAR file, you can use the jar xvf jMaki.war command, or you can rename the file to have a .zip extension and unzip it.

    • jmaki/resources/jmaki.js to creator-project-dir/web/resources.
    • jmaki/resources/dojo/combobox to creator-project-dir/web/resources/dojo/combobox.
    • The contents of the /resources/libs/dojo directory (not the whole dojo directory) to creator-project-dir/web/resources/libs/dojo/version.3.1.
    • jmaki/WEB-INF/lib/ajax-wrapper-comp.jar to creator-project-dir/web/WEB-INF/lib.


    Note: You might want to add the ajax-wraper-comp.jar to the IDE's library manager. Then, you can easily add the jMaki library to a project by right-clicking the Libraries node in the Projects window and choosing Add Library.

  3. Create a project.

  4. Add a Group Panel component to the page and position the component where you want the combo box to be.

  5. In the editing area of the IDE, click JSP to view the JSP script.

  6. Add xmlns:a="http://java.sun.com/jmaki-jsf" to the top-level <div> tag.

  7. Inside the tag for the Group Panel component, add the jMaki ajax tag for the combo box . Wrap the a:ajax tag inside an f:verbatim tag, as shown below. Note that the service attribute is referring to ApplicationBean1. Later, you add the completeCountry() method to the application bean to return the list of choices.

    Notice: February 2007: jMaki is still evolving. I am working with the latest version from https://ajax.dev.java.net/jmaki-plugin.html. I am still experimenting, but I think instead of the service attribute you need something like value="#{ApplicationBean1.completeCountry}". Once I get it figured out, I will post a new entry.

     
    	
    <?xml version="1.0" encoding="UTF-8"?>
    <jsp:root version="1.2" xmlns:a="http://java.sun.com/jmaki-jsf" 
    xmlns:f="http://java.sun.com/jsf/core" 
    xmlns:h="http://java.sun.com/jsf/html" 
    xmlns:jsp="http://java.sun.com/JSP/Page" 
    xmlns:ui="http://www.sun.com/web/ui">
        <jsp:directive.page contentType="text/html;charset=UTF-8" 
             pageEncoding="UTF-8"/>
        <f:view>
            <ui:page binding="#{Page1.page1}" id="page1">
                <ui:html binding="#{Page1.html1}" id="html1">
                    <ui:head binding="#{Page1.head1}" id="head1">
                        <ui:link binding="#{Page1.link1}" id="link1" 
                            url="/resources/stylesheet.css"/>
                    </ui:head>
                    <ui:body binding="#{Page1.body1}" id="body1" 
                        style="-rave-layout: grid">
                        <ui:form binding="#{Page1.form1}" id="form1">
                            <ui:panelGroup binding="#{Page1.groupPanel1}" 
                                id="groupPanel1" 
                                style="position: absolute; left: 24px; top: 48px">
                            <f:verbatim>
                            <a:ajax id="cb1" name="dojo.combobox" 
                               service="ApplicationBean1-completeCountry.ajax" />
                            </f:verbatim>
                            </ui:panelGroup>
                        </ui:form>
                    </ui:body>
                </ui:html>
            </ui:page>
        </f:view>
    </jsp:root>
    
    
     


  8. In the Projects window, double-click the Application Bean node to open the code in the Source Editor.

    Note: In this mini-tutorial, you add the properties to ApplicationBean1, mostly to make the tutorial short. In your own applications, you might want to create a class that extends AbstractApplicationBean and use the Managed Beans node in the Projects window to make the class' properties available in application scope.

  9. Add the following code to the bottom of the class (I got this from Jennifer's tutorial):


     
        private String[] countries =new String[] {
            "Canada", "France", "Uganda", "Ukraine", "United States of America",
                    "United Kingdom", "Japan", "Korea", "Jamacia", "Thailand"
        };
        
        private String[] countryCodes =
                new String[] {"CA", "FR", "UG", "UR", "USA", "UK", "JP",
                        "KR", "JA", "TH"
        };
        
        public void completeCountry(FacesContext context,
                String[] args,AjaxResult result) {
            result.setResponseType(AjaxResult.JSON);
            result.append("[");
            for (int loop=0; loop < countries.length; loop++){
                result.append("[\\"" + countries[loop] + "\\",\\""
                        + countryCodes[loop] + "\\" ]");
                if (loop < countries.length -1) result.append(",");}
            result.append("]");
        }		
    		
     


  10. Right-click in the code and choose Fix Imports.

  11. Run and test the code. The countries should show up in the drop-down list and, if you type K, Korea should show up in the text box.

  12. In the Projects window, double-click the Session Bean node to open it in the Source Editor. You will now add a property for storing the combo box's selection.

  13. Add the following code to the bottom of the class:

     
        private String country = "";
        
        public String getCountry() {
            return country;
        }
        
        public void setCountry(String country){
            this.country = country;
        }
    		
     


  14. In the JSP for Page1, add the value="#{SessionBean1.country}" attribute to the ajax tag, as shown below.

                            <a:ajax id="cb1" name="dojo.combobox" 
                               service="ApplicationBean1-completeCountry.ajax" 
                               value="#{SessionBean1.country}"/>		
    		
     


  15. Click Design to switch to the Visual Designer.

  16. In the Outline window, select the form1 node.

  17. In the Properties window, set the value for the onSubmit property to jmaki.attributes.get('form1:cb1').saveState();.

  18. Drop a Button component on the page and set it's text to Go.

  19. Right-click in the page and choose Page Navigation.

  20. In the Page Navigation editor, right-click and choose New Page. Click OK to accept the name Page2.

  21. Click Page1.jsp to expand the icon, then drag from Button1 to Page2.jsp.

  22. Double-click Page2.jsp to open it in the Visual Designer.

  23. Drop a Static Text component on the page.

  24. Right-click the component and choose Bind to Data. Click the Bind to an Object tab and select SessionBean1 > country (if, by chance, the property does not appear on the list, close and reopen the project and try again).

  25. Add a Hyperlink component to the page and set its text to Back. Click the ... button for the component's url property, choose Page1, and click OK.

  26. Click OK.

  27. Run the application. Select a value and click Go. The selected value, which was saved to the session bean's country property, is displayed.

  28. Click Back. Because the widget's value attribute is bound to the session bean's country property, the previously selected value is displayed.

To understand how the jMaki tags work, I highly recommend that you read both of Jennifer's tutorials.

About

divas

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today