Monday, June 29, 2009

Configuring JBOSS to support UTF-8 characters in the URL

The problem I have experienced this week. When I have chinese characters as part of the URL, the characters show up as garbage in the page. I mean request.getParameter("chineseCharacter") returns garbage characters. This problem happened in JBOSS 4.2.3 GA with Apache 2.0(mod_jk).

Fortunately the solution is simple:

Edit JBOSS_HOME/server/${SERVER_NAME}/deploy/jboss-web.deployer/server.xml

Add URIEnconding="UTF-8" to the HTTP connector and AJP connector:


<Connector port="8080" address="${jboss.bind.address}"
maxThreads="250" maxHttpHeaderSize="8192"
emptySessionPath="true" protocol="HTTP/1.1"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true" URIEncoding="UTF-8"/>

<!-- Define an AJP 1.3 Connector on port 8009 -->
<Connector port="8009" address="${jboss.bind.address}" protocol="AJP/1.3"
emptySessionPath="true" enableLookups="false" redirectPort="8443" URIEncoding="UTF-8"/>

Now restart your server and you should have no more problems with having non-latin characters in the URL.

Thursday, June 25, 2009

Adding an event listener function with arguments using Actionscript

This might come handy whenever you can't use directly mxml and you need to add an event listener function that needs one or more arguments.


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="myInitialize()">
<mx:Script>
<![CDATA[
import mx.controls.Alert;

private function myFunction(arg:String):void {
mx.controls.Alert.show("Received call with argument=" + arg);
}

private function myInitialize():void {
myButton.addEventListener(MouseEvent.CLICK, function(event:MouseEvent):void{
var someArg:String="an_argument";
myFunction(someArg);
});
}
]]>
</mx:Script>


<mx:Button id="myButton" label="Click me!"/>
</mx:Application>


See this code in action here

Wednesday, June 24, 2009

Adobe Flex 3 UI Components Lifecycle

In adobe flex 3 there are certain events that are called when a component is created.
These events are raised in the following order:

1) preInitialize: This event is raised when the component has just been created but none of the child components exist.

2) initialize: This event is raised after the component and all its children have been created but before any dimensions have been calculated.

3) creationComplete: This even is dispatched after all the component and its children have been created and after all the layout calculations have been performed.

4) applicationComplete: Dispatched after all the components of an application have been successfully created

Events 1) to 3) are dispatched in the order mentioned above for all visible components.
Note however that for components that are not visible on the screen by default, none of these events will be raised. This is because depending on the creation policy the hidden components might not exist yet.
For example in a TabNavigator only the components that are inside the default tab are created because they are visible. If you do change to another non-visible tab then Flex creates the components one by one. In that case the events mentioned above are raised.

We have created a simple example to demonstrate this. The DataGrid shows you a list of the events that have been raised during the lifecycle of the main application window. If you change to the second tab you will see additional entries in the list due to the creation of a Label UI component.


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" preinitialize="preInitialise()" initialize="initialise()" applicationComplete="applicationComplete()" creationComplete="creationComplete()" viewSourceURL="srcview/index.html">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;

[Bindable]
private var eventsCalled:ArrayCollection=new ArrayCollection();

public function preInitialise():void {
eventsCalled.addItem({label:"preInitialise called",event:"preInitialise"});
}

public function initialise():void {
eventsCalled.addItem({label:"initialise called",event:"initialise"});
}

public function creationComplete():void {
eventsCalled.addItem({label:"creation complete called",event:"creationComplete"});
}


public function applicationComplete():void {
eventsCalled.addItem("applicationComplete called");
}

]]>
</mx:Script>
<mx:TabNavigator width="400" height="400">
<mx:Canvas label="tab1">
<mx:DataGrid id="datagrid" dataProvider="{eventsCalled}" top="10" left="10" width="300" />
</mx:Canvas>
<mx:Canvas label="tab2">
<mx:Label text="This label is created only when it is displayed" creationComplete="creationComplete();" preinitialize="preInitialise();" initialize="initialise();" />
</mx:Canvas>

</mx:TabNavigator>
</mx:Application>


To see this example in action click: here

You can change this behavior by setting the creationPolicy attribute, for example in the application mxml node. This attribute is only valid for containers.

There are 4 possible values for this attribute:

1) creationPolicy="auto" - the container delays creating some or all of its descendants until they are needed. This is known as deferred instantiation

2) creationPolicy="all" - the container immediately creates all its descendants even if they are not selected.

3) creationPolicy="queued" - all components inside a container are added to a creation queue. The application waits until all children of a container are created before moving to the next container.

4. creationPolicy="none" - all components inside a container are never created. Whoever decides to go with this strategy needs to manually create all items inside a container.

For example to change the behavior seen above we could set the creationPolicy="all":


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationPolicy="all" preinitialize="preInitialise()" initialize="initialise()" applicationComplete="applicationComplete()" creationComplete="creationComplete()" viewSourceURL="srcview/index.html">
...
</mx:Application>

Sunday, June 21, 2009

SEO Urls/Hierarchical Actions with struts 2.1

I have added a working struts 2.1 project that gives you a working example on how to create SEO optimised urls for struts 2.1. You can find the previous post here.

Monday, June 15, 2009

Minifying CSS and JS with Yahoo YUI Compressor

In my previous blog post I explained how to use Ant to concatenate javascript and css files in a way to minimize the number of http requests.
Another recommendation by yahoofor building high performance websites is to minify JS and CSS files. The reasoning is that the smaller the size of the javascript/css, the less time it takes for them to be interpreted.

Yahoo provides a great utility - yahoo yui compressor that minifies both javascript and css.

We can therefore improve our build script and add the following task:


<!-- this compresses all the css and js in the static folder -->
<target name="js.minify">
<property
name="yui-compressor.jar"
location="lib/yuicompressor-2.4.2.jar" />
<property
name="yui-compressor-ant-task.jar"
location="lib/yui-compressor-ant-task-0.3.jar" />

<path id="task.classpath">
<pathelement location="${yui-compressor.jar}" />
<pathelement location="${yui-compressor-ant-task.jar}" />
</path>

<taskdef
name="yui-compressor"
classname="net.noha.tools.ant.yuicompressor.tasks.YuiCompressorTask">

<classpath refid="task.classpath"/>
</taskdef>

<yui-compressor warn="false" charset="UTF-8" jsSuffix="-min.js" cssSuffix="-min.css" fromdir="${build.dir}/static" todir="${build.dir}/static">
<include name="**/*.js" />
<include name="**/*.css" />
</yui-compressor>


<move todir="${build.dir}/static" includeemptydirs="false">
<fileset dir="${build.dir}/static">
<include name="**/*-min.css"/>
</fileset>
<mapper type="glob" from="*-min.css" to="*.css"/>
</move>
<move todir="${build.dir}/static" includeemptydirs="false">
<fileset dir="${build.dir}/static">
<include name="**/*-min.js"/>
</fileset>
<mapper type="glob" from="*-min.js" to="*.js"/>
</move>

</target>


First we copy all the javascript and css files to the build/static folder and then we use yahoo compressor to minify all the files in this directory.

Click here to download an example.

Sunday, June 14, 2009

Minimizing number of http requests by concatenating all the CSS and Javascript files

If you have installed yslow in your browser you will know all about yahoo's high performance rules for a website. One of the most important rules is to minimize the number of http requests. There are several ways of doing that. I will cover one of them in this post - minimizing the number of http requests by concatenating all the javascript files and css files into two big files.

Apache Ant makes the task of concatenating files together extremely easy by using concat.

<concat destfile="${build.dir}/concatenated.js">
<filelist dir="${src.dir}/js"
files="one.js, two.js"/>
</concat>


This is a simple solution but I chose not to use it for the following reasons:

1. I don't always want every single javascript/css to be included for all pages.
You could create multiple concatenated files with different combinations but that would be too messy.

2. We are creating a dependency between the jsps and the ant build script. Do you really want to do that?

3. Javascript, css can be notoriously difficult to debug, so for development purposes
it is useful not to do any concatenation.

Ant has a neat feature that allows to do string replacement on any file by using a filterset.

<copy file="${build.dir}/version.txt" toFile="${dist.dir}/version.txt">
<filterset>
<filter token="DATE" value="whatever"/>
</filterset>
</copy>

You can specify the string that you want to be replaced at build time by surrounding it with ampersands. So in the template jsps instead of including javascripts/css in the normal way, I did the following:

@IncludeCSS css/file1.css css/file2.css ...@
...
@IncludeJS js/jquery.js js/thickbox.js js/vmSlider.js js/blockUI.js@


Then I created the following ant task:

<ExtendedFileTransform concatenate="true" propertiesfile="${build.dir}/static.mapping.properties" >
<jspfileset refid="jspFileset">
</jspfileset>
<staticfileset dir="${static_content.dir}">
<include name="**/*.js" />
<include name="**/*.css" />
<include name="**/*.png" />
<include name="**/*.jpg" />
<include name="**/*.jpeg" />
<include name="**/*.gif" />
<include name="**/*.PNG" />
<include name="**/*.JPG" />
<include name="**/*.GIF" />
</staticfileset>
</ExtendedFileTransform>
ExtendedFileTransform is a custom task I created, based on Julien Lecombte's File Transform.
This custom task inspects all the jsps and searches for javascript(IncludeJS) and css includes(IncludeCSS). If concatenated="true" we concatenate the files specified within the IncludeXXX directory and we replace it with a valid html javascript/css include to the generated files. If concatenated="false", i.e. for development, there is no concatenation and the IncludeXXX directory is replaced with an include for each javascript/css file.

The full ant target that you could use for production looks like this:


<target name="-copy.static.files-prod">
<taskdef name="ExtendedFileTransform" classname="uk.co.simpletech.ant.ExtendedFileTransform" classpath="${build.dir}/classes" />

<mkdir dir="${build.dir}/staticpre" />

<!-- we copy all jsp files to a temporary location -->
<copy todir="${build.dir}/jsppre">
<fileset dir="jsp" includes="**/*" />
</copy>

<fileset dir="${build.dir}/jsppre" id="jspFileset">
<include name="**/*.jsp" />
</fileset>
<!-- we concatenate the files together -->

<ExtendedFileTransform concatenate="true">
<jspfileset refid="jspFileset">
</jspfileset>
<staticfileset dir="${build.dir}/static">
<include name="**/*.js" />
<include name="**/*.css" />
</staticfileset>
</ExtendedFileTransform>



<delete dir="${build.dir}/jsppre" />=
</target>

Here is an example project where you can see the css/js concatenation in action.

Case insensitive search in hibernate

It is very simple to do case insensitive search in hibernate.
Here is an example HQL query:


Query q = this.entityManager.createQuery("SELECT * FROM User u where lower(u.firstName)=:firstName");
q.setParameter("firstName", firstName.toLowerCase());


In this case lower() will convert the firstName property to lower case allowing you to do case insensitive search.

Saturday, June 13, 2009

Creating hierarchical actions in struts 2.1

Struts 2.1 doesn't directly support hierarchical actions. Nonetheless I still was able to implement them at visualmandarin.
Notice how the podcasts and exercises urls are all organized into folders and even the lesson title is present in the url: Lesson - Can I have a menu please?

If you are interested in SEO optimized urls for your website this kind of feature is a MUST. But how to do it struts 2.1? In short the steps you need to follow are:

Step 1

If you are running on struts 2, migrate to struts 2.1

Step 2

Make sure you are using the convention plugin

Step 3

Ensure that all your actions have an explicit namespace. If you don't you might find that those actions are being called when they shouldn't.

Step 4

Create a wildcard action in the namespace that you want to be hierarchical. In my case I have created one in namespace /lessons:


<action name="*" namespace="/lessons" method="execute" class="lessonsLocator">
<result name="lister"></result>
<result name="ResourceNotFoundException" type="chain">404</result>
</action>



Your lessons locator action should inspect the uri to determine which resource to display. In my case I was dealing with lessons but you could be dealing with categories and products or anything else. It shouldn't make any difference.

Step 5

Extend org.struts2.impl.StrutsActionProxy and override the following prepare() method:

@Override
protected void prepare() {
String profileKey = "create DefaultActionProxy: ";
try {
UtilTimerStack.push(profileKey);
// we backtrack the namespace until we find an action that matches
this.findActionByBacktracking();

if (config == null && unknownHandler != null) {
config = unknownHandler.handleUnknownAction(namespace, actionName);
}
if (config == null) {
String message;

if ((namespace != null) && (namespace.trim().length() > 0)) {
message = LocalizedTextUtil.findDefaultText(XWorkMessages.MISSING_PACKAGE_ACTION_EXCEPTION, Locale.getDefault(), new String[]{
namespace, actionName
});
} else {
message = LocalizedTextUtil.findDefaultText(XWorkMessages.MISSING_ACTION_EXCEPTION, Locale.getDefault(), new String[]{
actionName
});
}
throw new ConfigurationException(message);
}

resolveMethod();

if (!config.isAllowedMethod(method)) {
throw new ConfigurationException("Invalid method: "+method+" for action "+actionName);
}

invocation.init(this);

} finally {
UtilTimerStack.pop(profileKey);
}
}

/**
* Returns a list of all possible namespaces. The one with biggest length
* is top of the list up to /xxx... bottom of a list. Note that we don't backtrack until
* the empty namespace
*
* @param namespace
* @return
*/
private String [] getAllPossibleNamespaces(String namespace) {
List<String> namespaces = new ArrayList<String>();
// e.g. /lessons/hsk/.../1 ->
String [] tokens = namespace.split("/");
tokens=removeEmptyStrings(tokens);
if (tokens != null && tokens.length >= 0) {
for (int i=0; i< tokens.length; i ++) {
String gnamespace="";
for (int j=0;j<tokens.length- i;j++) {
gnamespace += "/" + tokens[j] ;
}
namespaces.add(gnamespace);
}
}
return namespaces.toArray(new String[0]);
}

private String [] removeEmptyStrings(String [] tokens) {
List<String> result = new ArrayList();
for (String token: tokens) {
if (token == null || token.equals("")) {

}
else {
result.add(token);
}
}
return result.toArray(new String[0]);
}

/**
* Searches for the given action in one or more namespaces
*
*/
private void findActionByBacktracking() {
if (namespace != null && !namespace.equals("") && !namespace.equals("/")) {
String [] namespaces =this.getAllPossibleNamespaces(namespace);

for (String namespace: namespaces) {

config = configuration.getRuntimeConfiguration().getActionConfig(namespace, actionName);

if (config != null ) break;
}

}
else {
config = configuration.getRuntimeConfiguration().getActionConfig(namespace, actionName);
}

}



Step 6

Extend org.apache.struts2.impl.StrutsActionProxyFactory.

My implementation as an example:

public class HierarchicalActionProxyFactory extends DefaultActionProxyFactory {
@Override
public ActionProxy createActionProxy(ActionInvocation inv, String namespace, String actionName, String methodName, boolean executeResult, boolean cleanupContext) {

HierarchicalActionProxy proxy = new HierarchicalActionProxy(inv, namespace, actionName, methodName, executeResult, cleanupContext);
container.inject(proxy);
proxy.prepare();
return proxy;
}
}


Step 7

Finally the last step: override the property struts.actionProxyFactory
in struts.properties and point to your implementation of the proxy factory.

My implementation was:

struts.actionProxyFactory=com.visualmandarin.web.config.HierarchicalActionProxyFactory


If you have followed these steps correctly you should be able to have the same kind of urls that I have in visualmandarin.com website. If there's something that you don't understand don't hesitate to ask!

You can find a working example here. This war file was tested in jboss 4.2.3 but should work in any compliant application server.

What you need to get this example working:

  • Add the struts 2 library files to the lib directory

  • Add the convention plugin jar file to the lib directory

  • Specify the correct path to your application server

Once you build the war file and deploy it, you can access the example at http://localhost/example3 or http://localhost:8080/example3
 
Software