I finally made it to San Francisco. My company sent me and ten colleagues to the Java One conference this year. This is supposed to be the biggest Java related conference in the world. We will see about that. It starts next Tuesday. In the meantime, I have some extra days I can spent in San Francisco. The plan is to travel to Fresno today and meet a friend which I have not seen for a couple of years.
Even before the Java One starts are there a lot of conferences about agile software development, Java based technologies or vendor specific stuff. Some of them are even for free. There is the CommunityOne West that starts next Monday. It is a side conference, also hosted by Sun. The Community One West goes from 1st to 3rd of June, also in Moscone Center. Since it is starting one day before the real JavaOne conference, it will be a great opportunity for me to get my head filled up with Java stuff even earlier. This is the CommunityOne program for Monday. There are a lot of sessions about Open Solaris and Cloud Computing. Since I will unfortunately only be coming back from Fresno on Monday, I will miss the morning and lunch sessions of the Community One West. However, there are some “pearls” I found during the afternoon like “Dynamic Data in a Web 2.0 World”, “Three Techniques for Database Scalability with Hibernate” or “What Do You Need to Know About Creating and Running a Scalable Web Site but Were Afraid to Ask?” Looking forward to go there.
Anyway, I want to quit this post with some practical tips for you guys entering the US. One of my colleagues was really hit hard this time from the US border control. I am not sure that is the correct name but they are the guys who will check your filled in papers from the plane and ask all these questions. Obviously they had found something in his profile or he just looked similar to someone they were looking for. He was asked to not proceed to the Exit but to another office called “Secondary”. In there, they asked a lot of detailed questions and this time even with a quite obvious background. Something like “Do you have family or friends in Saudi Arabia, Iran or somewhere else in the middle east?” I guess he was tempted to answer that our former System Owner migrated from Iran to Sweden some 20 years ago :)
Then the staff was really going into detail with questions about Java One, like what type of conference it is. How many years he had worked in our company. What his position is in the company. What exactly he was doing etc. Finally, he cleared secondary. Now everyone, even the Exit people, are in an area between the border security and the customs. This is where you pick up your luggage. I headed directly to the bathroom to get my hands washed. It is really smart, in times where US has the most Swine Influenza cases, to have everyone press their four finger and thumb of both hands on a fingerprint scanner!
Waiting for the luggage, some guys with beagle dogs went around, checking bags. These dogs are really great. They found a lot of food in peoples bags. It was fun to watch - snap, dog caught ya. After a couple of minutes, we got the bags and moved out. Guess what, my colleague was picked on again and he had to go someplace else. They asked him, if he wanted to change something in his customs declaration paper. Obviously that was not the case and they started searching his belongings. Of course they did not find anything.
Other stuff. Take it easy when leaving the plane. Border control usually starts off with only a few counters, so it looks like you have to wait forever. They will then open more and more counters. The passengers who were among the first, waited longest. It is better to come late I'd say. Make sure you have both sides on all forms filled in. Be prepared to answer detailed questions about the purpose of your trip and details about the place you are staying. Do not travel to the US if you do not speak English please. I had a Spanish lady in my queue, filling in a German I-94 form, who could not talk Any! English. It was a disaster. She did not even know what to fill in in which fields, not to talk about the questions they asked her. I know it is ignorant but thats the way it is, you have to be at least OK in English.
Last month Google added Java support to the Google App Engine. This means, that you can from now on host Java based applications on the Google infrastructure. Even better is the fact, that you can do it for free. Well, it is free for starters. There are quotas like 5 million page views per day, 6,5 hours CPU time per day, 1GB traffic per day etc. For the everyday "lets-do-something in Java" app, this is more than enough, so I decided to run a simple Wicket web-application on Googles appengine.
I am still a part-time student at Fernuni Hagen in Germany and in the current semester I am in a course called “Web 2.0 and social software”. The course is organized so that 3 students have to pick a topic from the web 2.0 bubble and prepare a presentation about it. Recently I have read the book “Collective Intelligence in Action” so I thought I might as well talk about Tag, Tagging and TagClouds. It is always better to not just talk in your presentations but show some real action. Therefore I created a little web-application, based on Satnam Alag's domain model from the book and powered with Apache Wicket and Spring to be fully functional.
The non Google App Enginefied version uses an in-memory HSQL database to persist Tags, Users and Items. This means, if you restart the application, everything will be gone. Everything is visualized using a TagCloud embedded in a Apache Wicket WebPage. The page will also contain entry forms to add new Users, Items and Tags. So here is the domain model which consists of five classes. The Entity class is an abstract base class for Item, Tag, TaggedItem and User.
public abstract class Entity implements Serializable { private static final long serialVersionUID = 1L;
public int id;
public String name;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false;
Entity entity = (Entity) o;
if (id != entity.id) return false;
return true; }
@Override public int hashCode() { return new Integer(id).hashCode(); } }
public class User extends Entity { }
public class Tag extends Entity { }
public class Item extends Entity { }
public class TaggedItem extends Entity { private int _userId;
private int _itemId;
private int _tagId;
private int _weight;
public int getUserId() { return _userId; }
public void setUserId(final int userId) { _userId = userId; }
public int getItemId() { return _itemId; }
public void setItemId(final int itemId) { _itemId = itemId; }
public int getTagId() { return _tagId; }
public void setTagId(final int tagId) { _tagId = tagId; }
public int getWeight() { return _weight; }
public void setWeight(final int weight) { _weight = weight; } }
The CRUD operations for this domain model are implemented using the DAO pattern (surprise, surprise). On top of the hierarchy sits the GenericDao interface which contains methods for read, write, delete. Then I have created interfaces for each individual DAO class that is connected to one entity in the domain model, ie. UserDao or ItemDao. These individual DAO interfaces extend the GenericDao, specifying the Entity to persist and the primary key type. The concrete implementation is now done in classes like UserJdbcDao or ItemJdbcDao. These are implementing the appropriate interface and extend a helper class called AbstractJdbcDao, which contains a reference to the Spring SimpleJdbcTemplate. Here is an example of the class structure for the User class.
public interface GenericDao<T, PK extends Serializable> {
/** * Persist the newInstance object into database */ PK create(T newInstance);
/** * Retrieve an object that was previously persisted to the database using * the indicated id as primary key */ T read(PK id);
/** * Retrieves all objects that were previously persisted to the database. */ List<T> readAll();
/** * Save changes made to a persistent object. */ void update(T transientObject);
/** * Remove an object from persistent storage in the database */ void delete(T persistentObject); }
public interface UserDao extends GenericDao<User, Long> { /** * Returns the {@link User} whose name matches the given String. * @param name a users name * @return User or <code>null</code> */ User readByName(final String name); }
public abstract class AbstractJdbcDao<T extends Entity> { private SimpleJdbcTemplate m_simpleJdbcTemplate; private String m_identityQuery;
public void setDataSource(DataSource dataSource) { m_simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); }
public String getIdentityQuery() { return m_identityQuery; }
public void setIdentityQuery(final String identityQuery) { m_identityQuery = identityQuery; }
abstract ParameterizedRowMapper<T> getMapper(); }
public class UserJdbcDao extends AbstractJdbcDao<User> implements UserDao { private static final ParameterizedRowMapper<User> MAPPER = new ParameterizedRowMapper<User>() { public User mapRow(ResultSet rs, int rowNum) throws SQLException { final User user = new User(); user.setId(rs.getLong("user_id")); user.setName(rs.getString("user_name")); return user; } };
public Long create(User newInstance) { final SimpleJdbcTemplate template = getSimpleJdbcTemplate(); template.update("INSERT INTO user(user_name) VALUES(?)", newInstance.getName()); return template.queryForLong(getIdentityQuery()); }
public User read(Long id) { final SimpleJdbcTemplate template = getSimpleJdbcTemplate(); final List<User> users = template.query("SELECT * FROM user WHERE user_id = ?", getMapper(), id); return users.isEmpty() ? null : users.get(0); }
public User readByName(final String name) { final SimpleJdbcTemplate template = getSimpleJdbcTemplate(); final List<User> users = template.query("SELECT * FROM user WHERE user_name = ?", getMapper(), name); return users.isEmpty() ? null : users.get(0); }
public List<User> readAll() { final SimpleJdbcTemplate template = getSimpleJdbcTemplate(); return template.query("SELECT * FROM user", getMapper()); }
public void update(User transientObject) { throw new UnsupportedOperationException("Not implemented yet."); }
public void delete(User persistentObject) { final SimpleJdbcTemplate template = getSimpleJdbcTemplate(); template.update("DELETE FROM user WHERE user_id = ?", persistentObject.getId()); }
Everything is wired together using Spring beans. This is where I define, that I want to use an in-memory database. All standard Spring stuff so far, no magic involved.
Also note that I used some special DataSource which will always execute a database initializer script. To use this InitializingBasicDataSource, you have to reference the SpringByExample library. In Maven powered projects you would add this to your POM:
<repositories> <repository> <id>springbyexample.org</id> <name>Spring by Example</name> <url>http://www.springbyexample.org/maven/repo</url> </repository> </repositories>
Finally I have created a single page using Apache Wicket which will visualize the TagCloud and also contain form fields to create and delete Users, Items and Tags. The page class is called HomePage and contains references to all DAO beans. Later on, it will replace the DAO beans with the ones I have to use in a Google App Engine environment. Here is my HomePage. I have removed a lot of code for better readability as the class is complex. Get the source code to have a look at the full implementation.
public class HomePage extends WebPage { private static final long serialVersionUID = 1L;
public HomePage(final PageParameters parameters) { addUserFields(); addItemFields(); addTagFields();
displayTagCloud();
... }
private void displayTagCloud() { ... }
private void addTagFields() { final Form tagForm = new Form("newTags");
final RequiredTextField newTagName = new RequiredTextField("newTagName", new PropertyModel(this, "newTagName")); tagForm.add(newTagName);
final IModel userChoices = new LoadableDetachableModel() { protected Object load() { return m_userDao.readAll(); } };
final IChoiceRenderer userChoiceRenderer = new IChoiceRenderer() { public Object getDisplayValue(Object object) { final User user = (User) object; return user.getName(); }
public String getIdValue(Object object, int index) { final User user = (User) object; return user.getId() + ""; } };
final ListChoice userListChoices = new ListChoice("taggingUser", new PropertyModel(this, "taggingUser"), userChoices, userChoiceRenderer); userListChoices.setRequired(true); tagForm.add(userListChoices);
final IModel itemChoices = new LoadableDetachableModel() { protected Object load() { return m_itemDao.readAll(); } };
final IChoiceRenderer itemChoiceRenderer = new IChoiceRenderer() { public Object getDisplayValue(Object object) { final Item item = (Item) object; return item.getName(); }
public String getIdValue(Object object, int index) { final Item item = (Item) object; return item.getId() + ""; } };
final ListChoice itemListChoices = new ListChoice("taggedItem", new PropertyModel(this, "taggedItem"), itemChoices, itemChoiceRenderer); itemListChoices.setRequired(true); tagForm.add(itemListChoices);
final Button saveNewTagButton = new Button("saveNewTagButton") { @Override public void onSubmit() { super.onSubmit();
Tag existingTag = m_tagDao.readByText(m_newTagName); if (existingTag == null) { final Tag newTag = new Tag(); newTag.setName(m_newTagName); m_tagDao.create(newTag);
final Long taggingUserId = m_taggingUser.getId(); final Long taggedItemId = m_taggedItem.getId();
final TaggedItem taggedItem = new TaggedItem(); taggedItem.setItemId(taggedItemId); taggedItem.setUserId(taggingUserId); taggedItem.setTagId(existingTag.getId());
// Existing Tags final Form existingTagsForm = new Form("existingTagsForm");
final IModel taggedItemsModel = new LoadableDetachableModel() { protected Object load() { return m_taggedItemDao.readAll(); } };
final ListView existingTaggedItems = new ListView("existingTaggedItems", taggedItemsModel) { protected void populateItem(ListItem item) { final TaggedItem taggedItem = (TaggedItem) item.getModelObject();
final User taggingUser = m_userDao.read(taggedItem.getUserId()); final Item itemContainingTag = m_itemDao.read(taggedItem.getItemId()); final Tag tag = m_tagDao.read(taggedItem.getTagId());
final Label taggedText = new Label("taggedText", new PropertyModel(tag, "name")); item.add(taggedText); final Label taggedBy = new Label("taggedBy", new PropertyModel(taggingUser, "name")); item.add(taggedBy); final Label taggedAt = new Label("taggedAt", new PropertyModel(itemContainingTag, "name")); item.add(taggedAt);
final Button deleteTaggedItem = new Button("deleteTaggedItem") { @Override public void onSubmit() { super.onSubmit();
So far so good. Lets now Google App Enginefy this application. First of all, since this application uses Apache Wicket, you have to change some settings regarding Threads. Google Appengine does not support Threads today. Step 1: run the Wicket application in deployment mode to disable a thread checking for modifications in the background. Step 2: override the method newSessionStore() in your WebApplication class like this:
@Override protected ISessionStore newSessionStore() { return new HttpSessionStore(this); }
This will eliminate another thread that is used by the default DiskPageStore class. Step 3: enable sessions in Google App Engine as they are turned off by default. Wicket uses Http Session heavily. I got all this from Alastair Maw’s blog, thanks a lot!
Now you have to add all the libraries that come with the Google App Engine SDK to your project. In my case the project is based on Maven, so I added the following to my pom.xml.
Unfortunately some dependencies cannot be resolved, even with the extra repositories I added manually. You have to add these jar file manually to your local Maven repository. I will not write about it here but check Dan Walmsleys Blog or Shalins Blog, they explain what you need to do.
Alright, now that we have all set up to Google App Enginefly our Java application - let's start. The App Engine SDK ships with a Servlet Container which you can start and test your application in an App Engine like environment. Download and unzip the SDK, then go into the bin folder. To enable remote debugging in the appengine environment, open the startup script (dev_appserver.sh in Linux) and make it look like this:
#!/bin/bash
# Launches the development AppServer
[ -z "${DEBUG}" ] || set -x # trace if $DEBUG env. var. is non-zero
SDK_BIN=`dirname $0 | sed -e "s#^\\([^/]\\)#${PWD}/\\1#"` # sed makes absolute
Next time you start your local appengine, you will be able to start a remote debugger on port 8000. Nice!
So at this point, the application would run on Google App Engine without problems. However, the data is not persistent and will be gone every time you restart. So let's use a real database. Each App Enginefied application can access something what Google calls a datastore. The datastore may be accessed using either JDO or JPA. Neither plain JDBC nor O/R mappers like Hibernate or Toplink will work at this stage. Appengine uses something called datanucleus for datastore access, which I think is another abstraction for different ways of persistence. So datanucleus will process JDO or JPA instrumented classes and do some persistence magic.
I decided to use JDO to access the appengine datastore from my application. In the first step let's add a PersistenceManagerFactory and some new DAO beans to the current Spring configuration.
Next I wrote a set of new DAO classes based on the JdoTemplate from Spring. When compared to JDBC, it is the AbstractJdoDao this time, which contains most code. The concreted DAO classes like UserJdoDao are rather small and reuse almost everything in the AbstractJdoDao.
public abstract class AbstractJdoDao<T extends Entity> { private JdoTemplate m_jdoTemplate;
public JdoTemplate getJdoTemplate() { return m_jdoTemplate; }
public void setPersistenceManagerFactory(final PersistenceManagerFactory persistenceManagerFactory) { m_jdoTemplate = new JdoTemplate(persistenceManagerFactory); }
public T readEntityByName(final String name, final Class<T> clazz) { final JdoTemplate jdoTemplate = getJdoTemplate(); final Collection found = jdoTemplate.find( clazz, "m_name == value", "String value", new Object[] {name} ); return (found != null && !found.isEmpty()) ? (T) found.toArray()[0] : null; }
public Long createEntity(final T item) { final JdoTemplate jdoTemplate = getJdoTemplate(); final T persistentItem = (T) jdoTemplate.makePersistent(item); return persistentItem.getId(); }
public T readEntity(final Long id, final Class<T> clazz) { final JdoTemplate jdoTemplate = getJdoTemplate(); return (T) jdoTemplate.getObjectById(clazz, id); }
public List<T> readAllEntities(final Class<T> clazz) { final JdoTemplate jdoTemplate = getJdoTemplate(); return new ArrayList<T>(jdoTemplate.find(clazz)); }
public void updateEntity(final T transientObject) { final JdoTemplate jdoTemplate = getJdoTemplate(); jdoTemplate.refresh(transientObject); }
public void deleteEntity(final T persistentObject) { final JdoTemplate jdoTemplate = getJdoTemplate(); jdoTemplate.deletePersistent(persistentObject); } }
public class UserJdoDao extends AbstractJdoDao<User> implements UserDao { public User readByName(final String name) { return readEntityByName(name, User.class); }
public Long create(final User user) { return createEntity(user); }
public User read(final Long id) { return readEntity(id, User.class); }
public List<User> readAll() { return readAllEntities(User.class); }
public void update(final User transientObject) { updateEntity(transientObject); }
public void delete(final User persistentObject) { deleteEntity(persistentObject); } }
Using JDO requires that the bytecode in your domain model classes is instrumented with the persistence information. So first of all, lets put down this information. To be least intrusive, I decided to provide separate .jdo files instead of using annotations. Here is the package.jdo file which I put in the package along with my domain model classes.
Unfortunately datanucleus does not support primary keys of type Integer and all Id's in my JDBC based applications were Integers. So I had to change from Integer to Long to get it working. Quite intrusive but something I can live with. As a last step, Maven needs to instrument the domain classes using the JDO instructions from my package.jdo file. I added the maven-datanucleus-plugin in my Maven build process.
Unfortunately it turned out the Google App Engine has huge difficulties when you have a hierarchy of persistence capable subclasses. In my case each User, Item, Tag and TaggedItem all derive from Entity. The Entity class contains the persistent fields id and name. For some reason in the current version of the datanucleus-appengine plugin, the fields from a persistence capable superclass are not accessible within the subclass. In other words, you cannot use inheritance in your domain model if you want to use JDO and Google App Engine. I have started two threads in the App Engine community and Max Ross from Google promised that Inheritance will receive a higher priority in upcoming versions of the datanucleus-appengine plugin.
Let's sum this up. Google App Engine is a really great thing Google came up with. It is also a Google example that Tim O'Reilly is right about the perpetual Beta, which is what I think we see with appengine right now. It has been put into public earlier than you would usually expect it from other Google products, probably to leverage the “power of the community” in making it better and more stable. On the other hand, I do not think that Google App Engine has reached a state where it can be used for real life enterprise applications.
Only one month left to this years JavaOne in San Francisco. About 8 to 10 Java geeks from my company will be heading to the US for the conference. We are leaving Stockholm May 29 to fly to San Francisco via Frankfurt. I am really happy I was selected to go to Java One this year. It is a great opportunity to get some fresh ideas from the Java Community. Also I am meeting a good friend which I haven't visited since 2002.
Today I received an email from JavaOne team that the schedule builder was ready and that it was recommended to put together a list of sessions I would like to attend. Unlike other software development conferences like OOPSLA, where everything is rather small, JavaOne is supposed to be quite crowdy and rooms fill up fast. So I spent some minutes today to build up my preliminary Java One session schedule.
Compared to OOPSLA 2008, the Java One is very Sun focused. A lot of talks are about Sun libraries, applications and tools. Since we are not using Glassfish application server or Java Server Faces, I decided to skip on these talks. The this years big hype seems to be Cloud Computing. There are tons of sessions having the word “cloud” in the title. Another big topic is REST and web services in general. Not sooo many talks are about dynamic languages this year I think. Unfortunately I skipped all the great Scala sessions at last years OOPSLA, as I did not knew what Scala was back then. There are now 3 talks about Scala and the Scala web framework Lift which I will be attending to. Unfortunately there are no sessions about Apache Wicket, my current favorite web framework.
Some of the session I really look forward to:
(TS-6802) Hadoop, a Highly Scalable, Distributed File/Data Processing System Implemented in Java™ Technology
This is about an open source implementation of Google's Map Reduce algorithm, which comes in handy if you have to deal with gigantic sets of data. This would be the case if you harvest user behavior on the web to use it for Collective Intelligence, an area which fascinates me very much right now. (BOF-3820) Lift: The Best Way to Create Rich Internet Applications with Scala
As Groovy went more or less by me, I decided to work myself in into Scala. There was a series about Scala in the German Java Magazin that woke my interested. Lift is the Scala webframework that supposingly “steals” the best features from other Java based web frameworks. They borrow the strict separation of layout and business logic from Apache Wicket, which is one of my favorite libraries for web development today.
(BOF-5105) Hudson Community Meet-Up
Writing Hudson plugins is fun. I wrote a plugin for Testability Explorer last Christmas and I am hoping to meet Kohsuke and some nice people I had mail contact with via the Hudson community like Ulli Hafner.
Finally some sessions focusing on scaleability and performance which I am hoping to put into practice in our company as we deal with a gaming application that need to be high performant.
(TS-4407) Best Practices for Large-Scale Web Sites: Lessons from eBay
(TS-4696) JDBC? We Don't Need No Stinkin’ JDBC: How LinkedIn Scaled with memcached, SOA, and a Bit of SQL
(TS-4588) Where’s My I/O: Some Insights into I/O Profiling and Debugging
My agenda also has some general purpose topics like Ajax Push and Comet as well as Central Event Processing (CEP) which might be useful in the future. So we will see about these.
I just finished one of the best books I have read in a long time. It is titled “Collective Intelligence in Action” from Manning Publications and is written by Satnam Alag. We were reading the book in a book circle, which my company runs twice a year.
Collective Intelligence is all about making web applications better by using intelligence gathered from user interactions and behavior. There are a lot of very successful web 2.0 applications out there, which harvest user intelligence and then use this data to improve the user experience. I liked this book because it was very different from other Java related books I have read. It is not focused on one particular technology or framework. It is not too code focused, even though quite mathematical sometimes. While I read it, I came up with all these cool new ideas how I could make my own websites better. I will start to implement a little bit of collective intelligence in the next few months. I can really recommend this book if you want to be inspired about some new advanced features for your web applications.
The book starts off by giving a brief overview about web 2.0 applications and collective intelligence. Then the author explains how users and items can be mapped to each other using either content based mapping or collaboration based mapping. It gets a bit mathematical here with some dot product computations and the cosine based similarity. Chapter 3 is all about tags, tagging and how to leverage tags in a web application. The chapters 4, 5 and 6 introduce some nifty tools that can be used to write a api based blog searcher and a web crawler. I have myself done this stuff when I build my web applications, so it was great to see alternative approaches. In the second and third part of the book the author introduces the different algorithms to make predictions or cluster users and items. You will learn about classification, regression, clustering etc. It is getting very theoretical and sometimes a bit hard to follow but very, very interesting. Since all the code examples in the book are in Java, Alag uses WEKA and JDM (Java Data Mining) to implement the algorithms.
The reader will also learn a bit Lucene, the popular text indexer and searching framework. Lucene is being used to do content based learning. The Lucene parts are pretty basic though and should be familiar to those of you, who have worked with Lucene before. The book ends with a practical example of how to build a recommendation engine similar to Amazon.
Who is the book for? I can recommend it to experienced Java developers who would like to try out some new things in their own web applications. There are tons of great ideas in this book. Having a website with a couple of hundred visitors per days is a plus if you practically want to unleash some collective intelligence.
Fortunately I have subscribed to the Atlassian newsletter. I learned about a special offer they were running for five days. Anyone who is interested could by Jira and Confluence for just $5 each. The only limitation is that only 5 users can be registered in these two programs. Atlassian wants to raise some charity money with this campaign. It is an excellent opportunity to get these two awesome tools if you have a couple of applications running, do your own business or are with a small team.
Jira is a Java based web application for issue- and bug tracking. It is used by the majority of the open source projects. Confluence is a Wiki application with tons of cool plugins, that can be integrated with Jira and other Atlassian products. You and your friends can use Confluence to share knowledge in a Web 2.0 fashion.
I got an email from a former colleague today. The mail contained a link to a tool, which he has been developing for the past months. It is a standalone software that will constantly collect statistical data from your MySQL database server. The data that is polled contains information about queries, users, tables etc. and will be aggregated, to give you the opportunity to find problem areas fast.
Jet Profiler is not free, but there is a free version that you can download. So I got myself a copy of the Linux version to try it out. Installation is simply extracting the archive and starting a bash script file. The tool is very simple to get started with, you don't even need the documentation. You define a connection to your MySQL database and how often you want to poll for data. Finally you click the record button and Jet Profiler will start to monitor your database server.
When running in record mode, you of course have to generate some load on your database server. Running some real life applications would be best, so I started my Jboss AS and ran a couple of unit tests. It was nice to see which queries where run most and which schemas were accessed more often than others. My test setup was a bit made up of course. No practical use for the results I got from Jet Profiler. In real applications however, this tool might be gold. If you are running an application that is using MySQL as database, you can easily find bottlenecks and performance killers. Try it out for yourself.
Yesterday I finished my first plugin for the continuous integration engine Hudson. Hudson is the engine of choice at our Bwin office in Stockholm. The idea to write a plugin was born while attending a presentation about an open source tool called Testability Explorer at OOPSLA, presented by Misko Hevery from Google.
Writing the Hudson plugin took me almost two months now. There is not so much documentation about plugin creation on the web. I started off by reading through a great tutorial I have found here. This is almost the only documentation I could find. But even with this 7-part tutorial you will still have to do a lot of try-and-error coding. In the tutorial you will learn about Publishers, Reporters and Reporting. But a lot of stuff is not covered. The best approach for new beginners is to read the tutorial and set up your own base code structure accordingly. Then check out all the other existing Hudson plugins and check how other developers solve the same tasks that you will have to accomplish. Luckily for me, one of the busiest plugin developers spoke German, so I could bug him with some personal questions via Email and he helped me out a lot.
In Hudson you can have Freestyle and Maven 2 based projects. Your plugin should support both project types. Unfortunately both project types require different entry points. For Freestyle projects you start by writing a class that derives from the Publisher class. Maven 2 projects require you to write a Reporter class. From there, a big challenge will be to write code that can be re-used for both project types. This is not always easy, as you have to subtype different Interfaces and Classes for Maven 2 and Freestyle projects.
Hudson is using Stapler for rending web output. I have never seen this framework before, so this is another technology you will have to familiarize yourself with when writing a plugin. Hudson is build so that certain methods will be invoked via Stapler on your classes. It was frustrating for me to find out, how these methods had to be called and what signatures were required to put everything to work. For instance, in one of the report classes (AbstractBuildReport) I had to have a method called getDynamic that returned an Object. This Object could be anything that I wanted to visualize in my report details. I found out about this method inly by looking at other plugins, it was neither documented in the tutorial nor somewhere else.
Another black box for me is the Master and Slave thing, that is mentioned in the Tutorial. It was said that some code runs in the Master thread, which is apparently the main thread that Hudson executes in. In my plugin I create a second thread that will parse the Testability Explorer reports. This is according to the tutorial. However, I never had to copy any files back to the Master. Everything worked without that, so I have no clue why this would be needed. The plugin works and I am happy about it. However, I still have this unsatisfying feeling that I did not understand everything correctly and dont know anything about the Hudson internals.
So for those of you planning to write their first Hudson plugin, do not expect so much fun for the first try. Probably a lot of code written in the Testability Explorer plugin I would do differently now, but maybe that is just normal in software development.
In this part, I will write about the Wicket and Guice bits in the sample Facet Search project. In Part Two, I have already introduced two Wicket classes, the WicketApplication and the MoviePage. The WicketApplication was only 30 lines long. It used a GuiceComponentInjector to wire all dependencies via Guice and returned the MoviePage as the homepage of the application.
MoviePage then, used a private member that is referencing the Facetmap.
@Inject private Facetmap m_facetmap;
Notice the @Inject annotation from Google Guice. But how does Guice know what to dependency-inject for this? This is defined in a class called MainModule. Modules are the essence of all Guice applications. So if you have something like this in your Module class
then Guice will use a single instance of the MovieFacetmap class wherever a Facetmap Interface is needed. Let's have a look in the MovieFacetmap again.
public class MovieFacetmap extends SimpleFacetmap { @Inject public MovieFacetmap(@Named("movieFacetmapName") String name, ResourceSpace resourceSpace, Properties properties) { super(name, resourceSpace, properties); } }
MovieFacetmap.java
Again Guice stuff is present here. The constructor is annotated with @Inject, thereby putting all parameters under Guice control. We need to tell Guice what parameters to send in when calling the MovieFacetmap constructor. This instruction is again done in the configure() method of the MainModule.
The instruction reads as this for Guice: whenever something is annotated with @Named("movieFacetmapName"), use the String „80s Movies“. Whenever a ResourceSpace type is needed, use a single instance of MovieResourceSpace. Whenever Properties are needed use the MovieSelectionPropertyProvider to get to these Properties. This might not be working in large applications where you have a lot of Properties used everywhere, but it is enough in this small webapplication.
Basically the same guice stuff is used in the MovieResourceSpace constructor.
Guice Instruction: Whenever a Map interface is annotated with @Named("movies"), use a single instance of MovieList instead. It is very important to use the Singleton scope which Google Guice provides. Otherwise Guice will create a new instance every time a "guiced" object is needed and then the whole system will just not work properly. It is assuming that you have exactly one instance of the Facetmap, ResourceSpace and FacetSpace. Finally this is the full MainModule that you need.
public class MainModule extends AbstractModule { protected void configure() { bind(Facetmap.class) .to(MovieFacetmap.class) .asEagerSingleton();
Now that is should be clear, how the Facetmap is injected into the MoviePage for Wicket, let's take a look under the hood. The MoviePage constructor just calls the setupFacetMap method (the name is not quite appropriate I just realized as the Facetmap is already set up). Anyway the method looks like this
I am getting a request parameter that Wicket wraps for me into a PageParameters object. The parameter will be abscent in the initial request, so I will set it to an empty String per default. Next step is getting the current Selection object based on the request parameter. If the request parameter is empty or null, I will use the root Selection.
With the Selection object, it is time to populate the Wicket ListView's with the forward Selection's and the Resources that match the current Selection. A forward Selection is basically a Selection that the user may choose from his current Selection. Any forward Selection that will return at least 1 Resource is considered a valid forward Selection. In part two I wrote about 2 properties that will influence this behaviour. It is possible to make every forward Selection a valid one by setting com.facetmap.Selection.showEmptySelections to true.
/** * Returns a list of {@link MovieCriteria} objects from the specified Selection. */ private List getForwardSelections(Selection selection) { List movieCriterias = new ArrayList();
int count = selection.getFacetCount(); for (int i = 0; i < count; i++) { String facetTitle = extractFacetTitle(selection.getHeadings(i)); Iterator iterator; try { iterator = selection.getForwardSelections(i); } catch (InternalException e) { throw new RuntimeException("Unable to get forward selections", e); }
if (iterator != null) { List
First get the Facet count from the current Selection, then iterate over the Facets to get the forward Selection's. Perform an inner loop over the forward Selections to get the information that you want to display in the page (matched Movies, display name). All this information is wrapped into two domain classes Option and MovieCriteria. Remember that these domain classes need to be Serializable to work properly with Wicket.
The final step in the MoviePage is showing the Resource's (Movies) that match the current Selection. This is done in the setupResources() method. Everything you need to do is call getResources() on the current Selection and then display the Resources somehow using the Wicket Framework. No big magic happening here. This is the full MoviePage again.
public class MoviePage extends WebPage {
private static final long serialVersionUID = 1L;
public static final String REF_PARAMETER = "refId";
@Inject private Facetmap m_facetmap;
/** * Will be called by the Wicket framework. */ public MoviePage(final PageParameters parameters) { setupFacetMap(parameters); }
/** * Initializes all Wicket components based on the current selection * and the (global) {@link Facetmap}. */ private void setupFacetMap(final PageParameters parameters) { String ref = parameters.getString(REF_PARAMETER, ""); Facetmap facetmap = m_facetmap;
/** * Initializes all Wicket components based on the current {@link Selection}. */ private void setupResources(Selection currentSelection) { List resources = new ArrayList(); SelectedResourceIterator resourceIterator = null; try { resourceIterator = currentSelection.getResources(); } catch (InternalException e) { throw new RuntimeException("An error occured while getting resources.", e); }
if (resourceIterator != null) { while (resourceIterator.hasNext()) { Resource resource; try { resource = resourceIterator.next(); resources.add(resource); } catch (InternalException e) { throw new RuntimeException("An error occured while iterating and adding resources.", e); } } }
ListView resourceList = new ListView("resourceList", resources) { @Override protected void populateItem(ListItem item) { Movie movie = (Movie) item.getModelObject(); Label text = new Label("resourceName", movie.getTitle()); item.add(text); } }; add(resourceList); }
/** * Populates a ListView component based on the given {@link Selection }. */ private void setupForwardSelections(Selection currentSelection) { List selections = new ArrayList(); if (currentSelection != null) { selections = getForwardSelections(currentSelection); }
Label facetNameLabel = new Label("facetName", facetName); facetNameLabel.setRenderBodyOnly(true); item.add(facetNameLabel);
List
MoviePage.java
Now for the part that I like most about Apache Wicket - unit testing. No Selenium, no Watir is needed to test Wicket web applications. The framework is shipped with a bunch of testing classes that will work almost like GUI testing. So if it works in your unit test, you know it will work in your browser as well (Layout testing not included of course). Here is my TestNG test for the MoviePage class.
public class MoviePageTest { @Test public void testRootSelection() { WicketTester app = new WicketTester(); app.getApplication().addComponentInstantiationListener(new GuiceComponentInjector(app.getApplication(), new MainModule()));
ListView boxOfficeGrossListView = (ListView) facetListView.get("1:optionList"); List gross = boxOfficeGrossListView.getList(); assertTrue(gross.isEmpty(), "We should not have box office gross information.");
MovieList movieList = new MovieList(new MovieFacets()); app.assertComponent("resourceList", ListView.class); ListView resourceListView = (ListView) app.getComponentFromLastRenderedPage("resourceList"); List resourceList = resourceListView.getList(); assertEquals(resourceList.size(), movieList.size()); }
@Test public void testDrewBarrymore() { testActor("Drew Barrymore", 1); }
@Test public void testHarrisonFord() { testActor("Harrison Ford", 8); }
/** * Queries the {@link MoviePage} with the specified actor and expects the * given number of movies in the result list. * * @param actorName the name of an actor from the MovieList * @param expectedMovies the number of movies that he or she plays in */ private void testActor(final String actorName, final int expectedMovies) { WicketTester app = new WicketTester(); app.getApplication().addComponentInstantiationListener(new GuiceComponentInjector(app.getApplication(), new MainModule()));
app.assertComponent("resourceList", ListView.class); ListView resourceListView = (ListView) app.getComponentFromLastRenderedPage("resourceList"); List resourceList = resourceListView.getList(); assertEquals(resourceList.size(), expectedMovies, "There should be " + actorName + " movie(s) with " + actorName + "!");
break; } } } }
MoviePageTest.java
I am creating a new WicketTester. This WicketTester is replacing our own WicketApplication class in the test, that is why I have to call addComponentInstantiationListener(..) manually (since I also do it in WicketApplication). With the WicketTester class you essentially get these methods for testing:
startPage – request any WebPage subclass you want to test assertRenderedPage – assert the WebPage really showed up assertComponent – make sure the components you have added in your WebPage subclass are really contained getComponentFromLastRenderedPage – get the component from the WebPage after it was rendered
Each Component then has specific methods to validate their state. For instance the ListView Component has a getList() method, which I use to get me the MovieList in my test. All I have left in the Test, is to assert that there were indeed 450 movies in that list. This is all done in the testRootSelection() method. I have written two additional TestNG test cases, which will verify the use case in which a user has made a forward Selection from the initial request. The two test cases are called testDrewBarrymore() and testHarrisonFord(). I am setting up a PageParameters object for Wicket that will contain the right request parameter to render all movies in which Drew Barrymore and Harrison Ford are playing. There should be 1 movie with Barrymore (E.T. yeehaw) and 8 movies with Ford in the result list. You could easily come up with more complicated scenarios as the forward selections continue from there. For now this test should be just enough.
This concludes the part about Apache Wicket and Google Guice.
At this point you should have a project file for either IntelliJ or Eclipse and your web application should fire up, if you run mvn jetty:run in your command shell. The classes I will talk about in this part, are borrowed from the facetmapgold-2.1.war file, which you can download from the Facetmap website. If you extract this .war file, you will find the source code in the src.com.facetmap.example.movies folder. I did some slight modifications to the code, so it would fit better with Google Guice and Wicket. Also some of the classes I will write about here, have been created within the javasplitter web application. So don't expect all files to be found in the exploded facetmapgold-2.1.war directory. Anyway, let's look into details now.
The only thing present in this file is the Wicket filter, which is required for all web applications based on Apache Wicket. Nothing special regarding Google Guice is required in here. If we used Spring as our dependency injection provider, there would be additional stuff in the web.xml file. As you can see, the WicketFilter references the applicationClass which is javasplitter.web.WicketApplication. So let's look into this class.
/** * Application object for your web application. * */ public class WicketApplication extends WebApplication { @Override protected void init() { initDependencies(); }
public void initDependencies() { addComponentInstantiationListener(new GuiceComponentInjector(this, new MainModule())); }
public Class getHomePage() { return MoviePage.class; } }
WicketApplication.java
You add a GuiceComponentInjector in the init method and return a WebPage from the getHomePage() method, which in our case will be the MoviePage. Also when adding the GuiceComponentInjector, you have to specify a Module that defines how you want to wire your dependencies. The module is the main unit in Google Guice and comparable with the applicationContext file in Spring. I will go into the Guice details in the next part, so lets continue with the MoviePage class.
The MoviePage is a typical Wicket WebPage. It ships with two files, MoviePage.java and MoviePage.html.
/** * A simple page that will display some movies. */ public class MoviePage extends WebPage {
private static final long serialVersionUID = 1L;
public static final String REF_PARAMETER = "refId";
@Inject private Facetmap m_facetmap;
/** * Will be called by the Wicket framework. */ public MoviePage(final PageParameters parameters) { setupFacetMap(parameters); }
/** * Initializes all Wicket components based on the current selection * and the (global) {@link Facetmap}. */ private void setupFacetMap(final PageParameters parameters) { String ref = parameters.getString(REF_PARAMETER, ""); Facetmap facetmap = m_facetmap;
/** * Initializes all Wicket components based on the current {@link Selection}. */ private void setupResources(Selection currentSelection) { List resources = new ArrayList(); SelectedResourceIterator resourceIterator = null; try { resourceIterator = currentSelection.getResources(); } catch (InternalException e) { throw new RuntimeException("An error occured while getting resources.", e); }
if (resourceIterator != null) { while (resourceIterator.hasNext()) { Resource resource; try { resource = resourceIterator.next(); resources.add(resource); } catch (InternalException e) { throw new RuntimeException("An error occured while iterating and adding resources.", e); } } }
ListView resourceList = new ListView("resourceList", resources) { @Override protected void populateItem(ListItem item) { Movie movie = (Movie) item.getModelObject(); Label text = new Label("resourceName", movie.getTitle()); item.add(text); } }; add(resourceList); }
/** * Populates a ListView component based on the given {@link Selection }. */ private void setupForwardSelections(Selection currentSelection) { List selections = new ArrayList(); if (currentSelection != null) { selections = getForwardSelections(currentSelection); }
/** * Returns the current {@link Selection} from the specified {@link Facetmap} using * the given identifier. Will return the root selection if the given ref * parameter is blank or null. */ private Selection getCurrentSelection(Facetmap facetmap, String ref) { Selection selection; try { selection = StringUtils.isBlank(ref) ? facetmap.getRootSelection() : facetmap.getSelection(ref); } catch (InternalException e) { throw new RuntimeException("An error occured accessing a Selection.", e); } catch (UnknownReferenceException e) { throw new RuntimeException("An error occured accessing a Selection.", e); } return selection; }
/** * Returns a list of {@link MovieCriteria} objects from the specified Selection. */ private List getForwardSelections(Selection selection) { List movieCriterias = new ArrayList();
int count = selection.getFacetCount(); for (int i = 0; i < count; i++) { String facetTitle = extractFacetTitle(selection.getHeadings(i)); Iterator iterator; try { iterator = selection.getForwardSelections(i); } catch (InternalException e) { throw new RuntimeException("Unable to get forward selections", e); }
private int extractResourceCount(Selection selection) { int i = 0; try { i = selection.getResourceCount(); } catch (InternalException e) { throw new RuntimeException("An error occured while accessing the resource count in a Selection.", e); } return i; }
private String extractHeadingTitle(Heading[] headings) { String title = ""; if (headings != null && headings.length > 0) { title = (headings [0]).getTitle(); } return title; }
private String extractFacetTitle(Heading[] headings) { String title = ""; if (headings != null && headings.length > 0) { title = (headings [0]).getFacet().getTitle(); } return title; } }
MoviePage.java
The html file is for the markup, the java file will add and populate all Components within the page. I am not going into the Wicket details here, so let's just assume that you all know how Wicket works. The important part in the MoviePage class is the Facetmap, which in turn is injected by Google Guice. A Facetmap represents some sort of container, that stores a list of all you items and all the possible facets and headings.
/** * A {@link SimpleFacetmap} specific to movies. * * @author reik.schatz */ public class MovieFacetmap extends SimpleFacetmap { @Inject public MovieFacetmap(@Named("movieFacetmapName") String name, ResourceSpace resourceSpace, Properties properties) { super(name, resourceSpace, properties); } }
MovieFacetmap.java
The Facetmap class used in this project is called MovieFacetmap and is a subclass of the SimpleFacetmap that is part of the Facetmap Light library. When the MovieFacetmap is created on application startup, it has to be initialized with a name, a ResourceSpace and some Properties. The name is just a String and can be everything. You will notice a little @Named Annotation next to the parameter. That one comes from Google Guice. I will get to that in a later part. For now, just accept that the name will magically be set to "80s Movies". The ResourceSpace is another container class. This is where the items (in our case Movies) and the different facets are really kept. The Facetmap container is just using the ResourceSpace internally. For this sample web application, the ResourceSpace is implemented in a class called MovieResourceSpace.
/** * Wraps a {@link MovieList} in a ResourceSpace implementation, backed by the * classification scheme provided by {@link MovieFacets}. This ResourceSpace * will contain Movie objects, and like all ResourceSpace objects, it has an * underlying FacetSpace which describes how its resources are classified. */ public class MovieResourceSpace implements ResourceSpace { private final Map m_movies; private final FacetSpace m_facetSpace;
public FacetSpace getFacetSpace() { return m_facetSpace; }
public int getResourceCount() throws InternalException { return m_movies.size(); }
}
MovieResourceSpace.java
When the MovieResourceSpace is created, it receives a Map of Movies and a FacetSpace. The Map given to the MovieResourceSpace is an instance of the MovieList class, which for convinience is inheriting from HashTable. The FacetSpace given to the MovieResourceSpace is an instance of MovieFacets. It is worth looking into these two classes a little bit closer.
When MovieList is instanciated, it will automatically add almost 500 movies to itself. Each Movie has an id, name, release date, box office gross, genre, studio and a list of actors playing in it.
/* * Sample use of Facetmap 2.0 * (c) 2007 by Complete Information Architecture and Travis Wilson. *
* All source code in package "com.facetmap.example" or its subpackages * (the "Sample Code") uses Facetmap software to enable faceted browsing of * its data. The data in this program is fictitious and is not intended for * any use other than the demonstration of Facetmap. *
* The Sample Code is distributed in the hope that it will be informative, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */
/** * This represents the storage of {@link Movie} resources that we want to browse * via Facetmap. Movies are stored in a Map (not a java List) because each Movie * must be retrievable with a unique ID that stays constant during the life * of the Facetmap component. (If we just used the index numbering in a java * List as each Movie's unique ID, the IDs would change if we ever deleted a * Movie from the list. */ public class MovieList extends Hashtable { @Inject public MovieList(FacetSpace facetSpace) { super();
List movies = new ArrayList(); try { movies = createMovieList(facetSpace); } catch (ParseException e) {
} catch (UnknownReferenceException e) {
}
for (Movie movie : movies) { put(movie.getId(), movie); } }
public List createMovieList(FacetSpace facetSpace) throws ParseException, UnknownReferenceException { List movies = new ArrayList();
MovieFacets again, is a subclass of SimpleFacetSpace and contains a lot of code regarding the different facets and their headings. The facets are something like genre, studio, actors etc. Some headings you will find in this class are called Crime Drama, 20th Century Fox or Al Pachino. Now you should be getting a clearer picture. Each Movie is mapped to different headings, that exist in the MovieFacetSpace. For instance the movie E.T. the Extra-Terrestrial is mapped to the headings Drama, Universal, Drew Barrymore etc. And by the way, this is one of my favourite movies.
/* * Sample use of Facetmap 2.0 * (c) 2007 by Complete Information Architecture and Travis Wilson. *
* All source code in package "com.facetmap.example" or its subpackages * (the "Sample Code") uses Facetmap software to enable faceted browsing of * its data. The data in this program is fictitious and is not intended for * any use other than the demonstration of Facetmap. *
* The Sample Code is distributed in the hope that it will be informative, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */
/** * Wraps movie classification values in Facet objects, which gives us a * FacetSpace that the Facetmap can use. This FacetSpace is used as the * underlying FacetSpace of {@link MovieResourceSpace}. */ public class MovieFacets extends SimpleFacetSpace { public MovieFacets() { // Create Genre facet (Taxonomy) SimpleTaxonomyFacet genre = new SimpleTaxonomyFacet("genre", "Genre", "Any Genre"); for (int i = 0; i < Genres.length; i++) { genre.addHeading(new SimpleTaxonomyHeading(Genres[i])); } SimpleTaxonomyHeading comedic = new SimpleTaxonomyHeading("Comedic"); genre.addHeading(comedic); for (int i = 0; i < ComedicGenres.length; i++) { genre.appendHeadingInto(new SimpleTaxonomyHeading(ComedicGenres[i]), comedic); } SimpleTaxonomyHeading dramatic = new SimpleTaxonomyHeading("Dramatic"); genre.addHeading(dramatic); for (int i = 0; i < DramaticGenres.length; i++) { genre.appendHeadingInto(new SimpleTaxonomyHeading(DramaticGenres[i]), dramatic); } addFacet(genre);
// Create Release Date facet (Date) try { DateFormat dateFormat = new SimpleDateFormat("d-MMM-yyyy"); SimpleDateFacet release = new SimpleDateFacet( "releaseDate", "Release Date", "Anytime", dateFormat.parse("1-Jan-1980"), dateFormat.parse("1-Jan-1990") ); addFacet(release); } catch (ParseException exc) { throw new Error("Hardcoded date strings couldn't be parsed!", exc); }
// Create Studio facet (Taxonomy) SimpleTaxonomyFacet studio = new SimpleTaxonomyFacet("studio", "Production Studio", "Any Studio"); for (int i = 0; i < BigStudios.length; i++) { studio.addHeading(new SimpleTaxonomyHeading(BigStudios[i])); } SimpleTaxonomyHeading other = new SimpleTaxonomyHeading("other", "Other studios"); studio.addHeading(other); for (int i = 0; i < SmallStudios.length; i++) { studio.appendHeadingInto(new SimpleTaxonomyHeading(SmallStudios[i]), other); } addFacet(studio);
// Create Actor facet (Compound Taxonomy) SimpleTaxonomyFacet actorTaxonomy = new SimpleTaxonomyFacet("actors", "Actors", "No preference"); for (int i = 0; i < Actors.length; i++) { actorTaxonomy.addHeading(new SimpleTaxonomyHeading(Actors[i])); } SimpleCompoundHeadingFacet actors = new SimpleCompoundHeadingFacet(actorTaxonomy); addFacet(actors); }
public static String[] Genres = new String[]{ "Documentary" };
This was pretty much it for Facetmap. The other two classes from the javasplitter.web.facetmap package, that I have not talked so far, are Movie and MovieSelectionPropertyProvider.
/* * Sample use of Facetmap 2.0 * (c) 2007 by Complete Information Architecture and Travis Wilson. *
* All source code in package "com.facetmap.example" or its subpackages * (the "Sample Code") uses Facetmap software to enable faceted browsing of * its data. The data in this program is fictitious and is not intended for * any use other than the demonstration of Facetmap. *
* The Sample Code is distributed in the hope that it will be informative, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */
/** * Contains all the data about a movie. This object is also a Resource, so * it translates business-specific calls like {@link #getActors()} to * Facetmap-specific calls like getHeading(4) . *
* You could instead create a Resource object which wraps a Movie object, * which would be just as good. We have taken the inheritance shortcut * here because it better illustrates the use of the Resource interface. *
* We have also sacrificed typesafety, for the sake of brevity. Studio and * genre values could be typed enumerations; facets could be classes. Here * they are all addressed by simple Strings to keep excess code out of the * example. */ public class Movie implements Resource, Serializable { protected int id; protected String title; protected String link; protected Date releaseDate; protected int domesticBoxOffice; protected String studio; protected String genre; protected Collection actors; protected Heading[] headings = new Heading[5];
// Put headings in array. Since we know the order of headings in the FacetSpace, we could just assign headings[0], headings[1], and so // on, but the following approach is less presumptuous: headings[facetSpace.indexOf(genreHeading.getFacet())] = genreHeading; headings[facetSpace.indexOf(releaseHeading.getFacet())] = releaseHeading; headings[facetSpace.indexOf(boxOfficeHeading.getFacet())] = boxOfficeHeading; headings[facetSpace.indexOf(studioHeading.getFacet())] = studioHeading; headings[facetSpace.indexOf(actorsHeading.getFacet())] = actorsHeading; }
// Resource support
public String getAttribute(Object key) { if (Resource.TITLE.equals(key)) { return title; } else { return null; } }
public Heading getHeading(int index) { return this.headings[index]; }
public int getHeadingCount() { return this.headings.length; }
public int getId() { return id; }
// domain accessors (used by movie application, not by facetmap)
public Collection getActors() { return Collections.unmodifiableCollection(actors); }
public int getDomesticBoxOffice() { return domesticBoxOffice; }
public String getGenre() { return genre; }
public Date getReleaseDate() { return releaseDate; }
public String getStudio() { return studio; }
public String getTitle() { return title; }
}
Movie.java
package javasplitter.web.facetmap;
import com.google.inject.Provider;
import java.util.Properties;
/** * Provides a {@link Properties} object that will be used in the creation * of the MovieFacetmap. * * @author reik.schatz */ public class MovieSelectionPropertyProvider implements Provider { public Properties get() { Properties properties = new Properties(); properties.put("com.facetmap.Selection.resultLimit", String.valueOf(Integer.MAX_VALUE)); properties.put("com.facetmap.Selection.showEmptySelections", "false"); return properties; } }
MovieSelectionPropertyProvider.java
The Movie class is just an entity class that wraps a single movie from the real world. The MovieSelectionPropertyProvider is something Google Guice specific. It functions as a Provider class that returns a Properties instance. This Properties instance is given to the constructor of the MovieFacetmap (see above). Two properties are being used within the application. com.facetmap.Selection.resultLimit defines how many items you want to see in your resultset at a time. As I want to see all movies in the result, I am using a very high number for this property. com.facetmap.Selection.showEmptySelections is set to false. If you set it to true, the user would be able to choose forward selections that do not contain any items (movies).
This concludes the second part. If you want to create your own facet search using Facetmap Light, you have to create your own Facetmap, ResourceSpace, FacetSpace and a list of Resources (movies or whatever). In the next part I will write about Google Guice and Wicket.