Contents:
Using JSF 1.2 with Facelets on Google App Engine for Java
On April Google announced the support for Java on Google App Engine. I became aware of this last week and rushed to create an account and check it out. Since this is an ‘early look’ release, I had to wait until the guys at Google grant me the rights to use the service. Meanwhile I downloaded the SDK and started building a test application to check if the frameworks I mostly use are supported. My minimum requirements are JSF 1.2 with Facelets for templating (I also use ICEfaces but I can live without them). The results where positive while using the SDK on my computer but when I’ve uploaded the application on App Engine (my account was activated two days ago) I received a nasty error thrown during the initialization phase of JSF.
After hours of searching and debugging I finally managed to get it up and running. Now I’m going to list the steps involved. The most interesting and insightful resource I found is this post, which describes how to setup JSF on App Engine as a step in configuring JBoss Seam.
As the post author states, you’ll have to enable sessions in appengine-web.xml, then configure JSF as usually, then set it up to use JBoss’s EL implementation and finally use those patched classes in order to avoid API calls that are restricted by the security policy of App Engine. I only used the patched classes under ‘jboss-el’ and ‘jsf_mojarra’ since I don’t use Seam.
After this I added Facelets and gone through the necessary configuration steps, built the application and tried to run it on App Engine.
Problems Occurred (yes, of course, Murphy’s Law dictates it):
1) FacesServlet was not properly initialized. This is probably because App Engine does not initialize servlets at startup, instead initialization is postponed until the first request. As a result an IllegalStateException was thrown. To resolve the issue I had to add the following to web.xml:
<listener>
<listener-class>
com.sun.faces.config.ConfigureListener
</listener-class>
</listener>
Error Message:
javax.servlet.ServletException: java.lang.IllegalStateException: Application was not properly initialized at startup, could not find Factory: javax.faces.context.FacesContextFactory
2) An error was thrown during FacesServlet initialization due to the use of a restricted class. After examining the stack trace I realized that JSF was trying to perform some XML validation and failed throwing a NoClassDefFoundError. I had no other option but to deactivate XML validation by setting the following at web.xml:
<context-param>
<param-name>com.sun.faces.validateXml</param-name>
<param-value>false</param-value>
</context-param>
Error Message:
java.lang.NoClassDefFoundError: com.sun.org.apache.xalan.internal.xsltc.runtime.BasisLibrary is a restricted class. Please see the Google App Engine developer’s guide for more details.
3) EL API classes were missing, had to include the EL API class library to the project.
Error Message:
java.lang.ClassNotFoundException: javax.el.CompositeELResolver
One last upload of the application after all the above tweaks and voilĂ ! The homepage loaded without any errors! The fact is that I didn’t have time to perform any further tests and for sure I cannot tell if all the features of JSF and Facelets will work normally. I’m waiting for your feedback on this. Good Luck!

Start a native application from your Java code
Starting a native application from your Java code is as simple as the following command:
Runtime.getRuntime().exec("notepad.exe");
Of course, this adds platform dependency to your code, and if you want your application to be portable it’s a good practice to avoid using the exec() method. But if it is necessary to initiate a native application for any reason, the way is easy and pretty straight-forward. The fact is that there’s always a case where executing a command of the operating system is the only way to achieve specific functionality.
In this case, independence can be approached if the command to be executed exist(with common or different syntax) in various operating systems. The first step is to find out the syntax of the command for every OS. Then within the code, you can use System.getProperty(”os.name”) to determine the OS that is being to host your Java application and finally use this information to execute the command using the corresponding syntax.
There is one more useful feature of the exec() method: it’s return value is an instance of the Process class, which can be used to get access to the actual process of the application initiated. Check out the javadoc of the Process class to find out more.

How to use log4j logging API
Logging is an important and pretty useful mechanism for every application. It can help developers to debug and improve their code or test it’s functionality. Apache has made a great work in this field with it’s tool named log4j. You can find more information about it here.
In this post I will provide a quick guide to help you get up and started with log4j. But fist of all you’ll have to download the latest version. Once you do, follow the instructions below:
1. Add log4j’s jar(log4j-x.x.xx.jar where x.x.xx is the version of the release you’ve downloaded) file to your application’s classpath.
2. Create a file named “log4j.properties” and place it in the default package of your source code(the root folder where all your code resides). Copy the following lines in it:
# Log levels
# Uncomment the following line to enable full loggin for every class
#log4j.rootLogger=trace, stdout, R
log4j.logger.gr.xfrag=trace, stdout, R
# Console appender configuration
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
# Rolling File Appender
log4j.appender.R=org.apache.log4j.RollingFileAppender
# Path and file name to store the log file.
log4j.appender.R.File=./logs/applog.log
log4j.appender.R.MaxFileSize=500KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
# Rolling File Appender layout
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d - %c - %p - %m%n
Here is a quick explanation of what the above properties do:
“log4j.logger.xxx” controls the loggers, where xxx is the package for witch you want to set log levels.
The line
log4j.logger.foo.bar=trace, stdout, R
means that you want every class under the foo.bar package to have a logging level of trace, and output the log to the standard output(the console) using a Console Appender named stdout and to a file using a Rolling File Appender named R.
After that you define the appenders I mentioned earlier and set their properties.
The lines
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) – %m%n
define the ConsoleAppender named stdout, set it’s layout to PatternLayout and then assign a pattern for the output.
Following the same procedure the RollingFileAppender is defined, setting some additional properties: the file name of the log, the size of the log and the number of backup files to keep.
3. The third and final step is about the code you’ll have to use. There’s not much to be said, this is the easiest part. Take a look of the class below:
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
public class Main {
private static Logger logger = Logger.getLogger(Main.class);
public static void main(String[] args) {
long time = System.currentTimeMillis();
logger.info("main method called..");
logger.info("another informative message");
logger.warn("This one is a warning!");
logger.log(Level.TRACE,
"And a trace message using log() method.");
long logTime = System.currentTimeMillis() - time;
logger.debug("Time taken to log the previous messages: "
+ logTime + " msecs");
// Exception logging example:
try{
String subs = "hello".substring(6);
}catch (Exception e){
logger.error("Error in main() method:", e);
}
}
}
First you have to import org.apache.log4j.Logger and org.apache.log4j.Level(if you want to use the log() method).
Then instantiate a static Logger object using the static method getLogger() and provide your class as an argument.
To log messages through your class, you use the logging methods of the created Logger object. There are two ways to log messages:
Directly, using the methods trace(), debug(), info(), warn(), error() and fatal(), providing the message as an argument.
Using the log() method, providing the level of the message from the Level class and the message to log as arguments.
According to the configuration you provide in the properties file, a message will be logged – or not. For example, if you set the level to WARN, all messages of level WARN, ERROR and FATAL will be logged and everything else will be omitted. In other words, the hierarchy is:
TRACE < DEBUG < INFO < WARN < ERROR < FATAL.
Now, check out how the appenders output the messages according to their pattern. Here’s what you get at the console when you run the Main class:
INFO [main] (Main.java:12) - main method called..
INFO [main] (Main.java:13) - another informative message
WARN [main] (Main.java:14) - This one is a warning!
TRACE [main] (Main.java:15) - And a trace message using log() method.
DEBUG [main] (Main.java:19) - Time taken to log the previous messages: 0 msecs
ERROR [main] (Main.java:26) - Error in main() method:
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1938)
at java.lang.String.substring(String.java:1905)
at gr.xfrag.loggingexample.Main.main(Main.java:24)
And the same in the log file:
2008-01-10 15:39:46,724 - gr.xfrag.loggingexample.Main - INFO - main method called..
2008-01-10 15:39:46,724 - gr.xfrag.loggingexample.Main - INFO - another informative message
2008-01-10 15:39:46,724 - gr.xfrag.loggingexample.Main - WARN - This one is a warning!
2008-01-10 15:39:46,724 - gr.xfrag.loggingexample.Main - TRACE - And a trace message using log() method.
2008-01-10 15:39:46,724 - gr.xfrag.loggingexample.Main - DEBUG - Time taken to log the previous messages: 0 msecs
2008-01-10 15:39:46,724 - gr.xfrag.loggingexample.Main - ERROR - Error in main() method:
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1938)
at java.lang.String.substring(String.java:1905)
at gr.xfrag.loggingexample.Main.main(Main.java:24)
Besides the deferences of the formating, notice how long it takes to log those messages – zero milliseconds on my machine. If you ask me, I’ll say that speed is the most impressive feature of log4j..
I hope the above information will help you get started with log4j and logging in general. You can learn more by reading the manual located at log4j’s home page: Log4j Manual
I also uploaded the example code as a NetBeans 6.0 project. Use the following link to download the zip archive:
Log4j Example NetBeans Project

Mapping FacesServlet to URLs without extensions
Over the past few months, I’ve been working on JavaServer Faces, making an effort to learn the framework and ultimately use it to create a web application. Currently I’m still in the learning process and the more I’m involved with JSF, the more I’m becoming a fan of it. The last challenge I’ve faced is not directly related with JSF, but has to do with Servlets in general.
When you declare a Servlet in your web application’s configuration file (that’s web.xml), you also have to declare a mapping for the Servlet to make the web container forward the requests to the Servlet. There’s two types of mappings you can choose from: extension mapping and prefix mapping. Extension mapping will be of the form “*.extension” and path prefix mapping will be “/path/*”. Here’s an example:
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
I prefer extension mapping for JSF, because this way I’m not restricted to have a certain path for my JSF-enabled pages. The challenge I was talking about previously, has to do with my requirement to go beyond the default mapping mechanism. I want to be able to invoke JSF pages from any path, without using an extension. For example, say there is a JSF page displaying user account information, that has to be invoked using the URL “/account/view.faces”. Wouldn’t it be nicer to have “/account/view” instead?
After a small research, I’ve found out that a Filter can do the job. All that have to be done is a check of the requested URL pattern and if it match the mapping criteria, forward the request to the FacesServlet. Here is how I’ve done it:
public class MappingFilter extends HttpServlet implements Filter {
...
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) request;
// Get the requested URI
String uri = httpReq.getRequestURI();
try{
// Check if the URI matches mapping creteria.
boolean matches = uri.matches(".*/[\w]+");
if(matches){
ServletContext context = filterConfig.getServletContext();
// Strip context path from the requested URI
String path = context.getContextPath();
if (uri.startsWith(path)){
uri = uri.substring(path.length());
}
// Check if there is actually a file to handle the forward.
URL url = context.getResource(uri+".jsp");
if(url != null){
// Generate the forward URI
String forwardURI = uri + facesExtension;
// Get the request dispatcher
RequestDispatcher rd =
context.getRequestDispatcher(forwardURI);
if(rd != null){
// Forward the request to FacesServlet
rd.forward(request, response);
return;
}
}
}
// We are not interested for this request, pass it to the FilterChain.
chain.doFilter(request, response);
} catch (ServletException sx) {
filterConfig.getServletContext().log(sx.getMessage());
} catch (IOException iox) {
filterConfig.getServletContext().log(iox.getMessage());
}
}
...
}
This filter works just fine and can be used to map extension-less requests to any Servlet. In other words, you can use it to map requests for plain JSP pages also. But when it comes to JSF, there’s a problem: JSF will write action URLs to the forms according to the servlet-mapping parameter that you have set in your web.xml configuration file. So, even if you request using the extension-less URL, after submitting the form your web browser’s bar will have the original location (the one with the extension) -and that’s not nice. After making a huge research this time, struggling for hours to find something in javadocs and in search engines, I’ve managed to find the class responsible for the creation of the action URL. It’s name is ViewHandler and the method is getActionURL(). I’ve also found that you can easily make a custom ViewHandler that sits on top of the one the framework is using and change only part of it’s functionality.
All you have to do is to create a class that extends javax.faces.application.ViewHandler and specify a constructor that takes a parameter of the same type as an argument. Then you declare it in faces-config.xml like this:
<application>
<view-handler>gr.xfrag.faces.mapping.MappingViewHandler</view-handler>
</application>
The JSF framework will find your declaration, and will call your implementation’s constructor, passing it the default ViewHandler used by the implementation you’re using(if you use JSF-RI it will pass com.sun.faces.application.ViewHandlerImpl). You can use this class to delegate every method you don’t want to customize from your custom ViewHandler to the default one. Using this technique, I’ve been able to strip the extension from the action URLs like this:
This way you can have flawless extension-less mapping for JavaServer Faces. If you want to disable requests for URLs having an extension completely (they will still work even if you use my classes), you can add a few more lines of code to the
Home