Showing posts with label woodstock. Show all posts
Showing posts with label woodstock. Show all posts

Saturday, July 26, 2014

JSF 1.2: Project Woodstock Application using JPA

Woodstock Dataprovider Entity Example
Here is another example of using Project Woodstock along with JPA in an Enterprise Application. The project requires the sample database included in NetBeans.

The project was updated using NetBeans 6.5.1.


The code for the project can be found on Bitbucket here: WoodstockJPAApplication

Friday, July 25, 2014

JSF 1.2: Project Woodstock Multiple Selection Table Example

Multiple Selection Table

This is another example of a Project Woodstock project that was converted from Project Rave and Sun Studio Creator 2. This example details a multiple selection table, and was originally created by Winston Prakash.

I have updated the project using NetBeans 6.5.1 and tested on GlassFish 2.1.1.

The updated project can be found on BitBucket here: MultipleSelectionTable

Thursday, July 24, 2014

JSF 1.2: Project Rave Single Selection Table

Single Selection Table
Here is another example Project Rave/Woodstock project originally written by Winston Prakash for Sun Studio Creator 2. It has been updated using NetBeans 6.5.1 and tested on Glassfish 2.1.1.

The project can be found on BitBucket here: SingleSelectionTable

JSF 1.2: Woodstock Collapsible Group Table Example

Collapsible Group Table Example
Here is another example of a Project Rave data table converted to Project Woodstock. Project Woodstock was a great idea and the implementation with Visual JSF was the right path to go with JSF development. It is a shame that the project was canceled by Sun. I met a lot of great people who worked on the projects, and are still friends today. The code for this project was originally developed by Winston Prakash at Sun.

The code was developed using NetBeans 6.5.1 and can be downloaded from BitBucket here: CollapsibleGroupTable


Monday, July 14, 2014

JSF 1.2: Project Woodstock Button Facet Table

I was going through some old code examples. I found one created with Sun Studio Creator. Yes, it was very old.

The original example was developed by Winston Prakash.

I did some updates to Project Woodstock from the original Project Rave, and came up with a pretty new example page.

The project can be downloaded here: ButtonHeaderTable

Note: You will need to use NetBeans 6.5.1, or 6.7.1 to run it.

Sunday, July 13, 2014

JSF 1.2: Visual Web Pack (Project Woodstock) Java Persistence API Example

Master-Detail Example
This is some example code that I have for a Visual Web Pack (VWP) project that demonstrates some complex data table examples.

I often fantasize about being able to get the band back together and make Woodstock 2.0. Here is an example of why. This was complex for JSF 1.2.

The code can be downloaded from: vwpjpaexamples

I would strongly recommend using NetBeans 6.5.1 to build and run the example project.

Monday, September 09, 2013

Woodstock File Upload Example


Here is another example from my code proof of concept archives.

As many of you may know, I was a big proponent of using Project Woodstock (Visual JSF). I still believe that Visual JSF and NetBeans were a great combination. In this project, you will see a couple of example applications for doing file uploads. The project was built using NetBeans 6.7.1 with the Visual JSF libraries and runtime installed.

Using the older NetBeans IDE will allow you to see Visual JSF and why it was cool in addition to getting the correct libraries installed.
Visual JSF was the "killer" framework that got me interested in JSF. It is a JSF 1.2 based framework. If you have need for nice looking components and a really easy framework + IDE combination, it is a good choice.

The code for the project can be found here: WoodstockFileUploadExample

Here is the download page visually in the IDE.


Page1.jsp


Page2.jsp

The code is really simple to create and use via NetBeans enjoy. This code will work on Java EE5, EE6, and EE7.

Saturday, May 28, 2011

Woodstock (Visual JSF) Calendar Binding Example

There was a post on the nbj2ee forum about binding a Woodstock Calendar to a backing bean. This is a simple example which demonstrates how to do it. The project was done in NetBean 6.7.1 and should work on NetBeans 6.5, 6.7, and 6.8 with the Visual JSF plugins installed.

WoodstockCalendarBindingExample







Enhanced by Zemanta

Saturday, January 01, 2011

JSF 2.x Component prerender() (PreRenderComponentEvent)

In Project Woodstock (Visual JSF), the page bean had a number of methods which could be overridden to provide additional functionality by adding convenient interception points in the JSF life cycle. This additional functionality was one of the selling points of Woodstock (Project Rave). If you are using JSF 1.2, it is still compelling.

One method which was very important was the prerender() method. This method was invoked prior to the page being rendered on the client. The com.sun.rave.web.ui.appbase.AbstractPageBean has a very complete explanation:



/**
* Callback method that is called just before rendering takes place.
* This method will only be called for the page that
* will actually be rendered (and not, for example, on a page that
* handled a postback and then navigated to a different page). Customize
* this method to allocate resources that will be required for rendering
* this page.
*/

This allowed for late binding of the component. This functionality has been added to JSF 2.0 in the SystemEvent facility. It is captured in two interfaces: PreRenderComponentEvent and PreRenderViewEvent. I will focus on the first interface, and provide an example for you.

This functionality is accomplished using the <f:event/> tag.  In this series of examples we have an <h:outputText/> which has its value injected displaying the event which was called, and a second more useful example which pre-populates <f:selectItems/> for use in an <h:selectOneListbox/> which also includes <f:ajax/> to display the selected value.


event.xhtml



<?xml version="1.0" encoding="UTF-8"?>
<!--
 Copyright 2010 Blue Lotus Software, LLC.
 Copyright 2010 John Yeary <jyeary@bluelotussoftware.com>.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 under the License.
-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
    <h:head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>&lt;f;event/&gt;</title>
    </h:head>
    <h:body>
        <h:form id="form1">
            <h:panelGrid id="panelGrid1" columns="1">
                <h:outputText id="outputText1">
                    <f:event id="event1" type="javax.faces.event.PreRenderComponentEvent" listener="#{eventBean.preRenderComponent}"/>
                </h:outputText>
                <h:selectOneListbox id="selectOneListbox" value="#{eventBean.selectedItem}">
                    <f:event id="event2" type="javax.faces.event.PreRenderComponentEvent" listener="#{eventBean.updateSelectItems}"/>
                    <f:ajax id="ajax1" render="outputText2"/>
                </h:selectOneListbox>
                <h:outputText id="outputText2" value="#{eventBean.selection}"/>
            </h:panelGrid>
        </h:form>
    </h:body>
</html>


EventBean.java



/*
 *  Copyright 2010 Blue Lotus Software, LLC.
 *  Copyright 2010 John Yeary <jyeary@bluelotussoftware.com>.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
/*
 * $Id:$
 */
package com.bluelotussoftware.example.jsf;

import java.util.ArrayList;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIOutput;
import javax.faces.component.UISelectItems;
import javax.faces.component.UISelectOne;
import javax.faces.event.ComponentSystemEvent;
import javax.faces.model.SelectItem;

/**
 * This is the {@link javax.faces.bean.ManagedBean} for the {@literal event.xhtml}
 * page. It is provided to demonstrate the {@literal <f:event/>} tag and its usage
 * in handling {@link javax.faces.event.PreRenderComponentEvent} events to populate
 * the representative components with values.
 * 
 * @author John Yeary <jyeary@bluelotussoftware.com>
 * @version 1.0
 */
@ManagedBean
@RequestScoped
public class EventBean {

    /**
     * value holder for the selected {@link javax.faces.component.html.HtmlSelectOneListbox}.
     */
    private String selectedItem;

    /**
     * Default constructor.
     */
    public EventBean() {
    }

    /**
     * Getter for the selected {@link javax.faces.component.html.HtmlSelectOneListbox}.
     * @return selected value.
     */
    public String getSelectedItem() {
        return selectedItem;
    }

    /**
     * Setter for the selected {@link javax.faces.component.html.HtmlSelectOneListbox}.
     * @param selectedItem set the component value.
     */
    public void setSelectedItem(String selectedItem) {
        this.selectedItem = selectedItem;
    }

    /**
     * Event Handler for {@link javax.faces.event.ComponentSystemEvent}. The usage here captures
     * the higher level event, but we are using it to capture {@link javax.faces.event.PreRenderComponentEvent}
     * and set the appropriate values.
     * @param event triggering component event to handle.
     */
    public void preRenderComponent(ComponentSystemEvent event) {
        UIOutput output = (UIOutput) event.getComponent();
        output.setValue(event.getClass().getName() + " fired.");
    }

    /**
     * Event Handler for {@link javax.faces.event.ComponentSystemEvent}. This method
     * sets the {@link javax.faces.component.UISelectItems} prior to the component being
     * rendered.
     * @param event triggering component event to handle.
     */
    public void updateSelectItems(ComponentSystemEvent event) {
        ArrayList<SelectItem> items = new ArrayList<SelectItem>();
        items.add(new SelectItem("Tuna", "Tuna"));
        items.add(new SelectItem("Salmon", "Salmon"));
        items.add(new SelectItem("Mojarra", "Mojarra", "A delicious fish, and UI framework."));
        items.add(new SelectItem("Tilapia", "Tilapia", null, true));
        UISelectItems selectItems = new UISelectItems();
        selectItems.setId("selectItems1");
        selectItems.setValue(items);

        UISelectOne uISelectOne = (UISelectOne) event.getComponent();
        uISelectOne.getChildren().add(selectItems);
    }

    /**
     * Returns the selected value.
     * @return selected value.
     */
    public String getSelection() {
        if (selectedItem != null) {
            return selectedItem;
        }
        return "Nothing Selected";
    }
}
}

Here is the result:


Monday, November 02, 2009

JSF 1.2: Woodstock and Facelets

I have been asked if there is an example of how to use facelets. In this example application, I have changed the default namespace in my NetBeans project to w from webuijsf to make it simpler to see. In this example I display the customers from the sample database which is part of the default installation of NetBeans.

Here is what it looks like displayed:


Here is the facelets view:

The source code can be found on BitBucket here:WoodstockFaceletsExample

Saturday, July 04, 2009

Woodstock Dropdown List Binding Examples

I am spending the morning answering a number of questions posted to the nbj2ee list. One of the questions was how to add separators to to drop down lists. I decided to write a little code example to show how this is done.

The idea is to retrieve the data values from a database. In this case, I use a built in travel database from NetBeans.

There are two examples. The first one is a simple database binding, and the second uses the Option class to control the output.

The Option class allows us to insert any "filler" into the items we display in the list. Here is the code.
    public Option[] getOptions() {
List<Option> options = new ArrayList<Option>();
personDataProvider.cursorFirst();
Option firstOption = new Option(personDataProvider.getValue("PERSON.PERSONID"), (String) personDataProvider.getValue("PERSON.NAME"));
options.add(firstOption);
Option filler = new Option(99999, "----------");
options.add(filler);
while (personDataProvider.cursorNext()) {
Option option = new Option(personDataProvider.getValue("PERSON.PERSONID"), (String) personDataProvider.getValue("PERSON.NAME"));
options.add(option);
}
return options.toArray(new Option[options.size()]);
}
Here is the source code DropDownListExample. The example was created using NetBeans 6.5.1 and Visual JSF plugin.

Wednesday, April 01, 2009

JSF 1.2: Visual JSF ( Project Woodstock) Table Row Striping, or Alternating Row Colors

I recently encountered some issues with setting the class attribute of my table rows using Javascript on Internet Explorer, and Firefox 3.0.8. The class was designed to change the background of the <td> elements of my table. I finally decided that I would try using the TableRowGroup styleClasses tag to try to accomplish the "striping", or alternating the color of odd and even rows in the table. The tag description indicates that it is as easy as adding two style classes which will accomplish this. This is not quite true if you have tried it.

The CSS for the table component in Woodstock has defined a background-color of white (#FFFFFF). This makes overriding it quite difficult.
I accomplished overriding it by placing the same element in the stylesheet.css file located in the project.

Here is what I added:
I then added my new css classes to the TableRowGroup as seen below.



The final result was to produce an elegent table with alternating colored rows.



Here is a link to the NetBeans 6.5 project on BitBucketTableAlternateRowStriping

Friday, February 06, 2009

Book Review: Pro Netbeans IDE 6 Rich Client Platform Edition

Disclaimer: Adam Myatt and I have been on the JavaOne 2008 and 2009 Tools and Languages Review Committee. I don't believe that there is any predjudice for/against the book, but in the interest of disclosure I thought it important to mention. Don't you wish politicians had that much honesty?

I had the pleasure of reading the Pro NetBeans IDE 6 Rich Client Platform Edition book by Adam Myatt. I had read it a while ago, but I did not have the time to do a review on it. The book is sixteen chapters long, and covers a variety of topics from download and installation to developing rich client applications. The book covers version 6/6.1 of NetBeans, but there is significant applicability to version 6.5 to make it worth purchasing.

The book has a primary target of new users to the NetBeans IDE. It is designed to take you from novice user to power user in a systematic organized way. The book is sufficiently modular that you can choose to read individual modules, or go from cover to cover. The chapters stand on their own so that you do not need to worry about missing something in a previous chapter if you decide to browse.

Based on the easy reading style and effectiveness of communicating complex topics, I would give the book (4/5) stars.

Chapter 1:
Downloading, Installing, and Customizing NetBeans

This chapter covers the basics of installation, and explains a number of options available for configuration.

Chapter 2:
The Source Editor

Here we cover the basics of the source code editor and its windows. It also covers some interesting features of the source editor like the error stripe and annotation glyphs. The error stripe allows the user to go directly to any errors which are in the code. The annotation glyph provides the user with suggestions. These may be as simple as reminding you to mark @Override on an overridden method.

One of the best discussions in the chapter has to do with built-in and custom macros you can create to simplify coding tasks. This was a great explanation of how it works.

Chapter 3:
Code Completion and Templates

Code completion is what makes an IDE so valuable. This chapter covers the NetBeans code completion technology in detail.

It also covers code templates which are a boon to any developer who learns to use them. Adam really explains this in a manner that makes them easy to learn and use.

Chapter 4:
Debugging

I thought I was fairly sophisticated in my use of debugging. This chapter made me feel inadequate. After reading it and implementing some of the ideas, I feel I am back to being an expert.

Note: I found one error on page 95. The third paragraph has Run --> Run File -->Run Debug Evaluate Expression. It should be Run --> Run File --> Run to Cursor.

I would buy the book for this chapter alone.


Chapter 5:
Profiling

This chapter covers profiling for performance. Sun and NetBeans has spent a lot of time creating this technology (like DTrace), instrumenting, and providing tools. It is a shame that they really have not promoted these capabilities to the developer community.

Adam has spent a lot of time detailing profiling and providing great examples to get you into it. His explanations may be enough to encourage developers to use these really great tools.

This chapter also includes how to profile remote JVMs and application servers. It is a really slick explanation and demo.

Chapter 6:
Managing Version Control

This chapter covers version control system implementations in NetBeans. It covers CVS and Subversion. Since the book was written, the Subversion implementaion has had numerous improvements. NetBeans 6.1 and 6.5 also include support for Mercurial.

Chapter 7:
Generating and Accessing Javadoc

This chapter covers Javadocs and tools in the IDE to make Javadocs easier to create. I must admit I thought they were already easy, but there are some features to make it even easier including code completion.

Chapter 8:
Managing Builds with Ant and Maven

This covers Apache Ant and Maven implementations in NetBeans. Adam covers some of the features of Ant with a high degree of skill. He covers the NetBeans implementation very well.

The section on Maven is a weak spot in the book. In fairness, the version of NetBeans which the book was based on had poor Maven capabilites. Version 6.5 of NetBeans has much better tools for handling Maven.

Chapter 9:
JUnit Testing

This chapter covers JUnit testing. This is another chapter that is a little to weak. NetBeans 6.0, 6.1, and 6.5 have some really great implementations for doing JUnit testing. This chapter does not do it justice.

Chapter 10:
Refactoring

This chapter covers refactoring. NetBeans has some really great refactoring tools.

JetBrains IntelliJ IDEA is the gold standard for refactoring, but each generation of NetBeans brings it one step closer.

There are some comprehensive explanations of how to use the refactoring tools in NetBeans. If you want to master the IDE, this chapter, and chapters 4, and 11 are a must.

Chapter 11:
Code Quality Tools

This chapter covers some of the really great plugins that are available for NetBeans including: Checkstyle, PMD, and SQE (FindBugs). If you are not using these static analysis tools in your code, you are doing yourself and customers a disservice. This chapter covers the tools in enough detail to get your interest. These plugins are in constant development, and you should check the latest versions and updates out.

These tools will make your code much better. You as a developer need to understand why. When Checkstyle marks code as a "Magic Number", you need to read the explanation. Understanding the why will help you to avoid these problems in your future code.

Chapter 12:
Developing JRuby/Ruby on Rails Applications

This chapter covers developing JRuby, and Ruby-on-Rails (RoR) applications using NetBeans. The chapter is not designed to teach you to program in Ruby, but to show you what features are available in the IDE. The NetBeans support for Ruby is fantastic. A number of other IDE developers are trying to emulate the functionality. I think that most Ruby developers will find that the support is a quantum leap in terms of ease and functionality over more traditional tools.

There is a note on page 297 which explains a really neat feature. If an existing application is deployed using Webrick, or Mongrel on port 3000, the IDE will increment the port number to prevent port in use errors.

Chapter 13:
Developing Web Applications

This is a long chapter covering web application development. The first part of the chapter covers the functionality of the IDE in terms of what features it provides. This includes items like the Javascript and CSS editors. Both of these tools are really useful.

The Javascript editor and debugger have been vastly improved in NetBeans 6.5.

The CSS editor with a change viewer make designing, or changing a CSS file a snap.

The chapter also covers the application server features and HTTP monitor. Specifically it covers Apache Tomcat and GlassFish. It explains how to add additional servers like JBoss, or Websphere to allow those server deployments.

The second half of the chapter covers web application development frameworks. The section covers Struts, Struts 2, Visual Java Server Faces (JSF) (Project Woodstock), and JMaki.

The Struts and Struts 2 section is relatively small. It provides the user with the basics of how to create and use Struts based projects.

The section on Visual JSF development is extensive and makes the book worth purchasing. The explanation on how to get started will set you on the right path. The section on visual data binding is elegant and simple. It also covers the Visual Database Query Editor. This functionality has been updated in NetBeans 6.5, but the explanation here still applies.

Note: Visual JavaServerFaces (JSF) development in NetBeans has been frozen. The promise of Project Woodstock in a version 4.3 release and beyond has been abandoned officially by Sun. The current supported version is 4.2. It will continued to be supported by the NetBeans team for the foreseeable future. The push by Sun is to provide support using third party providers of JSF components. The best of these providers is ICEFaces. They have a really great set of components, and have provided a transition plan for Project Woodstock developers.

The section on JMaki is too brief to really provide a great explanation of this great technology.

Chapter 14:
Developing Web Services: JAX-WS, SOA, BPEL, and RESTful

This chapter covers JAX-WS, SOA, BPEL, and RESTful services. These projects have undergone extensive updates which makes the information here slightly dated. The basic procedures are the same, but there are better tools in NetBeans 6.5.

Chapter 15:
Developing GUI Applications

This chapter covers GUI application development. It is the best aggregation on the subject I have seen. There are a number of tutorials on the NetBeans site, and some good explanations of the features, but this is the best explanation I have seen. There is a great tutorial example of how to use the various components of the IDE to do visual Swing development. I was impressed and learned some new things too.

There is a section on the Swing Application Framework (JSR-296) which is the best I have seen. This technology is supposed to make Swing development easier. I used the information in here to create an enterprise wide application in 1/4 of the time it normally takes. It was also less error prone since the framework handles threading and concurrency issues.

Note: On page 427 there is a code example that has the user add a showHelloWorld method. There is a missing variable that needs to be added. It should have:
private JDialog helloWorldBox;
There is another section on Beans Binding (JSR-296) which covers another ease of use technology for Swing. It allows the developer to bind data components to Swing components in an easy and consistent way. The explanation here of the technology combined with JSR-295 makes Swing development easy. It also covers the Database Table Editor to make modifying tables easy to use as part of the binding process.
Note: Page 431, last paragraph indicates that you can use the DOUGHNUTS table node to use the table editor, this is not correct. You must open the table, and select a column to open the table editor.

Note: Page 442, to use the validator you have created, you must compile the code first. Either by selecting the class itself and compiling it, or clean and building your project.

I personally found that the GUI project development section was crucial to me for using these great new technologies, and development of a successful enterprise Swing application.

Chapter 16:

Developing Rich Client Applications

This chapter covers the development of Rich Client Platform applications using the NetBeans platform as the base for your application. This section provides an introduction to the technology, and the basics of how to create your own branded rich client applications.

Summary:

I would recommend this book to anyone who wants to learn more about the NetBeans IDE.

Based on the easy reading style and effectiveness of communicating complex topics, I would give the book (4/5) stars.

Tuesday, November 25, 2008

JSF 1.2 : Project Woodstock Add/Remove Component Example

There have been a number of people who have asked me for example code on how to use Woodstock (Visual JSF) add/remove component examples. I have decided to post a proof-of-concept piece for people to use. It is using Woodstock 4.3 Build 7, but should work on 4.2 if you change the theme library to use 4.2 in the code.

Here is the code example: WoodstockAddRemoveComponentExample.

Monday, October 20, 2008

Happy 10th Birthday NetBeans

It is hard to believe that NetBeans is 10 years old. It seems like it was just yesterday that I switched from Sun Forte, Sun Studio Enterprise, and Sun Studio Creator to NetBeans. Don't get me wrong some of these IDEs were more polished at the time, and based on NetBeans in some cases. NetBeans just kept growing and the other IDEs fell by the wayside.

Why have multiple code bases? Sun made a good decision to focus on the community tool instead of wasting time on multiple code bases. It took time to get to this point though, but I think we can all agree it was a good decision.

I am participating in the NetBeans Decathalon. They wanted to know how I use NetBeans. Well as you can see from my blog... I use it on everything! On a serious note, I use NetBeans to develop enterprise class applications for my employer. It is a complete package from head to toe to accomplish this task. Most of my applications are JSF based interacting with JMS, EJBs, and Web Services. All of this on top of Project GlassFish.

My biggest project with NetBeans was using Visual JSF a.k.a Visual Web Pack (VWP) (Project Woodstock) to develop a timesheet tracking system which linked to our field force automation system and SAP.

This is also my favorite NetBeans story...

I decided to use VWP in NetBeans 5.0 to start the development. As more features were added to VWP, I kept upgrading. Eventually I was using 5.5 nightly builds along with Glassfish nightly builds. This became our production environment. NetBeans 6.0 nightly builds and GlassFish V1 Build 48. I just took Glassfish B48 out of production last week and replaced it with V2 UR2. This is a testament to how solid Glassfish is, and how useful NetBeans was in accomplishing my task.

I have been tasked to update this application by years end. I am waiting for NetBeans 6.5 to be released before I start. I am also waiting for some definitive word on Project Woodstock.

Happy Birthday NetBeans...

Sunday, March 02, 2008

Netbeans Visual JSF: Woodstock DropDown component using Calendar and Date objects

In this example, I will create a Netbeans Visual JSF Web Application using Woodstock DropDown components which use calendar and date objects. There will be some basic AJAX and validation.

Using Netbeans 6.0.1, create a new web application and select visual jsf as a framework.



This should create a visual web application.

Open the source packages directory from the Project window and click on the SessionBean1.java file. This class represents items which should be stored in the session which we want available between page views. Add the following properties to the bottom of the file:

private GregorianCalendar startCalendar;
private GregorianCalendar endCalendar;
private Date startDate;
private Date endDate;

public GregorianCalendar getEndCalendar() {
return endCalendar;
}

public void setEndCalendar(GregorianCalendar endCalendar) {
this.endCalendar = endCalendar;
}

public Date getEndDate() {
return endDate;
}

public void setEndDate(Date endDate) {
this.endDate = endDate;
}

public GregorianCalendar getStartCalendar() {
return startCalendar;
}

public void setStartCalendar(GregorianCalendar startCalendar) {
this.startCalendar = startCalendar;
}

public Date getStartDate() {
return startDate;
}

public void setStartDate(Date startDate) {
this.startDate = startDate;
}
After adding these component, right click on the page and fix imports. These properties will persist our values when we submit our page.

Next go back to the page and add 4 DropDown List and 4 StaticText components to the page from the palette. Add a DateTimeConverter and a CalendarConverter to the page. Right click on the staticText components and bind to data. Select bind to object and select startCalendar, on the next staticText field select endCalendar. Repeat for the remaining two staticText using start and end dates. After completing this select each component, and in the properties select the appropriate converter to be applied.





At this point we need to add a little Java to the backing bean. Add the following code to the page:



public Option[] getCalendars() {
ArrayList<Option> l = new ArrayList<Option>();
ArrayList<GregorianCalendar> calendars = new ArrayList<GregorianCalendar>();
GregorianCalendar gc = (GregorianCalendar) GregorianCalendar.getInstance();
gc.setTime(new Date());
gc.setTimeZone(TimeZone.getTimeZone("EST5EDT"));
gc.set(GregorianCalendar.HOUR_OF_DAY, 0);
gc.set(GregorianCalendar.MINUTE, 0);
gc.set(GregorianCalendar.SECOND, 0);
gc.set(GregorianCalendar.MILLISECOND, 0);
for (int i = 0; i < 24; i++) {
for (int j = 0; j < 60; j += 15) {
GregorianCalendar clone = (GregorianCalendar) gc.clone();
clone.set(GregorianCalendar.HOUR_OF_DAY, i);
clone.set(GregorianCalendar.MINUTE, j);
calendars.add(clone);
}
}
gc.set(GregorianCalendar.HOUR_OF_DAY, 24);
calendars.add(gc);
Collections.sort(calendars);
for (GregorianCalendar c : calendars) {
Option option = new Option();
option.setLabel(String.format("%02d", c.get(GregorianCalendar.HOUR_OF_DAY)) + ":" + String.format("%02d", c.get(GregorianCalendar.MINUTE)));
option.setValue(c);
l.add(option);
}
return l.toArray(new Option[l.size()]);
}

public Option[] getDates() {
ArrayList<Option> l = new ArrayList<Option>();
GregorianCalendar gc = (GregorianCalendar) GregorianCalendar.getInstance();
gc.setTime(new Date());
gc.setTimeZone(TimeZone.getTimeZone("EST5EDT"));
gc.set(GregorianCalendar.HOUR_OF_DAY, 0);
gc.set(GregorianCalendar.MINUTE, 0);
gc.set(GregorianCalendar.SECOND, 0);
gc.set(GregorianCalendar.MILLISECOND, 0);
for (int i = 0; i < 24; i++) {
for (int j = 0; j < 60; j += 15) {
GregorianCalendar clone = (GregorianCalendar) gc.clone();
clone.set(GregorianCalendar.HOUR_OF_DAY, i);
clone.set(GregorianCalendar.MINUTE, j);
Option option = new Option();
option.setLabel(String.format("%02d", clone.get(GregorianCalendar.HOUR_OF_DAY)) + ":" + String.format("%02d", clone.get(GregorianCalendar.MINUTE)));
option.setValue(clone.getTime());
l.add(option);
}
}
gc.set(GregorianCalendar.HOUR_OF_DAY, 24);
l.add(new Option(gc.getTime(), String.format("%02d", gc.get(GregorianCalendar.HOUR_OF_DAY)) + ":" + String.format("%02d", gc.get(GregorianCalendar.MINUTE))));
return l.toArray(new Option[l.size()]);
}



Note: Fix the imports, make sure that you choose import com.sun.webui.jsf.model.Option as the item to be imported.

Save and clean and build the application. This will refresh the framework so we can bind the new methods to our dropDown Lists.

Go back to the Design view. Click on the first two dropdown lists and bind them to the Page1.calendar items. Click on the next two items and bind them to the dates.


Next go to the properties and set the converters on the dropdown lists as appropriate. CalendarConverter on the first two dropdown lists and DateTimeConverter to the remaining dropdowns.

Next set the selected value to the appropriate property on the SessionBean1 Data Bean. startCalendar for dropDown1 and endCalendar for the second dropdown. Repeat for the date dropdowns. Add an appropriate label for each dropdown. I named them the same as the SessionBean1 property to be bound to.

Add a button and call it submit. Your example should look like this.


Next deploy the application and confirm that it works.

Next we will add some AJAX to the dropdown items. On dropDown1 add the following to the onChange event listed under the properties:
$('form1:dropDown1').submit(), $('form1:staticText1').refresh();
Repeat on the other dropdown components, but change the tags to point to the appropriate dropDown and staticText items.

Next, click on the calendarConverter1 component and change its properties: to

dateStyle: full
timeStyle: full
timeZone:EST5EDT
type: both
Repeat the process for the dateTimeConverter1.

We will now add a validator to dropDown2 which should be the endCalendar bound component. On the properties select validate under Events. Use the default handler listed. It should be dropDown2_validate


Go to Java source and navigate to the dropDown2_validate() method. Add the following code:


public void dropDown2_validate(FacesContext context, UIComponent component, Object value) {
GregorianCalendar end = (GregorianCalendar) value;
// dropDown1 is an AJAX component so the value on the backend is updated.
GregorianCalendar start = (GregorianCalendar) dropDown1.getValue();
if (start != null) {
if (end.compareTo(start) < 0) {
throw new ValidatorException(new FacesMessage("End Time must be greater than start time."));
}
}
}
Note: You need to ensure that you have both the start and end dropDown components. If they have different names, you will need to adjust the logic above to the appropriate dropDown component ids.

Your page should look something like this when you are done.



Redeploy the application. Check to see if the staticText fields update when you change values on the dropDown lists.



The submission should fail if the endCalendar is before the startCalendar.

I hope you enjoyed this brief tutorial. The files for the application are located here: CalendarDateDropDownExample.zip

Postscript: I asked for some folks at Sun to take a look at the page. They gave me some cool and interesting criticism of the tutorial.

One item that was not clear was that there are Woodstock components for calendars and schedulers. This is really an example of using a dropDown component with java.util.Calendar and java.util.Date.

It was suggested that I should use one or the other, but not both. Since this example is done, I will not change it. I will keep this in mind for future tutorials. The criticism was that it essentially was a duplication of effort and does not clearly state the case. I agree.

Additional Notes:


The project was developed using Netbeans 6.0/6.0.1 and Visual JSF (Project Woodstock 4.1.1). The latest version of Netbeans (6.1) includes Project Woodstock 4.2.

Project Woodstock has undergone a tremendous amount of changes from 4.1.1. This includes removing Prototype (JavaScript framework) and using a custom version of Dojo toolkit. The AJAX in this application depends on Prototype. You will need to install prototype in the project by adding a jar to the libraries. Here is prototype-1.5.0.jar.

Popular Posts