Friday, December 25, 2009

Validating empty text field using JSF

JSF has a pretty comprehensive support for validations, but it is lack of a validation for an empty field. The built-in “required” property of JSF is not so usable, since it validates empty fields only. If a field has a space in it, JSF will accept it. In most scenarios, when inputting text in a form, a space (or several spaces) is considered to be an empty field. Since JSF doesn’t support “out of the box” validation for empty field, we will write our own Validator that will do the job.

Writing a JSF Validator mainly involves 3 things:

  1. Writing the Validator code by implementing a JSF Validator interface.
  2. Registering Validator in JSF faces-config.xml.
  3. Using the Validator in a JSF page.

In order to write the Validator we have to implement “validate” method of Validator interface. This method will be called automatically by JSF, when we use the Validator in some of our input fields. Our Validator class simply checks that the field value is not empty. If the field is empty a ValidationException is thrown from the Validator. JSF mechanism knows to treat this exception as a validation error, when it checks the form inputs for validation errors. Let’s have a look at the Validator code:

package com.bashan.blog.jsf.validator;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
/**
 * @author Bashan
 */
public class RequiredValidator implements Validator {
  public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
    if (value == null || "".equals(value.toString().trim())) {
      FacesMessage message = new FacesMessage();
      String messageStr = (String)component.getAttributes().get("message");
      if (messageStr == null) {
        messageStr = "Please enter data";
      }
      message.setDetail(messageStr);
      message.setSummary(messageStr);
      message.setSeverity(FacesMessage.SEVERITY_ERROR);
      throw new ValidatorException(message);
    }
  }
}

Note, that the Validator tries to get an attribute named “message” from the component for which it is attached. The “message” attribute should contain a custom error message to show to the user. If “message” attribute is not used, a default error message: “Please enter data” is shown to the user.

Now, let’s register the Validator in JSF faces-config.xml file. This file should be located under the “WEB-INF” directory by default:

<?xml version="1.0" encoding="windows-1255"?>
<!DOCTYPE faces-config PUBLIC
  "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
  "http://java.sun.com/dtd/web-facesconfig_1_1.dtd">
<faces-config> 
  <validator>
    <validator-id>RequiredValidator</validator-id>
    <validator-class>com.bashan.blog.jsf.validator.RequiredValidator</validator-class>
  </validator>
</faces-config>

You can see in this “faces-config.xml” file the validator id, which is used to call the validator from a JSF page, and the JSF class corresponds to this validator id.

Finally, let’s have a look how this validator is used in a JSF page:

<h:inputTextarea id="someText" value="#{support.message}" styleClass="textarea1" required="true" requiredMessage="Please write something">
  <f:attribute name="message" value="Please write something" />
  <f:validator validatorId="RequiredValidator" />             
</h:inputTextarea>
<div>
  <h:message for="someText" styleClass="error"/>
</div>

This is only a fragment of a JSF page, showing a text area control and a message under it. Note, that the control can be any JSF input like <h:inputText />. Also note for the <f:attribue /> control used for sending a custom message to the Validator. Another important thing worth mentioning, it that the “required” attribute of the <h:inputTextArea /> control is also used with the same error message (using the “requiredMessage” property). One can say, using 2 validations is redundant, and that only the “RequiredValidator” could have been used. This was true, unless JSF mechanism had a problematic issue with empty fields: When field is empty (has no value and no spaces) validators and converters are not invoked. For this reason, both “required” and “RequiredValidtor” are needed to be used.

Monday, December 21, 2009

Tomcat Virtual Hosting

Tomcat is not only a servlet container. It supports many of the features of any HTTP web server and can be also used to serve static content as well. From my experience, it can handle heavy traffic quite decently. It doesn’t fall from it’s big brother: Apache Server, and frankly, there are times it seem to be functioning even better.

One of Tomcat’s features, is Virtual Hosting. Virtual Hosting means that a single web server can server more than one website at the same time. The server knows which website to server according to the domain of the request. For example, if you have 2 domains: http://one.com and http://two.com and you direct both domains to the same IP, the server will get requests from 2 different domains. Then it should know to serve “one” website to requests coming from domain http://onew.com and “second” website to requests coming from domain http://two.com.

Configuring Tomcat to support Virtual Hosting is an easy task. The configuration takes place in Tomcat’s server.xml file, which is placed under the “conf” directory. Inside the “Engine” xml tag, “Host” element should be added for every domain you would like to serve. For example, if we have a web application named “one” and a domain named: http://one.com, The “Host” element should look like:

<Host name="one.com" appBase="webapps/one">
  <Context path="" docBase="" debug="0"/>
  <Alias>www.one.com</Alias>
</Host>

Note that “one” is places under “webapps” which is Tomcat’s natural directory for web applications. Therefore, a relative path is used. In addition, take a look at the alias: www.one.com. That will allow the server to acept traffic from both: http://one.com and http://www.one.com.
Let’s have a look at a full server.xml example file, which defines 2 virtual hosts for 2 web applications: “one” and “two”:
<?xml version='1.0' encoding='utf-8'?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You 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.
-->
<!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 -->
<Server port="8005" shutdown="SHUTDOWN">
  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
  <Listener className="org.apache.catalina.core.JasperListener" />
  <!-- JMX Support for the Tomcat server. Documentation at /docs/non-existent.html -->
  <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>
  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->
 
 
    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL HTTP/1.1 Connector on port 8080
    -->
    <Connector port="80" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" URIEncoding="UTF-8" disableUploadTimeout="true" compression="on" compressableMimeType="text/html,text/xml,text/plain,application/xml"/>
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->        
    <!-- Define a SSL HTTP/1.1 Connector on port 8443
         This connector uses the JSSE configuration, when using APR, the
         connector should be using the OpenSSL style configuration
         described in the APR documentation -->
    <!--
    <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
    -->
    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->
    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Standalone" defaultHost="localhost" jvmRoute="jvm1">      
    -->
    <Engine name="Catalina" defaultHost="localhost">
      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->     
      <!-- The request dumper valve dumps useful debugging information about
           the request and response data received and sent by Tomcat.
           Documentation at: /docs/config/valve.html -->
      <!--
      <Valve className="org.apache.catalina.valves.RequestDumperValve"/>
      -->
      <!-- This Realm uses the UserDatabase configured in the global JNDI
           resources under the key "UserDatabase".  Any edits
           that are performed against this UserDatabase are immediately
           available for use by the Realm.  -->
      <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
             resourceName="UserDatabase"/>
      <!-- Define the default virtual host
           Note: XML Schema validation will not work with Xerces 2.2.
       -->
      <!--Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true"
            xmlValidation="false" xmlNamespaceAware="false"-->
        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->
        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log." suffix=".txt" pattern="common" resolveHosts="false"/>
        -->
      <!--/Host-->
  <Host name="one.com" appBase="webapps/one">
   <Context path="" docBase="" debug="0"/>
   <Alias>www.one.com</Alias>
  </Host>
  <Host name="two.com" appBase="webapps/two">
     <Context path="" docBase="" debug="0"/>
     <Alias>www.two.com</Alias>
  </Host>
    </Engine>
  </Service>
</Server>

Note, that I remarked Tomcat’s default “Host” element:

<!--Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true"
            xmlValidation="false" xmlNamespaceAware="false"-->

Remarking the default “Host” element is necessary. Otherwise Tomcat will simply load each web application twice: one for the default host definition and the second for the virtual host definition.

Installing Tomcat 6 on Windows 2008 server 64bit

Tomcat installation is actually composed of 2 parts:
  1. Installing Java Runtime Environment.
  2. Installing Tomcat.
In order to install Tomcat 6 on Windows 2008 server, you first have to download and install Java JRE for 64bit. The latest JRE can be easily downloaded from Sun’s website.
As it is for now, Tomcat doesn’t have 64bits version. In order to be able to run Tomcat 6 on Windows 2008 server 64bit, you will first have to download and install Tomcat 6 for 32bit and then download tomcat6.exe and tomcat6w.exe supporting 64bits from Apache svn repository. Replace the files located under Tomcat’s “bin” directory with these 2 files. These are actually the only 2 native files Tomcat is using to run as a Service. Running Tomcat as a service is necessary to be able to start the server, even if there is no user logged to the system.

Monday, December 7, 2009

Automatically focus first input field using JQuery

jQuery is a well know JavaScript framework. It has core libraries which contains many useful out of the box functions, that makes JavaScript code writing much better, easier, cleaner and cross browser. On top of jQuery there are many ready to use widgets and components that can be integrated into your web application in relatively short time. jQuery core js can be downloaded from jQuery main site, but it is much easier calling Google CDN (content delivery network) for getting jQuery. For example, if you want to use jQuery version 1.3.2 you can simply request this link:

http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js

or, as a JavaScript tag:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

Google has wide range of jQuery versions for your selection. It also offers additional frameworks and libraries as well (like MooTools, Yahoo UI and more). You can find more material about it in Google AJAX Libraries API.

Automatically focusing the first input field in web page that contains a form is a small but important feature in terms of user experience. Doing it in jQuery is an easy task:

<script type="text/javascript">
  $("input:text:visible:first").focus();
</script>

Of course, this code should be put after your form fields to function properly.

Note that the code is generic and doesn’t relate to any specific element id on the page.

Sunday, November 8, 2009

Automatically remove HTML remarks with Facelets

If you are working with Facelets, you can easily remove all you HTML remarks on the resulted page, by simply adding this directive in your web.xml:

<context-param>
  <param-name>facelets.SKIP_COMMENTS</param-name>
  <param-value>true</param-value>
</context-param>

Saturday, November 7, 2009

Using jQuery with JSF

JSF is using its own ids naming convention in order to prevent duplicate ids on the generated HTML page. JSF uses “:” as id separator. When you wish to use jQuery with JSF, this raises a problem: jQuery uses the “:” character in it’s core libraries as a selector of elements. Therefore, suppose we have a field named: someInput, which used in a form named: someForm, JSF will name the field in the resulted HTML as: someForm:someInput. In order to get the filed element in JQuery we should do:

var value = $('#someForm:someInput').val();
But, unfortunately jQuery treats the “:” character as a special character and therefore misunderstands our request. In order to override this problem, jQuery allows escaping the “:” character. escaping is done by putting “\\” before the “:”. In our example it will look like:
var value = $('#someForm\\:someInput').val();

Friday, November 6, 2009

Hibernate Paging with Previous and Next

Usually in web applications we have to show some table or list of data to the user. Over time this data is growing. Most of the times, the amount is data is not too big. Therefore, in many cases, it is enough loading all the data to memory, then showing it to the user. But, there are time in which the amount of data is too big. Therefore, it wouldn't be wise loading all the data on the server, simply in order to show just a part of it. Hibernate gives us a neat way of partially loading data by supplying 2 methods for the Query class:

  • setFirstResult: This method sets the first result we would like to see in our our list. Suppose we are getting all photos of a user, by doing something like: “select user.photos from User user”. The user is currently having 1000 pictures, but we want to show pictures starting from the 100th picture. We can use setFirstResult to accomplish that task.
  • setMaxResults: This method sets the maximum results that will be returned by the query. For example, if we would like to return only 100 photos for our user, we would do something like: query.setMaxResults(100).

As we can see we can use setFirstResult and setMaxResults to control which part of our list will be actually returned by the query. Of course, that Hibernate utilizes the specific dialect of the database server we are using to efficiently accomplish the task of fetching only a portion of the data.

We would like to use these 2 hibernate methods to construct paging effect in Hibernate. By saying “paging” we mean, that we would like to give Hibernate 2 parameters: in which page we are, and what is the size of our page. In return we would like to receive the items in that specific page. Accomplishing this task in Hibernate is quite easy and can be done by using simple math on the page and page size parameters. For example, if we would like Hibernate to return items in page 5 and in each page we would like to show 20 items, we can do:

query.setFirstResult(5 * 20).setMaxResults(20).list();

or in more general form:

query.setFirstResult(page * pageSize).setMaxResults(pageSize).list();

Showing the items for a specific page isn’t enough. We also would like to be able to tell if in a specific page there are more items. This will allow us to add “Next” button on out user interface. The trick to know if there is a next page, it to get one more additional item. If there is such item, we can know that there is a next page. This trick costs us in getting only one more item and therefore is pretty efficient in terms of performance. So, the general form for getting items shown above can be changed to:

query.setFirstResult(page * pageSize).setMaxResults(pageSize + 1).list();

Let’s take a look at a class named PagedResults, that gets an Hibernate query, page number, page size and in return gives us list of items according to the desired page and page size, and 2 more methods: isNextPage, isPreviousPage, that gives us indication if there are more pages or if we are at the first page:

package com.bashan.blog.persistence;
import org.hibernate.Query;
import java.util.List;
public class PagedResults {
  private List results;
  private int pageSize;
  private int page;
  public PagedResults(Query query, int page, int pageSize) {
    this.page = page;
    this.pageSize = pageSize;
    results = query.setFirstResult(page * pageSize).setMaxResults(pageSize + 1).list();
  }
  public boolean isNextPage() {
    return results.size() > pageSize;
  }
  public boolean isPreviousPage() {
    return page > 0;
  }
  public List getList() {
    return isNextPage() ?
        results.subList(0, pageSize) : results;
  }
}

Note that the method getList returns sub list of the original list. That is because the original list may return one additional item that we use only to know if there is a next page. We don’t want to show this item on our user interface.

Nicely truncating text with Java (by adding “…”)

Sometimes we have to show long text in place that is too small. Simply truncating text is not so nice, and it does not visually implies that there is more text after the truncation. We can use Java to easily truncate text nicely by adding “…” instead of the truncated part. We will construct 2 functions:

  • Truncate a string to a fixed maximum length and leave a request amount of characters from the end of the string. For example, if we have the text: “This is some long text test, This is some long text test, This is some long text test”, and we would like to truncate the text to be maximum size of 30 characters and leave 12 characters from the end of the string, the result would look like: “This is some lo...ng text test”. Note, that the “…” along with the string itself constructs no more than 30 characters.
  • The second function is a special case of the first function: we would like to truncate a string to a fixed maximum length, by leaving “…” at the end of the string. For example if we use the previous string, the result of truncating it will look like: “This is some long text test...”. Note, that again, the maximum length of string along with the “…” is no more than 30 characters.

Writing these 2 functions in Java is a very simple task that mainly takes advantage substring method:

package com.bashan.blog.string;
public class StringUtils {
  public static String truncateText(String str, int maxLen, int lenFromEnd) {
    int len;
    if (str != null && (len = str.length()) > maxLen) {
      return str.substring(0, maxLen - lenFromEnd - 3) + "..." +
          str.substring(len - lenFromEnd, len);
    }
    return str;
  }
  public static String truncateText(String str, int maxLen) {
    return truncateText(str, maxLen, 0);
  }
  public static void main(String[] args) {
    String str = "This is some long text test, This is some long text test, This is some long text test";
    System.out.println(truncateText(str, 30, 12));
    System.out.println(truncateText(str, 30));
  }
}

At the end we can see a small test program. The output for it is:

This is some lo...ng text test
This is some long text test...

Saturday, October 31, 2009

Date validation with Java

Even though there are many fancy calendar inputs on the internet, sometimes, the easiest way to let simple users to input date in web application is by using 3 drop downs: day, month and year. On the server side, we combine these 3 values to create a proper date instance. But, before converting these 3 values to date we need to make sure, the values create a valid date. There are few cases in which an invalid date can be inputted. For example, when a month with 30 days is selected along with day: 31.

Validating that the 3 values: day, month, year really constructs a proper date is an easy task in Java. But, the idea behind it, is not as trivial as it looks. The calendar class can create date instance from day, month and year, but it doesn’t make sure the values are in the range. For example, day with values 33 can be accepted without an exception being raised.

In order to make sure a date is valid we will do a small trick:

  • Construct a string date representation for the inputted values: day, month, year (we can choose any format).
  • Convert the string date to a java date instance by using a date formatter.
  • Convert the date back to a string again.
  • Check the original string we built against the converted date.

If both strings are equal, that means date is valid.

Here is the Java code that does the task:

package com.bashan.blog.date;
import org.apache.commons.lang.StringUtils;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.Format;
import java.text.ParseException;
public class DateUtil {
  public static boolean isDateValid(int day, int month, int year)
  {
    try
    {
      String date = StringUtils.leftPad(day + "", 2, "0") + "/" + StringUtils.leftPad(month + "", 2, "0") + "/" + year;
      String dateFormat = "dd/MM/yyyy";
      Date dateSimple = new SimpleDateFormat(dateFormat).parse(date);
      Format formatter = new SimpleDateFormat(dateFormat);
      return date.equals(formatter.format(dateSimple));
    }
    catch (ParseException e)
    {
      return false;
    }
  }
}

Note that this code uses StringUtils.leftPad method, which is part of Apache Commons Lang project.

Monday, October 12, 2009

Java Servlet that returns a transparent pixel

Advertising and web analytic services use many techniques and tricks in order to track user impressions and actions. One of the common ways of tracking users is by placing an image tag on a page. The image tag generates a request to some image and in addition to serving the image some statistics is being collected. This technique is used in order to reduce integration processes to a minimum. All needed to be done, is simply to place the image tag somewhere in the HTML web page, set some parameters if desired (passed by the url of the image), and that’s it. No need to worry from JavaScript not supported or Third party cookies being blocked.

An example for such a request can look like:

<img src="www.myservice.com/count?customerId=7 />

In this example, by placing the image tag in a web page, we are making a request to the server: www.myservice.co with the parameter: customerId=7, meaning the customer that sent the request is identified in our system as “7”.

Note, that we didn’t make any call to a real image. We made a request to a Java Servlet that generates for us a transparent image of one pixel. We want the image response to be as small a possible for 2 reasons:

  • The traffic from our server back to the client will be minimal. A reduction of traffic yields a better performance as well as reduced server traffic costs.
  • We want the image to be a small as possible, so it won’t be noticed and effect the layout of the page. For this reason we also return a transparent pixel.

Let see how we dynamically create a transparent image of one pixel and serve it back to the client:

package com.bashan.blog.servlet;
import javax.imageio.ImageIO;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
public class PixelServlet extends HttpServlet {
  private BufferedImage pixel;
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
    pixel = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
    pixel.setRGB(0, 0, (0xFF));
  }
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // Here we can do whatever logic we want   
    response.setContentType("image/png");
    OutputStream os = response.getOutputStream();
    ImageIO.write(pixel, "png", os);
  }
}

Note that when the Servlet is being initialized we create the pixel and make it transparent. On the “doGet” method we write the pixel to the outputStream of the response.

Of course, instead of serving the pixel this way, we can simply put a transparent image of a pixel in the root of our web server, and make a redirection to this pixel, but usually tracking pixels are known to be requested by lots of clients simultaneously, so in terms of performance, it is better to directly write the pixel to the stream.

Don't forget to declare and map this Servlet in your web.xml to make it usable...