Archive

Archive for June, 2009

Hibernate hard facts part 2

June 27th, 2009 5 comments

Hibernate LogoHibernate is a widely-used ORM framework. Many organizations use it across their projects in order to manage their data access tier. Yet, many developers working on Hibernate don’t fully understand the full measure of its features. In this serie of articles, I will try to dispel some common misunderstandings regarding Hibernate.

Part 1 : Updating a persistent object

Directional associations

Association is a relationship between two classes that denotes a connection between the two. Navigability is the way by which an instance of one class can access the instance of the second one. UML describes the following navigabilities:

  • undirectional navigability, from class A to class B
  • bidirectional navigability, from class A to class B and from the latter to the former
  • unknown navigability (early in the design)

When talking about persistence, associations are designed from (or to, depending on what comes first) foreign key constraints. If I want to describe that a customer can have multiple orders, chances are the Order table has a foreign key constraint on the Customer table. On the other hand, there’s no such thing as directionality in the relational world. This means that the designed directionality is a feature brought to you by the object world, and the mapping tool used.

In the relational world, we speak of a relationship’s ownership to identify the where the data used by the join resides. In the previous example, the Order table is the owner since it has the foreign key constraint on the Customer table. This ownership has no relation to navigability whatsoever.

In the case of a bidirectional association, one would think that creating the association from A to B would be enough. For example, in a one-to-many association, having a customer, if I create an account, I just have to add this account to my customer’s, haven’t I? Unfortunately, this is not the case. If I forget to associate both ends, I end up catching very nasty exceptions. Interestingly enough, they are different depending on which association you miss.

It is thus a good practice to create an addOrder() method on the Customer class to manage such subtleties:

/**
 * Adds an order to this customer's. Manage bidirectional associations.
 *
 * @param order
 */
public void addOrder(Order order) {

    getOrders().add(order);
    order.setCustomer(this);
}

Whether you use this tip or not, remember to document its use (or not) in the Javadoc, since if you don’t, client code will need to.

Now if one wants to remove an order from the database, one should normally call the session.delete() method. Like above, this will throw an exception if one didn’t previously remove this order from this customer’s. This will be slightly more hindering since it cannot be factorized in the domain class.

// We got the session somehow and the snippet is running in a transaction
Order order = (Order) session.load(Order.class, 1L);

Customer customer = order.getCustomer();

customer.getOrders().remove(order);

session.delete(order);

session.getTransaction().commit();

We’ve seen previously a simple many-to-one association creation. This gets even worse in the case of a many-to-many association update, since updating means removing and creating.

You can do it in a method, provided getters return the real collection and not an unmodifiable (a usually good practice).

// In the Customer class
public void removeOrder(Order order) {

    getOrders().remove(order);

    order.getCustomers().remove(this);
}
// In the Order class
public void removeCustomer(Customer customer) {

    getCustomers().remove(customer);

    customer.getOrders().remove(this);
}

You will find the test cases here.

Categories: Java Tags: , ,

Customize your JAXB bindings

June 17th, 2009 5 comments

JAXB is a bridge between the Java and the XML worlds, enabling your code to transparently marshalls and unmarshalls your Java objects to and from XML. In order to do this, you should have a class representing your XML-Schema. This class is created by the xjc. In most cases, xjc creates a class that won’t suit your needs. In this article, we’ll see why it does so and what we can do to customize this behaviour.

Prerequisite

This article suppose you use a Java Development Kit 6.0. Be wary that different updates of this same JDK 6 use different JAXB versions:

Update JAXB version
3 2.0.3
4 2.1.3

Concurrent technologies

Before diving into JAXB, one should ask oneself whether using JAXB is necessary. There’s a plethora of frameworks whose goal is to serialize/deserialize Java objects to and from XML:

  • Historically speaking (and from my humble knowledge), Castor XML was the first widely used framework to manage Java XML serialization.
  • Since Java 1.4, two classes XMLEncoder and XMLDecoder are available. Their are respectively equivalent to ObjectOutputStream and ObjectInputStream, only they produce XML instead of bytes.
  • Finally, XStream is a 3rd party framework that is fast to run and easy to use.

All these solutions are very good in reading/producing XML, yet they completely ignore the binding part. Binding is the creation of the Java class from the schema. Of course, JAXB has this feature.

XJC

xjc is the executable used to create Java classes from XML schemas. Available syntax are DTD, XML-Schema, RELAX NG, RELAX NG Compact and WSDL. Since I now exclusively use Maven to build my projects, I won’t use xjc directly but I’ll configure the Maven POM to use it. The first thing to do is to add the java.net repository to your POM (or your settings file, but I prefer the former):

<repositories>
    <repository>
        <id>maven2-repository.dev.java.net</id>
        <name>Java.net Maven 2 Repository</name>
        <url>http://download.java.net/maven/2</url>
    </repository>
</repositories>
<pluginRepositories>
    <pluginRepository>
        <id>maven2-repository.dev.java.net</id>
        <name>Java.net Maven 2 Repository</name>
        <url>http://download.java.net/maven/2</url>
    </pluginRepository>
</pluginRepositories>

Now, you’re ready to use the plugin:

<build>
    <plugins>
        <plugin>
            <groupId>org.jvnet.jaxb2.maven2</groupId>
            <artifactId>maven-jaxb2-plugin</artifactId>
            <version>0.7.1</version>
            <configuration>...</configuration>
        </plugin>
    </plugins>
</build>

Use the plugin with the following command line: mvn org.jvnet.jaxb2.maven2:maven-jaxb2-plugin:generate.

Common configuration

The previous command line will fail since we didn’t specify any configuration yet. The following should be assumed a good default:

<configuration>
    <schemaDirectory>src/main/resources/schema</schemaDirectory>
    <generateDirectory>src/main/generated</generateDirectory>
    <removeOldOutput>false</removeOldOutput>
</configuration>

This tells xjc to look for all xsd files under the src/main/schema directory and generate the classes under src/main/generated. It will use the binding files (*.xjb) under the former directory.

I sincerely advise you to set the removeOldOutput to false since xjc will erase all the directory content. If you use a source code management tool, this will include the directories used by your SCM (.cvs or .svn), a very bad idea.

You need two things still. The first is to set the the compiler level to at least 1.5 in order to annotations to work:

<plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <source>1.6</source>
        <target>1.6</target>
    </configuration>
</plugin>

Maven only accepts a single source directory. The second thing to do is to make the  src/main/generated directory to Maven when building the project. It can be done with the help of the builder plugin:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>build-helper-maven-plugin</artifactId>
    <executions>
        <execution>
            <id>add-source</id>
            <phase>generate-sources</phase>
            <goals>
                <goal>add-source</goal>
            </goals>
            <configuration>
                <sources>
                    <source>src/main/generated</source>
                </sources>
            </configuration>
        </execution>
    </executions>
</plugin>

Now using the previous command line will produce something useful! Try it and you will have some nice surprise.

Customization

In order to customize your bindings, you basically have 2 options:

  • polluting your XML Schema with foreign namespaces,
  • or keeping your XML Schema pure and putting all your bindings into a external file.

From the terms I used, you can guess I prefer option 2. This is the right time to use a binding file. Create a file named binding.xjb under src/main/resources/schema.

Package name

Of  course, the package name is not something desirable: by default, it is the XML-Schema namespace minus http:// plus _package. The first customization is to change this behaviour. Put the following content into your binding file:

<?xml version="1.0" encoding="UTF-8"?>
<bindings xmlns="http://java.sun.com/xml/ns/jaxb"
                xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance"
                xsi:schemaLocation="
http://java.sun.com/xml/ns/jaxb http://java.sun.com/xml/ns/jaxb/bindingschema_2_0.xsd"
    version="2.1">
    <schemaBindings>
        <package name="ch.frankel.blog.jaxb" />
    </schemaBindings>
</bindings>

If you have the following error, you should use update 14 from JDK 6:

java.lang.LinkageError: JAXB 2.0 API is being loaded from the bootstrap classloader, but this RI (from jar:file:/C:/${user.home}/.m2/repository/com/sun/xml/bind/jaxb-impl/2.1.10/jaxb-impl-2.1.10.jar!/com/sun/xml/bind/v2/model/impl/ModelBuilder.class) needs 2.1 API. Use the endorsed directory mechanism to place jaxb-api.jar in the bootstrap classloader. (See http://java.sun.com/j2se/1.5.0/docs/guide/standards/)

If not, chances are your classes will have been generated under the suitable package name.

Serializable

Managing your entities will probably require you to have them serializable. In order to achieve this, you’ll have to modify your binding file to add the java.io.Serializable interface to your classes along with a serialVersionUID. Every class generated will now be serializable and have the specified uid: a limitation of this process is that each of your generated class will have the same uid.

<?xml version="1.0" encoding="UTF-8"?>
<bindings xmlns="http://java.sun.com/xml/ns/jaxb"
                xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance"
                xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
                xsi:schemaLocation="
http://java.sun.com/xml/ns/jaxb http://java.sun.com/xml/ns/jaxb/bindingschema_2_0.xsd"
    version="2.1">
    <schemaBindings>
        <package name="ch.frankel.blog.jaxb" />
    </schemaBindings>
    <globalBindings>
        <serializable uid="100" />
     </globalBindings>
</bindings>
Superclass

It is sometimes beneficial that all your bound classes inherit from a common class, one that is not described in the XSD. This may happen if this superclass is entirely for technical purpose (sucha as strong typing) and shouldn’t clutter the schema.

In order to do so, two actions are necessary:

  • enable the extended mode for the xjc compiler. Just add <extension>true</extension> under your configuration in the POM
  • use the superClass tag in the http://java.sun.com/xml/ns/jaxb/xjc namespace

This class won’t be generated by xjc so you are free to create it as you please (making it abstract, adding methods and so on).

<?xml version="1.0" encoding="UTF-8"?>
<bindings xmlns="http://java.sun.com/xml/ns/jaxb"
                xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance"
                xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
                xsi:schemaLocation="
http://java.sun.com/xml/ns/jaxb http://java.sun.com/xml/ns/jaxb/bindingschema_2_0.xsd"
    version="2.1">
    <schemaBindings>
        <package name="ch.frankel.blog.jaxb" />
    </schemaBindings>
    <globalBindings>
        <serializable uid="100" />
        <xjc:superClass name="ch.frankel.blog.jaxb.XmlSuperClass" />
    </globalBindings>
</bindings>

Data type

By default, xjc will bind the schema to the most precise data type available. For example, a XML-Schema date type will be bound to a Java javax.xml.datatype.XMLGregorianCalendar. This has the drawback of coupling your bound classes to the JAXB API and forcing you to use classes you don’t really need. For purpose of example, check how to convert a java.sql.Date from the database to your entity javax.xml.datatype.XMLGregorianCalendar: have fun!

To ease your development, you can provide both during binding and marshalling/unmarshalling adapters meant to pass to and from XML. This is declared as such in the bindings file:

<?xml version="1.0" encoding="UTF-8"?>
<bindings xmlns="http://java.sun.com/xml/ns/jaxb"
                xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance"
                xmlns:xs="http://www.w3.org/2001/XMLSchema"
                xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
                xsi:schemaLocation="
http://java.sun.com/xml/ns/jaxb http://java.sun.com/xml/ns/jaxb/bindingschema_2_0.xsd
http://www.w3.org/2001/XMLSchema http://www.w3.org/2001/XMLSchema.xsd"
    version="2.1">
    <bindings schemaLocation="schema.xsd">
        <schemaBindings>
            <package name="ch.frankel.blog.jaxb" />
        </schemaBindings>
        <globalBindings>
            <javaType name="java.util.Date" xmlType="xs:date"
                parseMethod="ch.frankel.blog.jaxb.JaxbConverter.parseDate"
                printMethod="ch.frankel.blog.jaxb.JaxbConverter.printDate" />
            <serializable uid="100" />
            <xjc:superClass name="ch.frankel.blog.jaxb.AbstractSuperClass" />
        </globalBindings>
    </bindings>
</bindings>

Notice you got another namespace to manage. This will generate an adapter class under the org.w3._2001.xmlschema package you’ll have to use during marshalling/unmarshalling process.

Tweaking the output

Not every information you’ll need in Java will be provided by the XML-Schema. What about compairing our objects with equals()?

Not every schema you’ll use will have been designed by you or your team. Some will be legacy, some will be standards… That doesn’t mean you should suffer for other’s lack of good practice. What if the schema uses uppercase tags? Surely, you want your generated classes to follow Sun coding conventions.

The Sun JAXB team provides plugins to the XJC compiler that resolve the above problems. Have a look at them.

For our example, we choose to add hashCode(), equals() and toString() methods to our generated class. A plugin exists to do just that. You only have to configure this generation in the POM, adding the wanted arguments to the compiler and adding the plugins needed to manage these arguments:

<configuration>
...
    <args>
        <arg>-XtoString</arg>
        <arg>-Xequals</arg>
        <arg>-XhashCode</arg>
    </args>
    <plugins>
        <plugin>
            <groupId>org.jvnet.jaxb2_commons</groupId>
            <artifactId>jaxb2-basics</artifactId>
            <version>0.5.0</version>
        </plugin>
     </plugins>
</configuration>

In this specific case, you’ll have to add two more dependencies (Commons Lang and JAXB Basics runtime) to your POM since the generated classes will depend on them:

<dependencies>
...
    <dependency>
        <groupId>commons-lang</groupId>
        <artifactId>commons-lang</artifactId>
        <version>2.4</version>
    </dependency>
    <dependency>
        <groupId>org.jvnet.jaxb2_commons</groupId>
        <artifactId>jaxb2-basics-runtime</artifactId>
        <version>0.5.0</version>
    </dependency>
</dependencies>

JAXB Persistence Bindings

To go even further and have a single entity able to be marshalled by JAXB and managed by your persistence layer, you can use the HyperJaxb product.

HyperJaxb2 cares about Hibernate managed persistence whereas HyperJaxb3 focuses on JPA managed persistence. The latter seems to be suffering from a lack of documentation, but the objective looks promising.

Conclusion

When reading from and writing to XML, one may be provided with a XML Schema. In this case, it is a good practice to bind the schema to Java. JAXB is the standard solution to achieve this. Yet, in many cases, the generated Java classes will be lacking some features: this shouldn’t be considered the end of the world, since the binding process can be customized to take many parameters into account.

You’ll find the sources for this article here.

To go further:

Ego Driven Architecture

June 15th, 2009 No comments

Whoever is in charge of software architecture, be they senior developers, whole teams like in agile practice or architects-per-se, it is a deep trend to apply what I like to call Ego Driven Architecture (or EDA for short, not to be mistaken with Event Driven Architecture).

When one has to choose an architecture, one should design it from a number of objective criteria, including:

  • business requirements,
  • technical constraints,
  • ease of use,
  • maintenance costs,
  • etc.

One could even argue you should take care of subjective yet real constraints:

  • cross-service warfare (between the development team and the productio team),
  • interpersonal problems (between a project manager and the lead developer),
  • historical bias (not using EJB3 because EJB2 where too complex to develop),
  • etc.

Normaly, each criterion is then assigned a priority, and the designed architecture’s objective is to answer the most criteria, based on their priority. Alas, when using EDA, the top priority criterion is completely different: whatever the constraints and the requirements, the technologies used on the project should make the CV of the architect(s) shine brighter.

If you already don’t know what I speak of, imagine an architect using EJB3 on a project though the production application server is not ready to run them yet. Or an architect pressing the production team to upgrade to the latest version of the application server, although there’s no real need to. I know you’ve already seen such behaviours.

There’re a number of factors that contribute to the thriving of  EDA:

  1. There’s no validation of projects architecture by a dedicated technical team. Either there’s no such cross-project team or it has no influence over architectural choices, due to the business funding (read power). Remember that since the money comes from the business, it is always very hard to tell them ‘no’.
  2. Architects in charge of the design are junior. They definitely want to put to good use what they read in articles posted on the Web. Not to offense anyone, but before using Scala and such, wouldn’t it be better if someone already had enough feedbacks?
  3. Architects are only hired for the time of the project. If your contribution stops when the project is shipped, it is a very big incentive to try unconventional technologies. Try talking with internal IS teams and you’ll find the ‘veni, vedi, vici‘ syndrom a top resentment cause for outsourcing since they usually end up cleaning the crap.

Still, the root cause of EDA is a miscalculation on the architect’s part. The IS world, even globalized, is very very finite. You always work with the same persons. If you practice EDA, sooner or later, you’ll find someone who will remember you for being the one who proposed the architecture who killed the project. Our work is complex enough taking every business requirement, every technical constraint, every service warfare into account without bringing the architect’s ego into the fray. So please, refrain from using EDA

This doesn’t mean you shouldn’t strive to use pertinent technologies in your architecture but it should be based on objective reasons, not you carreer.

Hibernate hard facts part 1

June 14th, 2009 6 comments

Hibernate LogoHibernate is a widely-used ORM framework. Many organizations use it across their projects in order to manage their data access tier. Yet, many developers working on Hibernate don’t fully understand the full measure of its features. In this serie of articles, I will try to dispel some common misunderstandings regarding Hibernate.

Updating a persistent object

A widely made mistake using Hibernate is to call the update() method on an already persistent object :

session.getTransaction().begin();

Person person = (Person) session.load(Person.class, 1L);

person.setLastName("FooBar");

session.update(person);

session.getTransaction().commit();

This will get you the following Hibernate outputs :

Hibernate: select person0_.id as id0_0_,
    person0_.birthDate as birthDate0_0_,
    person0_.FIRST_NAME as FIRST3_0_0_,
    person0_.LAST_NAME as LAST4_0_0_ from Person person0_ where person0_.id=?
Hibernate: update Person set birthDate=?, FIRST_NAME=?, LAST_NAME=? where id=?

Now remove the line numbered 7. You get exactly the same output! If you check the database, the result will be the same: calling update() does nothing since the object is already persistent. If you are in debug mode, you can even check that the output’s update line is called when commiting the transaction in both cases.

You will find proof of this assertion here.

JMX use cases

June 7th, 2009 1 comment

JMX is a Java standard shipped with the JDK since Java 5. Though it enables you to efficiently and dynamically manage your applications, JMX has seen very few productions uses. In this article, I will show you the benefits of using such a technology in a couple of use cases.

Manage your application’s configuration

Even though each application has different needs regarding configuration (one needing a initial thread number attribute, the other an URL), every application needs to be more or less parameterized. In order to do this, countless generations of Java developers (am I overdoing here?) have created two components:

  • the first one is a property file where one puts the name value pairs,
  • the other one is a Java class whose responsibilities are to load the properties in itself and to provide access to the values. This class should be a singleton.

This is good and fine for initialization, but what about runtime changes of those parameters? This is where JMX comes in. With JMX, you can now expose those parameters with read/write authorizations. JDK 6 provides you with the JConsole application, which can connect on JMX-enabled applications. Lets’s take a very simple example, with a configuration having only two properties: there will be one Configuration class and one interface named ConfigurationMBean in order to follow the JMX standard for Standard MBean. This interface will describe all methods available on the MBean instance:

public interface ConfigurationMBean {

    public String getUrl();

    public int getNumberOfThread();

    public void setUrl(String url);

    public void setNumberOfThread(int numberOfThread);
}

Now, you’ll only have to register the singleton instance of this class in you MBean server, and you have exposed your application’s configuration to the outside with JMX!

Manage your application’s Springified configuration

In Spring, every bean that is configured in the Spring configuration file can be registered to the JMX server. That’s it: no need to create an MBean suffixed interface for each class you want to expose. Spring does it for you, using the more powerful DynamicMBean and ModelMBean classes under the hood.

By default, Spring will expose all your public properties and methods. You can still control more precisely what will be exposed through the use of:

  • meta-datas (@@-like comments in the javadocs, thus decoupling your code from Spring API),
  • Spring Java 5 annotations,
  • classical MBean interfaces referenced in the Spring’s definition file,
  • or even using MethodNameBasedMBeanInfoAssembler which describes the interface in the Spring’s definition file.

More importantly, Spring provides your MBeans with notification provider support. This means every MBean will implement NotificationBroadcaster and thus be able to send notifications to subscribers, for example when you change a value to a property or when you call a method.

Following is a snippet for the previous Configuration, using Spring:

<bean id="genericCfg" class="ch.frankel.blog.jmx.GenericConfiguration" />
<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter">
    <property name="beans">
        <map>
            <entry key="bean:type=configuration,name=generic" value-ref="genericCfg" />
        </map>
    </property>
</bean>

Spring uses the MBean’s id to register it under the MBean server.

Change a logger’s level

Logging is a critical functionality since the dawn of software. Now, let’s say you are faced with the following problem: your application keeps throwing exceptions but what is traced is not enough for the developers to diagnose. Luckily, one of the developer did put some trace, but on a very primitive level. Unluckily, in production mode, it’s pretty sure you log only important events, mainly exceptions, not the debug informations that could be so useful here.

The first solution is to change the log level in the configuration file and the restart the application. Ouch, that’s a very crude way, one that won’t make many people happy (depending on the criticity and availability of the application).

Another answer is to use the abilities of the logging framework. For example, Log4J is the legacy logging framework. It provides a way to configure the framework with a configuration file and to listens to changes made to this file in order to reflect it in the in-memory configuration (the static configureAndWatch() method found in both DOMConfigurator and PropertyConfigurator).This runs fine if you have an external file but what about configuration files shipped with the archive? You can argue that Web archives are often deployed in exploded mode but you cannot rely on it.

JMX will prove to be handy for such a case: if you could have exposed your loggers logging level, you could change them at runtime. Since JDK 1.4, Java has an API to log messages. It offers JMX registration for free, so let’s use it. The only thing to do is create a logger for your class. In a business method, use the logger to trace at FINE level. Now using your JMX console, locate the MBean named java.util.logging:type=Logging.

Type Name Description
Attribute LoggerNames Array of all loggers configured
Operation getLoggerLevel Get the level of a logger The root logger is referenced by an empty string
Operation setLoggerLevel Set the level of a logger to a specified value

In order to activate the log, just set the level of the logger used by your class to the value you used in the code. In order to test this, I recomend to create a Spring bean from a Java class using the logger and exporting it to JMX with Spring (see above).

Flush your cache

For the data access layer, Hibernate is the most used framework at the time of this writing. Hibernate enables you to use caching. Hibernate’s first level caching (session cache) is done within Hibernate itself; Hibernate’s second level caching (transsession cache) is delegated to a 3rd party framework. Default framework is Ehcache: it is a very simple, yet efficient solution.

Let’s say some of your application’s table contain repository datas, that is data that won’t be changed by the application. These datas are by definition eligible for second-level caching. Now picture this: your application should be highly available (365/24/7) and the repositories just changed. How can you tell Ehcache to reload the tables in memory without restarting the application?

Luckily, Ehcache provides you with the way to do it. In fact, the net.sf.ehcache.management.Cache class implements the net.sf.ehcache.management.CacheMBean so you can call all of the interface methods: one of such method, aptly named removeAll() empties your cache. Just call it and Hibernate, not finding any data in the cache, will reload them from the database.

You will perhaps object you do not want all of your cache to be reinitialized: now you understand why you should separate your cache instances in the configuration (e.g. one for each table or one for repository datas and one for updatable datas).

Testing JMX

It is legitimate to want to test JMX while developing before bringing in the whole server infrastructure. JDK 6 provides you with the JConsole utility which displays the following informations on any application you can connect to (local and remote):

  • memory usage through time,
  • threads instances through time,
  • number of loaded classes through time,
  • summary of VM (including classpath and properties),
  • all your exposed MBeans.

JConsole MBean view

This view lets you view your MBeans attributes and call your MBeans operations, so this is a very valuable tool (for free). Now try it with a legacy application of yours: notice how many MBeans are registered. Guess you didn’t expect that!

In order to use this tool in development mode, do not forget to launch it with the following arguments (notice the -J):

  • -J-Dcom.sun.management.jmxremote.ssl=false
  • -J-Dcom.sun.management.jmxremote.authenticate=false
  • -J-Djava.class.path="${JDK_HOME}/jdk1.6.0_10/lib/jconsole.jar;${JDK_HOME}/lib/tools.jar;${ADDITIONNAL_CLASSPATH}

The last argument can be omitted in most cases (though this is not the case for managing EhCache).

You can find the sources for all the examples here.

To go further