Recently I discovered Tomcat 7 supports websockets, I looked at the support and found it quite easy to use.
I have created a very simple websocket servlet that echoes the input from the user, first of all you need to create a class that extends from WebSocketServlet, then, for every subprotocol you want to handle, you need to create a subclass of the abstract MessageInbound. There you may choose to answer to text or binary messages, here is the source:
Now we can connect to the websocket from our javascript client code:
And as simple as that we have our web sockets working for our java application deployed on Tomcat 7.
This blog is mainly dedicated to show to the world what I think it's interesting to Java development itself.
Showing posts with label Front End. Show all posts
Showing posts with label Front End. Show all posts
Tuesday, June 19, 2012
Sunday, May 20, 2012
Wicket 1.5 + Spring Framework + Hibernate + jDTO Binder Sample Application
In this post I'll go through a sample project I've created to demonstrate jDTO Binder in action with some of the most popular frameworks on the Java world. The sample project is publicly available on GitHub.
To get the project running without too much fuss, then just checkout the project, open it on netbeans 7.1.2 and hit run :)
If you're on linux or mac os X then you can do something like this:
After that you may point your browser to http://localhost:8080/jdto-wicket-demo/ and that's it, you should see something like this:
The parameters mean in order, the horizontal distance, the vertical distance the blur distance and the shadow color.
Also you can see that the box is kind of rotated let's say 8 degrees to the left? Normally that would have been defined by using the transform property, but it seems that is still not that supported in all browsers, so I have added three rules to support webkit, mozilla and internet explorer 9:
Finally, to include some web fonts, some import statements must be added:
That enabled me to use the "Averia Libre" and "Oxygen" fonts on my styles.
Normally one would have had that css resource included on the java code but this wicket magic makes it more intuitive and consistent.
Another use of the tag is to link between pages, as I show in the following example:
In this case, I have a ViewOrdersPage.java file and by creating the link this way, wicket takes care of pointing the href to the right place without adding extra Java code.
With the use of CompoundPropertyModel things are really easy. I've added a behavior that submits the form data every time the field losses focus, this prevents unwanted data erasing on the client side. (Also I could have designed my page a little better hehe).
As you can see, the database connection pool has the url "jdbc:h2:mem:pizza" and that is all what it takes to tell H2 that you don't want to persist anything.
Finally, I've used a singleton bean to load the sample data when the application starts, this bean loads the list of available products.
One of the beauties of Spring is that you can use package-scoped classes as beans so you don't expose them to the team developers (and they don't feel tempted to use them).
Since this bean will be executed on startup time we will need a brand new transaction, so I've set the propagation attribute to "requires new".
That would be all for now, please feel free to make comments on the post and I hope you find it useful for starting a new project with this great technologies.
To get the project running without too much fuss, then just checkout the project, open it on netbeans 7.1.2 and hit run :)
If you're on linux or mac os X then you can do something like this:
$ git clone git://github.com/jDTOBinder/jdto-sample-projects.git $ cd jdto-sample-projects/jdto-wicket-demo/ $ mvn clean tomcat:run
After that you may point your browser to http://localhost:8080/jdto-wicket-demo/ and that's it, you should see something like this:
The CSS3 Highlights:
The styling is pretty standard styling what can be kind of uncommon is the menu box which is rotated and it has a little shadow, also some google web fonts are being used, let's go with the easiest first, the shadow:
box-shadow: 6px 6px 5px #888;
The parameters mean in order, the horizontal distance, the vertical distance the blur distance and the shadow color.
Also you can see that the box is kind of rotated let's say 8 degrees to the left? Normally that would have been defined by using the transform property, but it seems that is still not that supported in all browsers, so I have added three rules to support webkit, mozilla and internet explorer 9:
-webkit-transform:rotate(-8deg); -moz-transform:rotate(-8deg); -ms-transform: rotate(-8deg);
Finally, to include some web fonts, some import statements must be added:
/* import the google web font */ @import url(http://fonts.googleapis.com/css?family=Averia+Libre:700); @import url(http://fonts.googleapis.com/css?family=Oxygen);
That enabled me to use the "Averia Libre" and "Oxygen" fonts on my styles.
The Wicket Highlights
Apache Wicket is a really nice web framework that you can use to build everything in Java, from websites to web applications, there are some things that may be uncommon for some developers, I've used the wicket:link tag to include css resources packaged on the classpath:<head> <title>jDTO Binder Pizza Orders!</title> <wicket:link> <link rel="stylesheet" type="text/css" href="jdtopizzas.css" /> </wicket:link> </head>
Normally one would have had that css resource included on the java code but this wicket magic makes it more intuitive and consistent.
Another use of the tag is to link between pages, as I show in the following example:
<p>Take a look at the <wicket:link><a href="ViewOrdersPage.html">orders you have already created</a></wicket:link>.</p>
In this case, I have a ViewOrdersPage.java file and by creating the link this way, wicket takes care of pointing the href to the right place without adding extra Java code.
DTOs as the Wicket Models
Wicket extensively uses "intermediate" objects to act as the model of it components this is where DTOs come in handy, since you can modify the data they carry without affecting the data on the database, they are perfect for using them as the components model. The following code shows how you bind a wicket form with the "form" that takes the service to create a new pizza order:PizzaOrderForm form = new PizzaOrderForm(); form.setPizzas(new ArrayList<PizzaDTO>()); //create the order form. orderForm = new Form<PizzaOrderForm>( "orderForm", new CompoundPropertyModel<PizzaOrderForm>(form)); //for the case you want to add pizzas and you have already filled the form elements. //this is only necessary because I left out the menu list from the form. orderForm.add(new TextField("customerName").add(new BlurAjaxFormSubmitBehavior())); orderForm.add(new TextField("customerPhone").add(new BlurAjaxFormSubmitBehavior())); orderForm.add(new TextField("customerAddress").add(new BlurAjaxFormSubmitBehavior()));
With the use of CompoundPropertyModel things are really easy. I've added a behavior that submits the form data every time the field losses focus, this prevents unwanted data erasing on the client side. (Also I could have designed my page a little better hehe).
Spring and Hibernate Highlights
As this is a sample application but is intended to show real-life stuff, it uses spring framework and hibernate, but if you had to install and configure a database server to test the application, you probably wouldn't test it, so here is how I've used the H2 embedded database engine to use just your computers memory a little bit more:<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="org.h2.Driver"/> <property name="url" value="jdbc:h2:mem:pizza"/> </bean>
As you can see, the database connection pool has the url "jdbc:h2:mem:pizza" and that is all what it takes to tell H2 that you don't want to persist anything.
Finally, I've used a singleton bean to load the sample data when the application starts, this bean loads the list of available products.
<!-- initial data loader bean --> <bean id="initialDataLoader" class="org.jdto.demo.InitialDataLoader" />
class InitialDataLoader { private static final Logger logger = LoggerFactory.getLogger(InitialDataLoader.class); @Autowired private HibernateTemplate template; @PostConstruct @Transactional(propagation= Propagation.REQUIRES_NEW) private void init() { createPizzas(); } private void createPizzas() { logger.info("Creating initial set of pizzas!"); Pizza pepperoni = new Pizza("Pepperoni Pizza", 4, 8.50); Pizza mozzarella = new Pizza("Mozzarella Pizza", 3, 7.50); Pizza special = new Pizza("Special Ham Pizza", 5, 10.0); Pizza onion = new Pizza("Onion Pizza", 4, 9.0); Pizza anchovy = new Pizza("Anchovy Pizza", 2, 7.95); template.save(pepperoni); template.save(mozzarella); template.save(special); template.save(onion); template.save(anchovy); } }
One of the beauties of Spring is that you can use package-scoped classes as beans so you don't expose them to the team developers (and they don't feel tempted to use them).
Since this bean will be executed on startup time we will need a brand new transaction, so I've set the propagation attribute to "requires new".
jDTO Binder Highlights
In this application, jDTO Binder takes care of copying data between domain objects and DTO objects, how it's being used is described on the project's README file.That would be all for now, please feel free to make comments on the post and I hope you find it useful for starting a new project with this great technologies.
Thursday, December 8, 2011
Best Web Framework for Liferay Portlet Development
Over the past months I've tried several web frameworks for portlet development on the liferay community portal.
The options I've tried are:
The options I've tried are:
- The framework liferay provides. (MVC Portlet, Alloy UI)
- Spring Portlet MVC
- Vaadin
- Java Server Faces (Portletfaces and Primefaces components)
- Java Server Faces (Portletfaces and IceFaces components)
- Apache Wicket.
In my opinion, I would rate these frameworks in the following way:
- JSF Primefaces
- Spring Portlet MVC
- Vaadin
- Liferay Framework
- JSF IceFaces
- Wicket.
This is the discussion of each:
JSF Primefaces
This is the one I found best, easy to configure, most of the components working out of the box, and easy spring integration. The con is, if you're used to JSF 2 and greater you'd find some missing features which are kind of important like view scoped managed beans and you loose the ability to send parameters over EL (this is because of the spring integration). But in general terms this framework fits great for general portlet development.
Spring Portlet MVC
This framework really gets along with the portal and is the ideal thing if you like to code tons of javascript and have fine grained control over everything. The con is the increased development time and if you have a project with lots of portlets then you'll have a lot of xml files.
Vaadin
Vaadin does a great job also for portlet development most of the components work out of the box, but it has some annoyances:
- Every time you change something you need to re deploy your portlet.
- You need to have the same vaadin library you're developing deployed on your portal which may cause problems with older vaadin portlets.
- Compile-time weaving for spring integration.
- Some features mising.
Liferay Framework
This framework works really well on liferay, but is really a developer nightmare, not well documented, lots of javascript and java code, difficult to integrate with your own spring context. In general terms, this is only well-suited for really simple portlets with no ajax support.
JSF IceFaces
This is supposed to be the best option for liferay JSF portlet development, or at least that's what the creators say, nevertheless I couldn't really make it work after several hours of configuration and web browsing, but as it is a JSF framework, the basic jsf features work well, and I think with the proper documentation this could get really good.
Wicket
Even though I love wicket and was the first option I tried, I was disappointed that it barely worked. No wicket magic for ajax support and also wicket dropped support for portlets on 1.5 so really, is not a good option for liferay.
Well, that's it with the frameworks, I hope this short review can help you to find the best framework for developing liferay portlets.
Sunday, July 31, 2011
JSon and XML Views on Spring Web MVC
These past weeks I started a research on how was the best way to develop portlets for the liferay content manager, while on that research I came across the Spring Web MVC framework from which I've heard so many good things but until then never developed anything with it.
Even though developing portlets was somehow fun, I learned now why that framework is so loved also for regular web developers. And finally I'm loving it too :)
On this post I'll show you how to render with little efforts views on XML and JSon that are suitable for ajax development. I won't go through the boilerplate configuration for maven dependencies and the basic Spring Web MVC dispatcher portlet, spring context, etc. What I will show is how to configure and inject views suitable for transparently render xml and JSon out of JAX-B annotated Pojos.
If you want to see the whole example project, download it here. It requires Tomcat 7 or another Java EE 6 web container.
Library Requirements:
For the following practice I'll take advantage of the following libraries:
- The High Performance Jackson JSON processor.
- Spring OXM Integration (for xml rendering).
If you want to look at the configuration, I've uploaded the sample project to my file application so you cant download it.
Let's get Started.
First of all, We'll take a look at the POJOs we'll be converting to XML and JSon:
@XmlRootElement
public class ActionStatus implements Serializable {
private static final long serialVersionUID = 1L;
private boolean success;
private String message;
public ActionStatus() {
}
public ActionStatus(boolean success, String message) {
this.success = success;
this.message = message;
}
... //getters & setters
}
This one is generic and it helps us to provide feedback to the user.
@XmlRootElement
public class Contact implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String email;
private String phone;
public Contact() {
}
public Contact(String name, String email, String phone) {
this.name = name;
this.email = email;
this.phone = phone;
}
... //getters & setters
}
This one represents a contact which we could push or pull to/from the database.
Please notice that I've only added the @XmlRootElement annotation at class level. This annotation is a JAX-B annotation (you can see a better explanation from this pervious post) and it will help us to convert to both XML and JSon format. (The same way JAX-RS works).
Now we need to configure the views on our applicationContext.xml file (or on the dispatcher servlet xml file if you wish).
XML: MarshallingView
In this case we'll define the view as a bean, this view takes a Marshaller implementation as the constructor argument:
<!-- the json view -->
<bean id="jaxbAnnotationBinder" class="org.codehaus.jackson.xc.JaxbAnnotationIntrospector" />
<bean id="jsonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />
<bean id="jsonview" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"
p:objectMapper="#{jsonObjectMapper.setAnnotationIntrospector(jaxbAnnotationBinder)}" />
If we want to improve the implementation we can scan the beans from the classpath using the annotation (I'll let it as an exercise).
JSon: MappingJacksonJsonView
In this case we'll define some beans to bootstrap Jackson:
- A JAX-B annotation introspector: this will use the JAX-B annotations to obtain metadata from the POJO.
- An ObjectMapper implementation: this will use the given introspector to map our fields to JSON.
<!-- the json view -->
<bean id="jaxbAnnotationBinder" class="org.codehaus.jackson.xc.JaxbAnnotationIntrospector" />
<bean id="jsonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />
<bean id="jsonview" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"
p:objectMapper="#{jsonObjectMapper.setAnnotationIntrospector(jaxbAnnotationBinder)}" />
Finally, we can inject the view we wish to use on our controller as follows:
@Controller
public class IndexController {
@Autowired
@Qualifier("jsonview")
private View jsonView;
@Autowired
@Qualifier("xmlview")
private View xmlView;
@RequestMapping({"/", "/index.htm"})
public String homePage() {
return "index";
}
@RequestMapping("/contact/blank/xml")
public ModelAndView createBlankContactXml() {
return new ModelAndView(xmlView, "response", new Contact("blank", "blank@blank", "123456789"));
}
@RequestMapping("/contact/blank/json")
public ModelAndView createBlankContactJson() {
return new ModelAndView(jsonView, "response", new Contact("blank", "blank@blank", "123456789"));
}
@RequestMapping("/contact/save")
public ModelAndView createContact(Contact contact) {
System.out.println(contact.toString());
return new ModelAndView(jsonView, "response", new ActionStatus(true, "Woohooo"));
}
}
Note that we could change the way the POJO is rendered by just changing the string on the @Quailifier annotation. I find this approach very easy and elegant.
Hope you find this useful.
Monday, June 20, 2011
How to Integrate Spring with GWT Servlet
One thing you may be wondering when you start a new (and maybe your first) GWT project using spring framework on the back-end is how can we autowire the remote service servlets with the Service beans on the backend?
There are many ways to achieve this, but my favorite is very simple and direct, and it may be a great solution if you're looking on how to autowire a servlet too, and is to create a new superclass for all our RemoteServiceServlets, I called that superclass SpringServiceServlet, and it looks like this:
package com.juancavallotti.server;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import org.springframework.web.context.support.WebApplicationContextUtils;
/**
*
* @author juancavallotti
*/
public class SpringRemoteServiceServlet extends RemoteServiceServlet {
private static final long serialVersionUID = 1L;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
WebApplicationContextUtils
.getRequiredWebApplicationContext(getServletContext())
.getAutowireCapableBeanFactory()
.autowireBean(this);
}
}
So from now on, we just extend this class when writing our services and we get full autowire capabilities.
Hope you find it useful.
Sunday, June 12, 2011
List Edit Form in Wicket 1.5
The final result will look like the following image:

It's a simple table that has an add Item button to add an extra row to enter contact information, and the submit button which is supposed to do something interesting with the data.
First of all, here is the HTML file, pretty standard stuff:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>List Edit Form</h1>
<form wicket:id="multiform">
<table>
<thead>
<tr>
<th>Name</th>
<th>Last</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr wicket:id="forms">
<td><input type="text" wicket:id="name" /></td>
<td><input type="text" wicket:id="lastName"/></td>
<td><input type="text" wicket:id="email"/></td>
</tr>
</tbody>
</table>
<button type="submit" wicket:id="addItemButton">Add Item</button>
<button type="submit" wicket:id="doSomethingUseful">Submit</button>
</form>
</body>
</html>
As we can see, we have the form fields on the table, bound with wicket ids, and obviously the row has an id to match a wicket iterator component and of course the form has an id too.
We'll be editing contacts so we create a contact bean to hold the important information for the contacts, here I show only the attributes but imagine that this bean should have getters and setters for the attributes and it's better if you implement equals and hash code.
public class Contact implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String lastName;
private String email;
....
}
Now let's take a look at the code for the page:
package com.juancavallotti.wicket15.forms;
import java.util.ArrayList;
import java.util.List;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormSubmitBehavior;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.PropertyModel;
/**
*
* @author juancavallotti
*/
public class MultiFormPage extends WebPage {
private static final long serialVersionUID = 1L;
private List<Contact> contacts;
public MultiFormPage() {
contacts = new ArrayList<Contact>();
final Form multiform = new Form("multiform");
multiform.setOutputMarkupId(true);
//the list of items
multiform.add(new ListView("forms", new PropertyModel(this, "contacts")) {
private static final long serialVersionUID = 1L;
@Override
protected void populateItem(ListItem item) {
item.add(new TextField("name", new PropertyModel(item.getModelObject(), "name")));
item.add(new TextField("lastName", new PropertyModel(item.getModelObject(), "lastName")));
item.add(new TextField("email", new PropertyModel(item.getModelObject(), "email")));
}
});
//actions for the add item button
multiform.add(new AjaxSubmitLink("addItemButton") {
private static final long serialVersionUID = 1L;
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
contacts.add(new Contact());
target.add(multiform);
}
@Override
protected void onError(AjaxRequestTarget target, Form<?> form) {
target.add(multiform);
}
});
//actions for the submit button
multiform.add(new SubmitLink("doSomethingUseful") {
private static final long serialVersionUID = 1L;
@Override
public void onSubmit() {
System.out.println(contacts);
}
});
add(multiform);
}
}
Here we create the form, and add to it a list view, in the list view we populate the item with text fields and a property model that will perform the actual magic when the form is submitted.
Then we add the button to create new items, which is responsible for adding a new contact on the contact list and repainting the whole form on the client.
And finally we add the button to submit the form to hopefully someday do something interesting with the bunch of contacts the users will input.
Reflecting the data changes Immediately
An enhancement for this would be to reflect data changes as soon as the user makes them. This only requires a small code change. We add for each text field an ajax submit behavior for the event "blur" and that's it, the following snippet shows how to do it.
@Override
protected void populateItem(ListItem item) {
item.add(new TextField("name", new PropertyModel(item.getModelObject(), "name"))
.add(new BlurSubmitBehavior(multiform)));
item.add(new TextField("lastName", new PropertyModel(item.getModelObject(), "lastName"))
.add(new BlurSubmitBehavior(multiform)));
item.add(new TextField("email", new PropertyModel(item.getModelObject(), "email"))
.add(new BlurSubmitBehavior(multiform)));
}
class BlurSubmitBehavior extends AjaxFormSubmitBehavior {
private static final long serialVersionUID = 1L;
public BlurSubmitBehavior(Form form) {
super(form, "onblur");
}
@Override
protected void onSubmit(AjaxRequestTarget target) {
//we do nothing but we could do something interesting
System.out.println(contacts);
}
@Override
protected void onError(AjaxRequestTarget target) {
}
};
That's all for now, hope you find it useful.
Sunday, June 5, 2011
How to integrate Maven, GWT and Netbeans IDE
On the past I've created a web application based on GWT and in Netbeans IDE. I have to say it was a total nightmare! The version of GWT I worked with is 1.7, now things have changed, version 2.x is here for a long time and there are many tools to work with it.
A piece of advice.
For those who want to start a new GWT project, I still encourage them to use Eclipse IDE with the Google Plugin, the sad truth is eclipse is really MUCH better to work with GWT than Netbeans and has many tools such as visual designers and wizards to do things easy and all of that. Nevertheless, if you use maven you can work with both IDE's and take the best from both worlds!
Let's get started.
First of all you will want to have some help with code editing, refactoring, creating new files out of a template and so on, to do this you want to install the GWT4NB plugin, this plugin can be easily installed on the Netbeans plugin manager or downloaded from the Netbeans page.
This plugins enables the IDE with very helpful stuff, it also works fairly well with maven and ant projects. To use ant you should download the GWT SDK and instruct the plugin on where to find it.

Maven Dependencies
Now we want to have the actual GWT libraries to start coding our application, so we need to include two important dependencies:
- gwt-user: With this dependency we have the core GWT API, we may choose the version we like but the important thing is the scope of this library, we will add this library as provided because we'll only use it when compiling gwt code to javascript, if we don't set this dependency to provided, it will end up on the final WAR making it heavier.
- gwt-servlet: We need this to process RPC requests and it isn't really used on development so we'll set the scope for this dependency to runtime.
<dependency>
<groupId>com.google.gwt</groupId>
<artifactId>gwt-servlet</artifactId>
<version>${gwt.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.google.gwt</groupId>
<artifactId>gwt-user</artifactId>
<version>${gwt.version}</version>
<scope>provided</scope>
</dependency>
Now that we have the GWT dependencies and we have no more problems to compile our JAVA code, we need a way to compile the client code into Javascript. Also we need a way to start GWT development mode to be able to test our code, to do this we'll use the Maven GWT plugin.
We can hook (or not) the Maven GWT plugin into our lifecycle, but the very annoying thing of working with GWT on Netbeans (at least for previous releases) is the fact that you end up compiling the GWT client side as many times as you compile the application, and believe me you don't want to waste two extra minutes of your life for each build, so I removed the build hook.
You can fire at will the gwt client side code compilation using the goal gwt:compile of the maven GWT plugin.
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>gwt-maven-plugin</artifactId>
<version>2.2.0</version>
<executions>
<execution>
<goals>
<!-- remove this to not compile gwt client every time -->
<goal>compile</goal>
<goal>test</goal>
</goals>
</execution>
</executions>
<configuration>
<hostedWebapp>${project.build.directory}/${project.build.finalName}</hostedWebapp>
</configuration>
</plugin> Running and Debugging in Development Mode
Something brilliant about development mode is the possibility to change code and see the changes as soon as you reload the browser, so we obviously want the ability to do that. The maven GWT plugin provides us with two goals to start the development mode: gwt:run and gwt:debug.
If we choose to use the gwt:debug goal, then the plugin tells us the parameters to attach out JPDA debugger to the hosted mode, and then set breakpoints at will.

Pitfalls and Gotchas
There are some pitfalls and gotchas when working with GWT. The most important one is: If you plan to use a J2EE full profile container (and with it use EJBs and persistence), my advice is: Do not use GWT, or use it in a way you lookup EJBs using JNDI. This is because GWT development mode deploys the application on a Jetty server who knows nothing about EJBs and such. A better solution would be to use the spring framework, not only because it's better but the spring framework doesn't have any problem on running on jetty.
That's all for now, hope you find it helpful.
Sunday, May 29, 2011
Playing with Wicket 1.5
This weekend I played with the new wicket 1.5 and saw some improvements that I'd like to share. These improvements are about page mounting and page parameter translation, it turns out that we don't choose anymore how parameters will be passed to the page when we mount the page but just simply mount the page and then you can read parameters in a new way.
Mounting a Page.
To mount a page we just need to (as always) call the mount method on our application class, but we can note that the wicket folks have removed (not even deprecated) the mount methods that take IRequestTargetUrlCodingStrategy as a parameter and instead created a simple mountPage method.
Here is an example of how pages will be mounted from now on:
@Override
protected void init() {
super.init();
mountPage("/home", HomePage.class);
}
Reading the Parameters.
Some of you may ask, if the URL coding strategies have been removed, now how can we read the page parameters?
The answer is simple! From the PageParameters object we get on the page constructor, this class has been rebuilt and moved into another package and no longer extends ValueMap, this change is HUGE and it will impact lots of my code for sure, but anyway, I think this change is for good since now I can query lots of things to read the parameters and something really ugly is now removed from our lives: We now can read indexed parameters with numbers and not with string-numbers. We also have the chance to read the parameters converted as different types in a much more elegant way.
Here is an example of how parameters can be read:
public class HomePage extends WebPage {
private static final long serialVersionUID = 1L;
public HomePage(PageParameters params) {
//build a list of the page parameters:
ArrayList<String> stringList = new ArrayList<String>();
int indexed = params.getIndexedCount();
//go through the indexed page parameters
for (int i = 0; i < indexed; i++) {
stringList.add(i + ": " + params.get(i).toString());
}
//go through the named page parameters
for (String key : params.getNamedKeys()) {
stringList.add(key + ": " + params.get(key).toString());
}
...
}
}
Servlet 3 Integration.
Wicket 1.5 wont have integration with servlet 3 but I've managed to use servlet3-style configuration for the wicket filter, the way it's done is less than ugly and I hope they add servlet 3 support in the future at least in the form of a separate project.
Here's how I did it:
package com.juancavallotti.wicket15;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebFilter;
import org.apache.wicket.protocol.http.WicketFilter;
/**
* This is a dummy subclass of filter to allow servlet 3.0 style config.
* @author juancavallotti
*/
@WebFilter(urlPatterns = "/*", initParams = {
@WebInitParam(name = "applicationClassName",
value = "com.juancavallotti.wicket15.DemoWicketApplication"),
@WebInitParam(name = "filterMappingUrlPattern",
value = "/*")
})
public class MyWicketFilter extends WicketFilter {
}
Sunday, May 15, 2011
Wicket 1.4 URL Character Encoding Problems
While developing web apps using wicket I've faced a problem with character encoding on URLs, for example, if you are using default settings and deploying your application into Tomcat, you'll be able to reproduce the issue quite simply:
- Create a page that prints somewhere a parameter read from the url (on standard query string url coding strategy).
- Call the page directly from the browser using some special char on the parameter value.
- Check that the special char has been decoded wrongly and you're scratching your head ;) on how to solve this out.
So my first thought was "this for sure is a wicket issue!" but soon learned the problem is much deeper than that. It turns out that most browsers don't tell to the server the encoding in which they're making the request so it's up to the server to guess this.
Modern browsers can send (and they actually do) make the requests in UTF-8 but most of the containers assume (because it's what you can read in the HTTP protocol RFC) that the encoding is by default ISO-8859-1. From the HTTP protocol definition:
The "charset" parameter is used with some media types to define the character set (section 3.4) of the data. When no explicit charset parameter is provided by the sender, media subtypes of the "text" type are defined to have a default charset value of "ISO-8859-1" when received via HTTP.
Ok, now, wicket has a lot of things you can set up on the web application, one of all is the request cycle character encoding, and it defaults to UTF-8, so this leads us to the first solution to our problem.
The first solution: Change the request cycle character encoding.
This can be done in a very simple way, with just a line of code:
getRequestCycleSettings().setResponseRequestEncoding("ISO-8859-1");
By doing this, you tell wicket to treat requests and responses as they were in ISO-8859-1 and special characters on the URL get url-encoded and everything works just fine. I have though some suspicions that some strings with special characters get broken but I really can't confirm that (because it could be they get broken for some other reason).
Now, I don't know you but I really don't feel comfortable with having my request and response on ISO-8859-1, specially because I like UTF-8. So since the problem is that the container assumes the requests are in ISO-8859-1 why not tell the container to assume the requests will be by default on UTF-8?
The second solution: Let the container assume the requests are in UTF-8.
To make this solution work we'll need to have access to the production server's configuration, and it's quite easy: tomcat's http connector has a property called URIEncoding, we just need to set that up and all set:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="UTF-8" /> This solution is quite pretty and works like a charm as well, and you can stick with your beloved UTF-8 charset.
I have a third solution but isn't pretty.
The third solution: Write your own QueryStringURLCodingStrategy
This solution is what I've fell down when I first met the issue because I thought it was a wicket issue and was exactly that: subclassing QueryStringURLCodingStrategy and write my own implementation of the decode parameters method and decode the parameters yourself!. At the time it worked, but now I can see it just have a lot of side problems so I think you want to stay away from this solution.
Other solutions that didn't work for me.
While trying to solve this problem I also tried other solutions without luck: some tried writing a servlet filter to set the encoding of the request to UTF-8 including the filters provided by the spring framework and apache tomcat. I also wrote my own implementation of a filter to change the encoding with no luck (the problem didn't go away). But also I think it's worth a try.
Saturday, May 7, 2011
Creating Custom Ajax Behavior on Wicket 1.4
Today we're creating a calendar picker behavior to add to some wicket components. Sample code for this post can be downloaded here.
At this point we have what we need to start creating a fun ajax behavior to enable text fields or panels to have a date picker.
And this is the HTML
In order to run the sample code you need a servlet 3 container like Apache Tomcat 7, lets get started.
Wicket Application Configuration.
Since servlet 3, the web.xml file isn't needed anymore. So how we configure the wicket filter? we could create a web.xml file and define it there but since we want to do things in the new way, we can define a subclass of the wicket filter and add the annotation defined on servlet 3 spec.
@WebFilter(urlPatterns = "/*", initParams=@WebInitParam(name="applicationClassName", value="com.juancavallotti.wicketcustomcomponents.DemoApplication"))
public class CustomWicketFilter extends WicketFilter {
}
Wicket Application and Home Page.
The wicket application and home page are pretty standard so I will not put them here, you can take a look at them directly on the sample code package.
JQuery and JQueryUI.
For this example we've used JQueryUI. As you should know, you can add resources on the java packages, so that's what we did, there are some more elegant ways to do this, specially if you're building your own component library, but for this example we've added the files from the JQueryUI bundle on the classpath and within our home page we loaded the necessary resources:
add(new StyleSheetReference("jqueryuitheme", HomePage.class, "jquery-ui-1.8.12.custom.css"));
add(new JavaScriptReference("jqueryjs", HomePage.class, "jquery-1.5.1.min.js"));
add(new JavaScriptReference("jqueryuijs", HomePage.class, "jquery-ui-1.8.12.custom.min.js"));
We have previously copied those files into /src/main/resources/{path to package} and wicket resource system will take care to set the right url for us on the html file.
Coding a custom AJAX Behavior
The common way to bootstrap JQueryUI components (and generally most of JQuery components) is to call a method with the name of the component on an HTML element with some id, like the following:
$(document).ready(function() {
$("#${componentId}").datepicker(${options});
});
So we'll start with that, and save it into a file called calendarTemplate.js on the resources package in which we'll create our custom behavior, in my case: /src/main/resources/com/juancavallotti/components.Now we create one class called JqueryUIDatePickerBehavior, that class will extend AbstractDefaultAjaxBehavior, and it looks like the following:
package com.juancavallotti.components;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.model.Model;
import org.apache.wicket.util.template.TextTemplateHeaderContributor;
/**
*
* @author juancavallotti
*/
public class JqueryUIDatePickerBehavior extends AbstractDefaultAjaxBehavior {
private JqueryUIDatePickerSettings settings;
public JqueryUIDatePickerBehavior() {
}
public JqueryUIDatePickerBehavior(JqueryUIDatePickerSettings settings) {
this.settings = settings;
}
@Override
public void onConfigure(Component component) {
component.setOutputMarkupId(true);
String id = component.getMarkupId(true);
Map<String, Object> params = new HashMap<String, Object>();
params.put("componentId", id);
params.put("options", buildSettings());
component.add(TextTemplateHeaderContributor.forJavaScript(JqueryUIDatePickerBehavior.class, "calendarTemplate.js", new Model((Serializable) params)));
}
@Override
protected void respond(AjaxRequestTarget target) {
}
private String buildSettings() {
if (settings == null) {
return "";
}
return settings.toString();
}
}
We override the onConfigure method and instruct the target component for this behavior to output the markup id, then we get that id and populate a HashMap with it (and some configuration that we'll soon explain). Then we call TextTemplateHeaderContributor class and we load our javascript template. The resulting code will be placed on the header section of the page with it's parameters replaced from the values on the hash map.Finally, we know that the DatePicker component has a lot of options (you can check them out on the documentation page), so It's a good idea to be able to set those options within java code, so we create a class named JqueryUIDatePickerSettings and add some of those options. Please note that this is only example code intended to give you some understanding of how this works, a production implementation should be far more robust than this one.
public class JqueryUIDatePickerSettings {
private String altField;
private String buttonText;
private String dateFormat;
public JqueryUIDatePickerSettings setTargetComponent(Component component) {
String markupId = component.getMarkupId(true);
altField = "#" + markupId;
return this;
}
public String getButtonText() {
return buttonText;
}
public JqueryUIDatePickerSettings setButtonText(String buttonText) {
this.buttonText = buttonText;
return this;
}
public String getDateFormat() {
return dateFormat;
}
public JqueryUIDatePickerSettings setDateFormat(String strDateFormat) {
this.dateFormat = strDateFormat;
return this;
}
@Override
public String toString() {
return "{"
+ "altField: '" + altField + "',"
+ "buttonText: '" + buttonText + "' , showOn: 'button',"
+ "dateFormat: '"+dateFormat + "'"
+ "}";
}
}
So now we have all the puzzle pieces in place but one: How we add the date picker behavior to some component? Very easy!Let's take a look at our full home page code and HTML:
public class HomePage extends WebPage {
private TextField<Date> date;
public HomePage() {
//BOOTSTRAP THE SETTINGS AND A TARGET COMPONENT
date = new TextField("datePickerTarget");
date.setOutputMarkupId(true);
JqueryUIDatePickerSettings settings = new JqueryUIDatePickerSettings();
settings.setTargetComponent(date).setButtonText("Pick Date!").setDateFormat("dd/mm/y");
add(new StyleSheetReference("jqueryuitheme", HomePage.class, "jquery-ui-1.8.12.custom.css"));
add(new JavaScriptReference("jqueryjs", HomePage.class, "jquery-1.5.1.min.js"));
add(new JavaScriptReference("jqueryuijs", HomePage.class, "jquery-ui-1.8.12.custom.min.js"));
//EXAMPLE USE OF THE BEHAVIOR
add(new TextField("miDatePicker").add(new JqueryUIDatePickerBehavior(settings)));
add(new WebMarkupContainer("inlineCalendar").add(new JqueryUIDatePickerBehavior()));
add(date);
}
} <body>
<h1>jCavallotti JQuery UI custom Components</h1>
<div wicket:id="inlineCalendar"></div>
<div><input type="text" wicket:id="miDatePicker" /></div>
<div><input type="text" wicket:id="datePickerTarget" /></div>
</body>
So we can finally see how things are working:
Conclusion
Building a component library in wicket is really easy and powerful, but we should not forget that there's already a lot of stuff out there ready for us to just use it, specially on wicket stuff maven repository. Nevertheless if what we find doesn't fit our needs we can still build a powerful component library.
Subscribe to:
Posts (Atom)



