Sunday, July 29, 2007

Make Your Webapp Speak French

Whenever you create a web application that has global implications, you always need to internationalize it. This means it should be able to interact with the user in their browser or selected language. Our latest requirement for the timecard utility is for usability in both English and French. It demonstrates how to internationalize a JSF application using message bundles.

Message bundles are resources provided through properties files. The java.util.ResourceBundle is a convenient class used to access resources availed to the application. Properties files hold key/value pairs of strings.
Creating internationalization property files is typically a manual process: you identify what text on the UI needs to be in alternative languages, create key/value pairs for them in a properties file, then copy the whole set to other properties files - providing translated text in those files. As you can already tell, to change a single text element, you need to update all other files as well. Also, if you change the key, you need to manually update the classes that use that key directly. NetBeans 6.0 does not provide context-sensitive code completion between properties files and Java classes.

To implement the requirement specified, you create two property files - one for English and the other for French, then populate them accordingly. So, if I put in the english.properties title = Timecard Utility, then I need to also put in the french.properties title = Utilité de Carte de Pointage. The application will only look for the title key in the appropriate properties file and print out its string value. In the JSP, you'd need to call the french properties file with:
<f:loadBundle basename="com.strive.research.intl.french" var="lang"/>
(assuming it is in com/strive/research/intl package).

While this strategy works well, it doesn't update strings generated in the application itself and the propery file to use cannot be set dynamically. The solution is to use your managed bean to set which file the JSP should used. To do this, you create an additional variable in the managed bean that can be set based on the user's selection. When the selection is made, an appropriate locale and properties file are set before the page is redisplayed. To be able to print language-appropriate dates and times, you'd need to take advantage of the java.util.Locale class. The image below shows the result of selecting the French language option.



The big advantage of this implementation is that you don't have to change much code to support additional languages. Also, text changes can be made without having to recompile the application.
JSF also provides a mechanism for automatically applying the correct language based on the browser language. You'd need to set that up in faces-config.xml.

Brandon, let me know if you need the source code for this - pretty minor changes - and I'll send it to you. This application is growing bigger and bigger codebase-wise.

A Break On The Bass

This is an Overwater 6-string bass similar to something I'd like to own someday. Reviews of this bass are favorable, but the $2000 price tag is a bummer for most of us.
With a bass guitar like that, you need a stack that includes a cabinet such as this 1500-watt Epifani UL2-610 (about $1500) and a matching amp head (some 900+ watt box from Carvin or GK). O, and don't forget the cool multi-effects pod (like the Boss GT6B) that comes in handy on solo gigs. With equipment like this, I know I'd crank out bass tunes that'd surprise even myself. You begin looking professional at that level.

I've hang out with some bass players that are fond of bragging about their tools or which lengendary bass player they are trying to emulate, and yet when they set up to play, they stink. There's another breed of bass players that use the lowest end equipment (no bragging rights) and yet produce the sweetest grooves. That's the camp I'd rather be in - purely good skill and style. Granted, any good musician should invest in good equipment, but you don't have to go overboard.

I'm probably the weirdest bass player anyone will ever meet: I don't know how to read music (play by feel and ear), don't know who the great bass players and pioneers are, don't even know what equipment I should have, don't practice for my gigs (you'd think I'd be good at improvising, but nah!), don't maintain my equipment well (I haven't changed strings on one of my bass guitar in over a year), and don't play by the rules much. I have my own sound that sometimes works as bass (because I play it on a bass guitar). I'm a little better than a generic bass player, about average in fact, the experience (of 6 years come September) having helped me add some salt to my playing. I think one of my biggest handicaps is my interest in diverse kinds of music. Granted, I don't like opera or metal/hard rock or certain pointless R&B/Hip-hop/Rap music, but I can handle all kinds of music from all over the world based on thei artistic merit. If it has a beat and bass, I'll probably listen to it. That exposure leaves we wanting to learn everything about those kinds of music - so I end up having no influence or specific style. The question "who are your influences?" is often answered with "Hmmmm ...".

But with 2 records under my belt, a couple of recurring studio gigs, several opportunities to play in worship bands, and a few side projects with local artists and musicians, I suppose I don't stink after all. Though, I know there's much more I can do with this skill. Virtuoso players like Victor Wooten get me on fire - a challenge to improve my game. Though I'll probably never play like him, I can learn a lot from his style and technique. My dream would be to have the ability to take a common song and reinvent it from a bass perspective - give it some fresh air and new taste. There's always a danger of "going flat" once you start playing well and often, where you begin to overuse the technique you have with no new skills. That's the runt I want to get out of ... it's a catalyst for burnout if one is ot careful.

When you are busy as I have been, there's not much time to focus on your talent and improve. So in September, I'm dropping most of my engagements to embark on a learning trail - to explore ways I can be a better musician and bass player, add some professionalism to my game, and develop a character that's more consistent with a serious bass player. I'd like to learn new things and implement many of the suggestions and critique I've received over the last few years. Because music is only a hobby at this time, I'd also like to explore what it'd take to become a professional bass player.

My good friend Dave Taylor (a good drummer) had asked me once: "if you were given $1million to just play music and quit your job, would you take it?" The answer may surprise many, but I said "no". The reason is this: I don't care how much I make as long as the tasks keep me challenged enough that I don't get bored to death. For me to stay "alive", I need constant challenges and things to figure out. I could learn some serious grooves that make me a celebrity, but I'm not satisfied if I can never improve on them. With music, there's nothing "unknown" about music in this age, so creativity rests in composing and arranging with what we have now. My day job is n technology research, and the challenges are endless - which keeps me excited and looking forward to what the day may bring. Besides, I'd be a lazy bum if all I had to do was make music (all bills paid for). I think I'd start making bad music eventually just because I have the expectation to make music. This is a weakness in Hollywood studios: they sign a director and ask him to produce 5 movies a year. The pressure will cause him to produce crappy movies sometimes, just to fulfill his end of the bargain.

In any case, I think it's high time I returned to the basics, took a break, learned a few new things meanwhile. If I've made commitments to you already, I'll still honor them. Just don't be surprised when strange (read experimental) sounds come from me .... Also, I continue to be a backup on occasion. They say you never really abandon your talent, but I'm going to try and chill out the public aspect of it.

Saturday, July 28, 2007

Selection Input for JSF Forms

Supposing the client for the timecard utility sends us two new requirements - that users should have an option of entering time as 24-hour or 12-hour format, and be able to review and modify up to 4 previous weeks in addition to the current week. In HTML, this would mean using radio buttons for the time format and a dropdown list for which week is being viewed/modified.
In JSF, you can use any of <h:selectBooleanCheckBox>, <h:selectManyCheckBox>, <h:selectBooleanListBox>, <h:selectManyMenu>, <h:selectOneListBox>, <h:selectOneMenu>, or <h:selectOneRadioButton>. To implement the requirements specified, we use <h:selectOneRadioButton> for radio buttons and <h:selectOneMenu> for the dropdown list.
Fortunately, JSF has the same mechanism for using these components. You create a class that returns SelectItem[] objects, and use it in both the JSP (to populate the components) and the managed bean. The thing to be careful about is to put components that are supposed to be updated together in their own form elements. Only those elements are updated when a button is clicked.

To start with, we create a new Java class in our project that holds the options. Here's the source code for Options.java. It declares the options we need and appropriate getters/setters. It also has a temporary routine to generate the 5 weeks needed. This method can be extended to read this data from a database.
The managed bean can then add attributes that use the options selected in the form. Here's the sources for Timecard2.java. The JSF configuration file would need to be updated with navigation rules (new faces-config.xml) for the options, and the main display JSP updated to show the appropriate components (here's index.java). After you deploy the application, you should have something that looks like this:

With this new build, a user can choose what format to enter time as, and which week to view by selecting the appropriate. This example demonstrates how easily a JSF application can be extended. It also begins cracking at the power of the JSF framework - there's much much more you can do with this technology.

Using Subversion for NetBeans on Windows XP

Any programmer by now knows the value of having a source versioning and change management facility. A day comes when you mess up existing programs or lose your work, and that's where you can check out the latest working version from a repository somewhere. Beyond that, other benefits of using SCM include source code control and configuration management.
Because of simplicity and cost (free), I decided to use Subversion as the SCM solution. Subversion is designed to replace CVS, which I've had some trouble with. My latest aggravation comes from CVS's popular error message "cvs [server aborted]: Couldn't chdir to working directory : Invalid argument" (2.0.51d). Rather than try to resolve the issue, I decided it was time to find another solution, thus Subversion.

We've come to a point in development where we are making a lot of changes to the timecard utility. In order to preserve all our work, we should start checking it into a repository. This will also allow us to branch the application and merge changes from various contributors.
Here's the process for installing Subversion n Windows XP and to use it in NetBeans 6.0 (M10).
  1. Download Subversion from http://subversion.tigris.org/project_packages.html. Choose the binary executables under the Windows section. I'm using version 1.4.4.
  2. Run the executable and note the install directory (C:\Program Files\Subversion).
  3. Add environment variables: SVN_EDITOR = C:\Windows\notepad.exe (to use Notepad as the log editor), and to PATH += C:\Program Files\Subversion\bin (NetBeans needs this).
  4. Create a database directory that'll hold your versioned projects (J:\Subversion). Use the usual Windows Explorer for this.
  5. I want all my NetBeans projects to be versioned under the NetBeans directory in the SVN database. So we create a repository as such - at command prompt, svnadmin create "J:\Subversion\NetBeans". A directory should appear under your SVN database (#4).
  6. The repository in #5 above has a conf directory. Open the svnserv.conf and uncomment anon-access = read, auth-access = write, and password-db = passwd. Save that file.
  7. Open the passwd file with a text editor and add a user under [users] in the form username = password. Save the file.
  8. Create a windows service for SVN: at the command prompt, run sc create svnserver binPath= "\"C:\Program Files\Subversion\bin\svnserve.exe\" --service --root J:\Subversion --listen-port=6043 --listen-host=localhost" DisplayName= "Subversion Repository" depend= Tcpip. Startup is manual, so visit the Services applet and set how you want it to start, and start it.
In NetBeans, import the project into SVN:
  1. Right-click the project -> Versioning | Import Into SVN Repository ...; repository url = svn://localhost:6043/NetBeans, enter the username and password specified earlier. [Next].
  2. Repository folder defaults to the project folder name. I'd leave it like that. [Finish].
That's all! At the completion of each task, you should check your work in. If multiple developers work on the project, synchronize your local workspace with the latest from SVN.

Wednesday, July 25, 2007

Basic UI Design With JavaServer Faces (Pt. I)

In May, I wrote a post about getting JSP-based webapps to use JSF. Based on that post, we will convert our existing timecard utility to a JSF-based web application. The steps in the JSF post are largely good enough, with exceptions that I mention in here.

Be prepared to write a whole lot more code. The coding isn't hard - it's the repetitiveness and time you spend doing it that takes the steam out of it.
Beyond changes required by JSF (config files), we only change the JSP (add JSF markup) and bean (make it managed). In the end, we still get the same look and the application accomplishes the same things as before.
This implementation has 60+ components (areas, fields) on the page that need to be updated dynamically. The bulk of them are in the display table itself, and the rest are the various total and summary fields. We keep it simple in this example and use only <h:view>, <h:form>, <h:inputText>, <h:outputText>, and <h:commandButton> for JSF markup, although we could have just as easily implemented a <h:panelGrid> for the table.
You have to start worrying about session management. Case in point, if the view expires (either because the application was restarted or the session expired), you start getting exceptions like "javax.servlet.ServletException: viewId:/index.faces - View /index.faces could not be restored" caused by javax.faces.application.ViewExpiredException. That means you have to start over, as JSF emphasizes navigation/page flow (you need to start at the beginning).
JSF does not cure issues you already had in the JSP solution - all the bottlenecks and inefficiencies in algorithms will still be there. In fact, you might end up tossing lots of code, such as those that depend on parameters and field names passed from the client. It's true that pure HTML is generated by the JSF framework, but fields never have consistent names, especially when the view is regenerated.
I might add that JSF introduces its own issues - hints that designing a JSP app can be quite different from JSF - the need to plan everything and stick to the plan. They just behave differently.

Source code:
# The JSF-aware JSP file (index.jsp).
# The overhauled bean to support JSF (TimecardBean2.java).
# The other classes and pages remain the same.

After deploying the webapp, it's now available at <domain>:<port>/<webapp>/index.faces (as opposed to the usual <domain>:<port>/<webapp>/, which would have called index.jsp). Even with the <welcome-file> element set in the deployment descriptor to open the *.faces page, SJSAS web server does not get it right. Though, you can set NetBeans to open the page specifically (debug/run).

Some NetBeans 6.0 (M9) quirks:
(1) You don't get the option to reset encapsulated attributes' access levels when generating setters/getters, so remember to precede them with 'private' during declaration.
(2) The IDE no longer has a means to select all variables [Select All button] for which you are generating setters/getters. In fact, it also no longer allows you to select which getters or setters you want on one screen - how it was done in version 5.5].
(3) Whenever you add breakpoints in debug mode, you have to "debug project" again = compiling and deploying to a debug-mode server. Quite inconvenient, as some may wonder why breakpoints are not working.
(4) Code completion is case sensitive. The whole idea of this feature should be to reduce having to remember variables in your classes/pages. Now I have to remember whether I capitalized something or not?

Monday, July 23, 2007

Dynamic Web Content With JavaServer Pages (JSP)

Anytime you go to a website and it knows who you are, or asks you to log in, or you can do tasks on it, etc., that site is no longer static. Such dynamic websites run at least one web application to accomplish all those tasks. It doesn't have to be complicated really - a simple mechanism that responds autonomously to user requests can be considered a "web application". The previous timecard utility application was not dynamic. If you hit [Update], nothing happens. In this post, I describe a strategy to give that button some life. The result is shown above.

There're several ways to create dynamic web applications, including ASP and PHP, but I chose to use JavaServer Pages (JSP) to implement this functionality. The idea is simple: when a user clicks the update button, send all the data entered into the page to the server and update totals (lunch/work hours and week summary on the right).
This arena takes a basic web designer into the world of programming. Several tutorials exist on the web, including Sun's JSP Tutorial and the Java Tutorial. With these two resources, I've never really needed to buy reference books.

My implementation here simply uses JSP in its most popular form - mixing scriptlets and HTML code. When the page is called, it checks for a required session object and if none exists, creates one. That session object holds the dynamic data we need in parts of the page.
The session object is written along JavaBean conventions, but since we do not use it as such in this example, it can be any POJO. That class does the actual calculation of the times. The strategy is to use the principles of OOP for most server-side programming. Here, the timecard object depends on a Day object (which represents a typical day's hours - a column in our table), and a Week object (which represents all the Days of a week - the whole table). Each Day knows how to add up its own hours, and the week knows how to add up the computed hours from its Days to create a summary.

In NetBeans:
(1) Update the JSP code.
(2) Add new Java classes: TimecardBean.java, Day.java, Week.java, and a utility/helper class for formatting and parsing times and dates - DateTime.java.
(3) Deploy to the web server.

# As the code show, we are now naming fields of the form dynamically so that we'll be able to read them back easily. Also, business rules are implemented concerning the accumulation of work hours. For example, all day hours are rounded to the nearest quarter hour, and a mandatory lunch period is deducted if someone works more than 4 hours (and doesn't take lunch).

It's as simple as that - and you have a dynamic web application. Our code now also reports any errors it encounters and catches a few exceptions.
Possible problems so far with this kind of solution include a slow user experience because whenever the update button is clicked, the web server clears the timecard object and repopulates it with data sent from the client, recalculates all values, and regenerates the HTML to send to your browser.

Skills Needed: Basic Java and JSP programming.
Technologies So Far: HTML, CSS, Java.
IDE: NetBeans 6.0 (M9)
Web/App Server: Sun Java System Application Server 9.
JDK: 1.6+

Friday, July 20, 2007

Dress Up HTML With CSS

So far, our basic web designer knows how to write HTML and can run web applications on a web server. He has designed a mockup UI for the timecard utility, and although it doesn't do anything yet, it can be used to polish requirements. This is a followup to Simple Applications On Basic Web Servers. The prototype so far doesn't offer much visually and does not look that professional, so our goal here is to make it somewhat visually appealing. You do this with CSS.

You'll be surprised how many web designers and programmers out there have no idea or do not know how to use Cascading Style Sheets (CSS). I was one of them - I was comfortable doing database and business logic programming that I did not care much for how content was presented - that was another team's responsibility. However, as I began owning whole projects, I found it necessary to understand the presentation of content. It not only makes me a more well-rounded developer, but has affected how I do development. Thanks to my friend Ben who helped me get started. [By the way, Ben runs the BenTedder.com web design business].

Basically, CSS defines how HTML elements are displayed. All major web browsers support rendering web pages with style using CSS. There's several tutorials and books on CSS - it might be advisable to invest in a current desk reference, although you can find pretty much everything you want by simply searching the web. Theres even websites that have complete templates and programs you can use to generate CSS code for you. Although they make work easy, sometimes it's better to know how things work under the hood - whole reason to read up on CSS and learn to manually write code. The W3C CSS Tutorial is a good place to start; reference books you buy should be advanced beyond the basics on that site.

Here are some advantages of using CSS, including ability to make layout and visual changes for multiple pages from a single point, reduction of HTML code base, separation of style from content, and ease on search engines (find content rather than style). You should always know though that different browsers behave a little differently to CSS. Your best bet is Firefox to do better, as it is more compliant to standards than Internet Explorer is.

There are several CSS Editors on the Internet, most of them free or open-source. There are applications too that can generate both HTML and CSS through a visual design process (Adobe Dreamweaver MX??). The NetBeans 6.0 (M10) IDE also includes a CSS editor, which we will use to dress up our timecard application.
  1. Add a CSS file: File | New File. Web -> Cascading Style Sheet [Next]. Name the file (maintimecard), and specify a folder (style) [Finish]. Will be accessible as style/maintimecard.css.
  2. Edit the CSS: NetBeans' editor has quite a lot of features including code highlighting, code completion, macro recording, style builder, and preview. At this stage, we don't need to be looking for another editor.
  3. Link the CSS to the HTML file and update the HTML: you'll have to manually edit index.jsp to link to the CSS file and the HTML to use CSS styles specified. Here is the CSS and HTML code.
  4. Deploy the application.
When you display the application now in a browser, it looks like this. (IE shows a slightly different look, especially that it misses showing the dotted line right below "work hours" line).


How about that? We even add the idea of displaying messages to the user right in the form. Visually, this is a far cry from the basic HTML look we did before.
When I do development though, visual appeal is the last thing I worry about. Usually, you design your business logic first, then the database, and finally the presentation (HTML and such) when you know everything else works. In some projects, visual components are not polished until a later version of the software.

Thursday, July 19, 2007

Simple Applications On Basic Web Servers

Perharps the single most important implementation decision a web programmer must deal with is their choice of platform. When you start coding, the server-side components are usually specific to a language or platform. As an example, if you choose IIS, you'll initially be stuck with Microsoft technologies; if you choose Apache Tomcat, you are choosing the Java path. Of course plugins abound that enable additional features, such as Tomcat behaving like an IIS server, or to run PHP scripts, etc. But this decision usually determines what "camp" you belong to.

A basic web server simply responds to HTTP requests and socket connections. Since we are leaning towards implementing our solution in Java, there are plenty of servers - as listed here on Java-Source - that are free/open-source. Apache Tomcat is perhaps the most popular web server on the Internet today. Though in this exercise, we'll be using the Sun Java System Application Server, which comes bundled with the NetBeans IDE. As usual, I choose web servers based on how easy they are to configure, if my favorite IDEs support them, if they can be debugged on, level of complexity to extend, ease of deployment, and industry reviews that may suggest their performance is production grade. Later as your application grows, you start worrying about clustering and load balancing, response times under pressure, security, etc.

A scenario was presented in a previous post: the need to implement a simple timecard utility. To be able to do "live mockups", you need to have a real web server to which is deployed a foundational prototype. To start with, we'll create a simple application that dishes out HTML representing a basic UI. Instead of using plain HTML files, we'll take advantage of JavaServer Pages to generate the HTML. It also sets us up to use servlet technologies to respond to HTTP requests and ability to dynamically generate content. Many other server-side technologies do the same thing, including ASP, PHP, and ColdFusion, for example.

Often when you do web design, you start with mockups of how the final product might look like. Along with requirements from your client, you might then come up with use cases and such. We'll use NetBeans 6.0 (M10) to create a simple HTML based mockup:
  1. Create a new web project: File | New Project. Choose Project = Web -> Web Application. Project name and location = TimecardWebApp; context path /Timecard. [Finish].
  2. Design your page: index.jsp should be open in the IDE. Just code HTML into this page. Here's HTML code of what's needed to produce a mockup. NetBeans includes a palette that allows you to generate code for basic components using simple drag-and-drop onto the page.
  3. Run the application: right-click the web application -> Run Project. This will start up SJSAS, which is our web server in this context, deploy the web application to it, and open up the page in your default web browser. It should open at http://localhost:8080/Timecard/.
That's all for this step, and you should have something that looks like this:

Of course this page does not do anything yet. We are only interested in the look of the application in order to visually show the client what we will be able to do. The idea is that a user will enter the hours they came to work, took their lunch, left for the day, and any holiday or sick hours awarded. When they hit [Update], it should update the totals. That's all for now - additional features will be added later as the client specifies them (in future posts).

As you can see, IDEs such as NetBeans make web development a snap. Beware with v6.0 M10 though: the full package install take upwards of a minute to get started, and code completion/JIT is still painfully slow. But the advantage with using this IDE is its simplicity of use, available features, and how quickly you can get applications done. Of course whenever we need to implement something, we'll try it first in NetBeans; if it's not possible or there's a better way, we don't want to feel stuck in this IDE.

Wednesday, July 18, 2007

From Simple HTML To Advanced Web Technologies

In these days when even grandma can design and maintain a website - sometimes for free, what value can a web designer or programmer add to justify paid work and interest in their product? I get pretty irked by designers that crank out solutions in pure HTML, and fail to take advantage of web technologies and standards that'd enhance the user experience, make design/programming a breeze, and take advantage of the latest technologies. Most of these things are available for free on the web.

So after chatting with a few developers that are stuck in HTML-only web design, I decided to start this series to demonstrate how you can take a simple HTML application and use all kinds of standards and technologies on it. I'm talking Javascript, CSS, Flash, AJAX, Direct Web Remoting (DWR), JSF, and a myriad other web tooling and presentation APIs, such as Yahoo!'s, Facebook's, or and Google's. I'll approach this series from a Java perspective, exploring everything from using EJB 3.0 for your data layer, various design models and patterns that may apply, and considerations for developing your own components for improved efficiency. We might also touch on issues with various containers and application servers, load-balancing (in code?) and taking advantage of modern IDE features that take the headache out of programming and design. What about designing for mobile devices? We'll see how that can be done.
Another idea is to find a good application or website and reverse engineer it - that's the ultimate learning curve. Since this is essentially "educational" and "research", you are not bound by copyright and other legal issues - as long as you don't steal their code.
Finally, integration with .Net and other technologies is a possibility. What would it take to port application to various environments, or at least have them play together? Of special interest will also be finding out which is the easiest and least expensive way to implement such a solution.

The application I'm choosing for this exercise is a simple timecard utility that can be extended to include features related to time management. This doesn't sound hard, does it? I mean, you can have a prototype literally overnight. All it does is present an interface where users can punch in the hours they worked, and it calculates the usual paycheck. The basic prototype is manual and simple, but it enables us to have something simply functional and see how the various technologies can be used to enhance it. Simple goal.

That said, I'll do Java development in the NetBeans 6.0 (M9) IDE. It comes with the Sun Java System Application Server 9, and that's pretty much all that's needed at this point. Of course you should already have a Java EE 5-aware JDK (1.5 or later). Eventually, we'll need a database to store our information.