Understanding Cassandra Code Base

Lately I’ve been adding some random small features to cassandra so I took the time to have a closer look at the internal design of the system.
While with some features added, such as an embedded service, I could have certainly get away without good understanding of the codebase and design, others, such as the truncate feature require good understanding of the various algorithms used, such as how writes are performed, how reads are performed, how values are deleted (hint: they are not…) etc.

The codebase, although isn’t very large, about 91136 lines, is quite dense and packed with algorithmic sauce, so simply reading through it just didn’t cut it for me. (I used the following kong-fu to count: $ cassandra/trunk $ find * -name *.java -type f -exec cat {} \;|wc -l)

I’m writing this post in hope it’d help others get up to speed. I’m not going to cover the basics, such as what is cassandra, how to deploy, how to checkout code, how to build, how to download thrift etc. I’m also not going to cover the real algorithmic complicated parts, such as how merkle trees are used by the ae-service, how bloom filters are used in different parts of cassandra (and what are they), how gossip is used etc. I don’t think I’m the right person to explain all this, plus there are already bits of those in the cassandra developer wiki. What I am going to write about is what was the path that I took in order to learn cassandra and what I’ve learned along the way. I haven’t found all that stuff documented somewhere else (perhaps I’ll contribute it back to the wiki when I’m done) so I think I’d be very helpful to have it next time I dive into a new codebase.

Lastly, a disclaimer: The views expressed here are simply my personal understanding of how the system works, they are both incomplete and inaccurate, so be warned. Keep in mind that I’m only learning and still sort of new to cassandra. Please also keep in mind that cassandra is a moving target and keeps changing so rapidly that any given snapshot of the code will get irrelevant sooner or later. By the time of writing this the currently official version is 0.6.1 but I’m working on trunk towards 0.7.0.

Here’s a description of the steps I took and things I learned.

Download, configure, run…

First you need to download the code and run unit tests. If you use eclipse, idea, netbeans, vi, emacs and what not, you want to configure it. That was easy. There’s more here.

Reading

Next you want to read some of the background material, depending on what part exactly you want to work on. I wanted to understand the read path, write path and how values are deleted, so I read the following documents about 5 times each. Yes, 5 times. Each. They are packed with information and I found myself absorbing a few more details each time I read. I used to read the document, get back to the source code, make sure I understand how the algorithm maps to the methods and classes, reread the document, reread the source code, read the unit tests (and run them, with a debugger) etc. Here are the docs.

http://wiki.apache.org/cassandra/ArchitectureInternals

SEDA paper

http://wiki.apache.org/cassandra/HintedHandoff

http://wiki.apache.org/cassandra/ArchitectureAntiEntropy

http://wiki.apache.org/cassandra/ArchitectureSSTable

http://wiki.apache.org/cassandra/ArchitectureCommitLog

http://wiki.apache.org/cassandra/DistributedDeletes

I also read the google BigTable paper and the fascinating Amazon’s Dynamo paper, but that was a long time ago. They are good as background material, but not required to understand actual bits of code.

Well, after having read all this I was starting to get a clue what can be done and how but I still didn’t feel I’m at the level of really coding new features. After reading through the code a few times I realized I’m kind of stuck and still don’t understand things like “how do values really get deleted”, which class is responsible for which functionality, what stages are there and how is data flowing between stages, or “how can I mark and entire column family as deleted”, which is what I really wanted to do with the truncate operation.

Stages

Cassandra operates in a concurrency model described by the SEDA paper. This basically means that, unlike many other concurrent systems, an operation, say a write operation, does not start and end by the same thread. Instead, an operation starts at one thread, which then passes it to another thread (asynchronously), which then passes it to another thread etc, until it ends. As a matter of fact, the operation doesn’t exactly flow b/w threads, it actually flows b/w stages. It moves from one stage to another. Each stage is associated with a thread pool and this thread pool executes the operation when it’s convenient to it. Some operations are IO bound, some are disk or network bound, so “convenience” is determined by resource availability. The SEDA paper explains this process very well (good read, worth your time), but basically what you gain by that is higher level of concurrently and better resource management, resource being CPU, disk, network etc.

So, to understand data flow in cassandra you first need to understand SEDA. Then you need to know which stages exist in cassandra and exactly does the data flow b/w them.

Fortunately, to get you started, a partial list of stages is present at the StageManager class:

public final static String READ_STAGE = "ROW-READ-STAGE";
public final static String MUTATION_STAGE = "ROW-MUTATION-STAGE";
public final static String STREAM_STAGE = "STREAM-STAGE";
public final static String GOSSIP_STAGE = "GS";
public static final String RESPONSE_STAGE = "RESPONSE-STAGE";
public final static String AE_SERVICE_STAGE = "AE-SERVICE-STAGE";
private static final String LOADBALANCE_STAGE = "LOAD-BALANCER-STAGE";

I won’t go into detail about what each and every stage is responsible for (b/c I don’t know…) but I can say that, in short, we have the ROW-READ-STAGE which takes part in the read operation, the ROW-MUTATION-STAGE which takes part in the write and delete operations, the AE-SERVICE-STAGE which is responsible for anti-entropy. This is not a comprehensive list of stages, depending on the code path you’re interested in, you may find more along the way. For example, browsing the file ColumnFamilyStore you’ll find some more stages, such as FLUSH-SORTER-POOL, FLUSH-WRITER-POOL and MEMTABLE-POST-FLUSHER. In Cassandra stages are identified by instances of the ExecutorService, which is more or less a thread pool and they all have all-caps names, such as MEMTABLE-POST-FLUSHER.

To visualize that I created a diagram that mixes both classes and stages. This isn’t valid UML, but I think it’s a good way to look at how data flows in the system. This is not a comprehensive diagram of all classes and all stages, just the ones that were interesting to me.


yUML source

Debugging

Reading through the code using a debugger, while running a unit-test is an awesome way to get things into your head. I’m not a huge fan of debuggers, but one thing they are good at is learning a new codebase by singlestepping into unit tests. So what I did was to run the unit-tests while single stepping into the code. That was awesome. I also ran the unit tests for Hector, which uses the thrift interface and spawn an embedded cassandra server so they were right to the point, user friendly and eye opening.

Class Diagrams

Next thing I did is use a tool to extract class diagrams from the existing codebase. That was not a great use of my time.

Well, the tool I used wasn’t great, but that’s not the point. The point is that cassandra’s codebase is written in such way that class diagrams help very little in understanding it. UML class diagrams are great for object oriented design. The essence of them is the list of classes, class members and their relationships. For example if a class A has a list of Bs, so you can draw that in a UML class diagram such that A is an aggregation of Bs and just by looking at the diagram you learn a lot. For example, an Airplane has a list of Passengers.

Cassandra is a complex system with solid algorithmic background and excellent performance, but, to be honest, IMO from the sole perspective of good oo practice, it isn’t a good case study… Its classes contain many static methods and members and in many cases you’d see one class calling other static method of another class, C style, therefore I found that class diagrams, although they are somewhat helpful at getting a visual sense of what classes exist and learn roughly manner about their relationships, are not so helpful.

I ditched the class diagrams and continued to the next diagram – sequence diagrams.

Sequence Diagrams

Sequence diagrams are great at abstracting and visualizing interactions b/w entities. In my case an entity may either be a class, or a STAGE, or a thrift client. Luckily with sequence diagrams you don’t have to be too specific and formal about the kind of entities are used in it, you just represent them all as happy actors (at least, I allow myself to do that, I hope the gods of UML will forgive).

The following diagrams were produced by running Hector’s unit tests and using an embedded cassandra server (single node). The diagrams aren’t generic, they describe only one possible code path while there could be many, but I preferred keeping them as simple as possible even in the cost of small inaccuracies.

I used a simple online sequence diagram editor at http://www.websequencediagrams.com to generate them.

Read Path

note left of CassandraServer: Read Path

CassandraServer -> StorageProxy: readProtocol
StorageProxy -> weakReadLocal: READ-STAGE.call

weakReadLocal -> SliceByNamesReadCommand: getRow
SliceByNamesReadCommand -> Table: getRow
Table -> ColumnFamilyStore: getColumnFamily
ColumnFamilyStore -> QueryFilter: collectCollatedColumns
QueryFilter -> ColumnFamilyStore:
ColumnFamilyStore -> ColumnFamilyStore: removeDeleted
ColumnFamilyStore -> Table:
Table -> SliceByNamesReadCommand:
SliceByNamesReadCommand -> weakReadLocal:

weakReadLocal -> StorageProxy:
StorageProxy -> CassandraServer:

Write Path

note left of CassandraServer: Write Path
CassandraServer -> StorageProxy: mutateBlocking

note over StorageProxy: async
StorageProxy --> StorageProxy: MUTATION-STAGE call
StorageProxy -> RowMutation: run

RowMutation -> Table: apply

note over Table, CommitLog: async
Table --> CommitLog: COMMIT-LOG-WRITER add
CommitLog -> CommitLogSegment: write
CommitLogSegment -> CommitLog: 

Table -> ColumnFamilyStore: apply
ColumnFamilyStore -> Memtable: put
Memtable -> Memtable: resolve
Memtable -> ColumnFamilyStore:
ColumnFamilyStore -> Table:
Table -> RowMutation:
RowMutation -> StorageProxy:
StorageProxy --> StorageProxy: signal
StorageProxy -> CassandraServer:

Table is a Keyspace

One final note: As user of cassandra I use the terms Keyspace, ColumnFamily, Column etc. However, the codebase is packed with the term Table. What are Tables?… As it turns out, a Table is actually a Keyspace… just keep this in mind, that’s all.

Learning the codebase was a large and satisfying task, I hope this writing helps you get up and running as well.


JMX in Hector

Hector is a Java client for Cassandra I’ve implemented and have written about before (here and here).

What I haven’t written about is its extensive JMX support, which makes it really unique, among other properties such as failover and really simple load balancing. JMX support in hector isn’t really new, but it’s the first time I have the chance to write writing about it.

JMX is Java’s standard way for monitoring applications. The default thrift cassandra client provides no JMX support at all so I figured you have to be crazy to run a cassandra client at such a high scale without being able to monitor it.

Here’s the list of JMX attributes provided by hector

WriteFail - Number of failed write operations.
ReadFail - Number of failed read operations
RecoverableTimedOutCount - Number of recoverable TimedOut
  exceptions. Those exceptions may happen when certain nodes
  are under heavy load that they can't provide the service
RecoverableUnavailableCount - Number of recoverable
  Unavailable exceptions
RecoverableTransportExceptionCount - Number of recoverable
  Transport exceptions
RecoverableErrorCount - Total number of recoverable errors.
SkipHostSuccess - Number of times that a successful skip-host
  (failover) has occurred.
NumPoolExhaustedEventCount - Number of times threads have
  encountered the pool-exhausted state (and were blocked)
NumPools - Number of connections pools.
  This is also the number of unique hosts in the
   ring that this client has communicated with.
  The number may be one or more, depending on the load balance
  policy and failover attempts.
PoolNames - The list of known pools
NumIdleConnections - Number of currently idle connections
  (in all pools)
NumActive - number of currently active connections (all pools)
NumExhaustedPools - Number of currently exhausted
  connection pools.
RecoverableLoadBalancedConnectErrors - Number of recoverable
  load-balance connection errors.
ExhaustedPoolNames - The list of exhausted connection pools.
NumBlockedThreads - Number of currently blocked threads.
NumConnectionErrors - Number of connection errors
  (initial connection to the ring for retrieving metadata)
KnownHosts - the list of known hosts in the ring.
  This list will be used by the client in case failover is required.
updateKnownHosts - This is an operation that may be invoked
   by an admin to tell the client to update its list of known hosts.
  Usually this is done after the ring configuration has changed.

Performance Counters: (I used the mechanics of perf4j to implement those)

READ.success_TPS - Total Read Transactions Per Second
  (measured as the average over the last 10 seconds).
READ.success_Mean - The Mean time of successful read requests
  over the last 10 seconds.
READ.success_Min - Time in millisec of the fastest successful
  read operation (over the last 10 seconds)
READ.success_Max - Time in millisec of the slowest read
  (over the last 10 seconds)
READ.success_StdDev - Standard deviation of time of successful read
  operations (over the last 10 seconds)
WRITE.success_TPS - Total write transactions per second over
  (over the last 10 seconds).
WRITE.success_Mean - ...
WRITE.success_Min
WRITE.success_Max
WRITE.success_StdDev
READ.fail_TPS
READ.fail_Mean
READ.fail_Min
READ.fail_Max
READ.fail_StdDev
WRITE.fail_TPS
WRITE.fail_Mean
WRITE.fail_Min
WRITE.fail_Max
WRITE.fail_StdDev

This looks like this in jconsole (ignore the zeros, it’s not real data…)


Load balancing and improved failover in Hector

Balance the load, woman!

I’ve added a very simple load balancing feature, as well as improved failover behavior to Hector. Hector is a Java Cassandra client, to read more about it please see my previous post Hector – a Java Cassandra client.

In version 0.5.0-6 I added poor-man’s load balancing as well as improved failover behavior.

The interface CassandraClientPool used to have this method for obtaining clients:

/**
 * Borrows a client from the pool defined by url:port
 * @param url
 * @param port
 * @return
 */
CassandraClient borrowClient(String url, int port)
    throws IllegalStateException, PoolExhaustedException, Exception;

Now with the added LB and failover it has:

/**
 * Borrow a load-balanced client, a random client from the array of given client addresses.
 *
 * This method is typically used to allow load balancing b/w the list of given client URLs. The
 * method will return a random client from the array of the given url:port pairs.
 * The method will try connecting each host in the list and will only stop when there's one
 * successful connection, so in that sense it's also useful for failover.
 *
 * @param clientUrls An array of "url:port" cassandra client addresses.
 *
 * @return A randomly chosen client from the array of clientUrls.
 * @throws Exception
 */
CassandraClient borrowClient(String[] clientUrls) throws Exception;

And usage looks like that:

// Get a connection to any of the hosts cas1, ca2 or cas3
CassandraClient client = pool.borrowClient(new String[] {"cas1:9160", "cas2:9160", "cas3:9160"});

So, when calling borrowClient(String[]) the method randomly chooses any of the clients in the array and connects to it. That’s what I call poor man’s load balancing, just plain dumb random, not real load balancing. By all means, true load balancing which takes into account performance measurements such as response time and throughput is infinitely better than the plain random selection I’m employing here and in my opinion should be left out for your ops folks to deal with and not to the program, however, if you only need a very simplistic approach of random selection, then this method may suite your needs.

A nice side effect of using this method is improved failover. In previous versions hector implemented failover, but in order to find out about the ring structure it had to connect to at least one host in the ring first and query it to learn about the rest. The result was that if a new connection is made and it’s so unfortunate that this new connections is made to unavailable host, then this new client cannot connect to the host to learn about other live hosts so it fails right away. With this new method which sends an array of hosts the client keeps connecting to hosts in the list in random order until it finds one that’s up. In the example above the client may choose to connect to cas2 first; if cas2 is down it’ll try to connect to (say) cas3 and if cas3 is also down it’ll try to connect to cas1; only if all three hosts are down will it give up and return an error. Failing to connect to hosts is considered an error, but a recoverable error, so it’s transparent to the client of hector but is reported to JMX and has its own special counter (RecoverableLoadBalancedConnectErrors).


Hector – a Java Cassandra client

UPDATE 3: Comments are closed now and for the sake of information reuse, please post all your hector questions to the mailing list hector-users@googlegroups.com and please subscribe to it as well.

UPDATE: I added a downloads section, so you may simply download the jar and sources if you’re not into git or maven.

UPDATE 2: I added license clarification; the license it MIT, which is the most permissive license I know of and basically lets you do anything with the software: use it commercially or uncommercially, copy it, fork it (but I’ll be happy to accept patches and committers) and whatnot. I added a LICENSE file and over time I’ll add that block of comment to every file.

In the Greek Mythology, Hector was the builder of Troy, the greatest warrior ever and brother of Cassandra.

Nowdays, Cassandra is a high scale database and Hector is the Java client I’ve written for it.

Over the last couple of days I got the the conclusion that the java client I’ve been using so far to speak to cassanrda wasn’t satisfactory. I used the one simply called cassandra-java-client, which is a good start but had some shortcomings I could just not live with (no support for Cassandra v0.5, no JMX and no failover). So I’ve written my own.

For anyone not familiar with cassanra, it’s client API is just a simple thrift client. This means that, unlike other datastore clients such as jdbc etc, the client provided has somewhat limiter functionality; It can sent messages to cassanra, write values and read values of course, but other client goodies required for large scale applications are not provided, features such as monitoring, connection pooling etc. The client I initially used provides connection pooling, which is a very nice start, but I decided it was missing too much so I’d write my own.

As a good open-source citizen, I initially contacted the authors of cassandra-java-client asking their permission to contribute and make the suggested improvements, but after weeks without reply I realized I’ll need to go solo. I started with the concepts captured by the folks who had built the java-client, but pretty soon the code has morphed to be something completely different.

Here’s how code that uses Hector looks like. This is an implementation of a simple distributed hashtable over cassandra. By the virtue of cassandra, this hashtable can grow pretty large:

  /**
   * Insert a new value keyed by key
   * @param key Key for the value
   * @param value the String value to insert
   */
  public void insert(final String key, final String value) throws Exception {
    execute(new Command(){
      public Void execute(final Keyspace ks) throws Exception {
        ks.insert(key, createColumnPath(COLUMN_NAME), bytes(value));
        return null;
      }
    });
  }
 
  /**
   * Get a string value.
   * @return The string value; null if no value exists for the given key.
   */
  public String get(final String key) throws Exception {
    return execute(new Command(){
      public String execute(final Keyspace ks) throws Exception {
        try {
          return string(ks.getColumn(key, createColumnPath(COLUMN_NAME)).getValue());
        } catch (NotFoundException e) {
          return null;
        }
      }
    });
  }
 
  /**
   * Delete a key from cassandra
   */
  public void delete(final String key) throws Exception {
    execute(new Command(){
      public Void execute(final Keyspace ks) throws Exception {
        ks.remove(key, createColumnPath(COLUMN_NAME));
        return null;
      }
    });
  }

Out of the box Cassanra provides a raw thrift client, which is OK, but lacks many features essential to real world clients. I’ve built Hector to fill this gap.

Here are the high level features of Hector, currently hosted at github.

  • A high-level object oriented interface to cassandra. As noted before, Cassandra’s out of the box client is a thrift client, which isn’t always that nice and clean to work with. I wanted to provide higher level and cleaner API. This part was mainly inspired by the mentioned cassandra-java-client. The API is defined in the Keyspace interface. See for example methods such as Keyspace.insert() and keyspace.getColumn()
  • Failover support. Cassandra is a distributed data store and it may handle very well one or several hosts going down. However, out of the box thrift provides no support for failing clients. What it the client is configured to connect a cassandra host that just happened to be down right now? In hector, if a client is connected to one host in the ring and this host goes down, the client will automatically and transparently search for other available hosts to perform its operation before giving up  and returning an error to its user. There are currently 3 ways to configure the failover policy: FAIL_FAST (no retry, just fail if there are errors, nothing smart), ON_FAIL_TRY_ONE_NEXT_AVAILABLE (try one more host before giving up) and ON_FAIL_TRY_ALL_AVAILABLE (try all available hosts before giving up). See CassandraClient.FailoverPolicy.
  • Connection pooling. This is a real necessity for high scale applications. The usual pattern for DAOs (Data Access Objects) is large number of small reads/writes. Clients cannot afford to open a new connection with each and every request, not only because of the overhead in the tcp handshake (thrift uses tcp), but also because of the fact that sockets remain in TIME_WAIT so a client may easily run out of available sockets if it operates fast enough. This part was also inspired by cassandra-java-client but was improved in my version. Hector provides connection pooling and a nice framework that manages all its gory details.
  • JMX support. It’s a widely known fact that applications have a life of their own. You built it to do X but it does Y b/c you didn’t expect Z to happen. Running an application without the ability to monitor it is like walking blindfolded on a dark highway; sooner or later you’ll get hit by something. Hector exposes JMX for many important runtime metrics, such as number of available connections, idle connections, error statistics and more.
  • Support for the Command design pattern to allow clients to concentrate on their business logic and let hector take care of the required plumbing. This is demonstrated in the code above.

I’ve been using hector internally, at outbrain and so far so good. I’d be happy to get the comminuty feedback – API, implementation, features and so on and hope you can find it useful.


Running Cassandra as an embedded service

While developing an application at outbrain, using Cassandra I was looking for a good way to test my app. The application consists of a Cassandra Client package, some Data Access Objects (DAOs) and some bean object that represent the data entities in cassandra. I wanted to test them all.

As unit test tradition goes, my requirement was zero-configuration, zero preparation, no external dependencies, full isolation, fully reproducible results and fast. Database testing has always been a challenge in this perspective, for example when testing SQL clients in java often HSQLDB is used to to mock the database. Cassandra, however, did not have something ready just yet so I had to build it.

One way to go was to setup a cassandra instance just for unit testing. There are many downsides to this approach, such as it’s not zero-configuration, tests need to cleanup before they execute, if two tests are run at the same time by two developers they can collide and change the results in unexpected way, it’s slow… out of the question, not good.

Enter the embedded cassandra server.

With the help of the community I’ve built an embedded cassandra service ideal for unit testing and perhaps other uses. I’ve also built a cleanup utility that helps wipe out all data before the service starts running so the combination of both provides isolation etc. Now each test process runs an in-process, embedded instance of cassandra.

Below is the source code, already committed to cassandra SCM on trunk. If you want to use it for the current stable release(0.5.0) only a small package rename is required (in trunk some classes moved a bit), and it’s presented at the end of the post.

The embedded service:

package org.apache.cassandra.service;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.io.util.FileUtils;
import org.apache.cassandra.thrift.CassandraDaemon;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
/**
 * An embedded, in-memory cassandra storage service that listens
 * on the thrift interface as configured in storage-conf.xml
 * This kind of service is useful when running unit tests of
 * services using cassandra for example.
 *
 
 * This is the implementation of https://issues.apache.org/jira/browse/CASSANDRA-740
 *
 
 * How to use:
 * In the client code create a new thread and spawn it with its {@link Thread#start()} method.
 * Example:
 *
 *      // Tell cassandra where the configuration files are.
        System.setProperty("storage-config", "conf");
 
        cassandra = new EmbeddedCassandraService();
        cassandra.init();
 
        // spawn cassandra in a new thread
        Thread t = new Thread(cassandra);
        t.setDaemon(true);
        t.start();
 
 *
 * @author Ran Tavory (rantav@gmail.com)
 *
 */
public class EmbeddedCassandraService implements Runnable
{
 
    CassandraDaemon cassandraDaemon;
 
    public void init() throws TTransportException, IOException
    {
        cassandraDaemon = new CassandraDaemon();
        cassandraDaemon.init(null);
    }
 
    public void run()
    {
        cassandraDaemon.start();
    }
}

The data cleaner:

package org.apache.cassandra.contrib.utils.service;
 
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
 
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.io.util.FileUtils;
 
/**
 * A cleanup utility that wipes the cassandra data directories.
 *
 * @author Ran Tavory (rantav@gmail.com)
 *
 */
public class CassandraServiceDataCleaner {
 
    /**
     * Creates all data dir if they don't exist and cleans them
     * @throws IOException
     */
    public void prepare() throws IOException {
        makeDirsIfNotExist();
        cleanupDataDirectories();
    }
 
    /**
     * Deletes all data from cassandra data directories, including the commit log.
     * @throws IOException in case of permissions error etc.
     */
    public void cleanupDataDirectories() throws IOException {
        for (String s: getDataDirs()) {
            cleanDir(s);
        }
    }
    /**
     * Creates the data diurectories, if they didn't exist.
     * @throws IOException if directories cannot be created (permissions etc).
     */
    public void makeDirsIfNotExist() throws IOException {
        for (String s: getDataDirs()) {
            mkdir(s);
        }
    }
 
    /**
     * Collects all data dirs and returns a set of String paths on the file system.
     *
     * @return
     */
    private Set getDataDirs() {
        Set dirs = new HashSet();
        for (String s : DatabaseDescriptor.getAllDataFileLocations()) {
            dirs.add(s);
        }
        dirs.add(DatabaseDescriptor.getLogFileLocation());
        return dirs;
    }
    /**
     * Creates a directory
     *
     * @param dir
     * @throws IOException
     */
    private void mkdir(String dir) throws IOException {
        FileUtils.createDirectory(dir);
    }
 
    /**
     * Removes all directory content from file the system
     *
     * @param dir
     * @throws IOException
     */
    private void cleanDir(String dir) throws IOException {
        File dirFile = new File(dir);
        if (dirFile.exists() && dirFile.isDirectory()) {
            FileUtils.delete(dirFile.listFiles());
        }
    }
}

And an example test that uses both:

package org.apache.cassandra.contrib.utils.service;
 
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
 
import java.io.IOException;
import java.io.UnsupportedEncodingException;
 
import org.apache.cassandra.service.EmbeddedCassandraService;
import org.apache.cassandra.thrift.Cassandra;
import org.apache.cassandra.thrift.ColumnOrSuperColumn;
import org.apache.cassandra.thrift.ColumnPath;
import org.apache.cassandra.thrift.ConsistencyLevel;
import org.apache.cassandra.thrift.InvalidRequestException;
import org.apache.cassandra.thrift.NotFoundException;
import org.apache.cassandra.thrift.TimedOutException;
import org.apache.cassandra.thrift.UnavailableException;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.junit.BeforeClass;
import org.junit.Test;
 
/**
 * Example how to use an embedded and a data cleaner.
 *
 * @author Ran Tavory (rantav@gmail.com)
 *
 */
public class CassandraServiceTest {
 
    private static EmbeddedCassandraService cassandra;
 
    /**
     * Set embedded cassandra up and spawn it in a new thread.
     *
     * @throws TTransportException
     * @throws IOException
     * @throws InterruptedException
     */
    @BeforeClass
    public static void setup() throws TTransportException, IOException,
            InterruptedException {
        // Tell cassandra where the configuration files are.
        // Use the test configuration file.
        System.setProperty("storage-config", "../../test/conf");
 
        CassandraServiceDataCleaner cleaner = new CassandraServiceDataCleaner();
        cleaner.prepare();
        cassandra = new EmbeddedCassandraService();
        cassandra.init();
        Thread t = new Thread(cassandra);
        t.setDaemon(true);
        t.start();
    }   
 
    @Test
    public void testInProcessCassandraServer()
            throws UnsupportedEncodingException, InvalidRequestException,
            UnavailableException, TimedOutException, TException,
            NotFoundException {
        Cassandra.Client client = getClient();
 
        String key_user_id = "1";
 
        long timestamp = System.currentTimeMillis();
        ColumnPath cp = new ColumnPath("Standard1");
        cp.setColumn("name".getBytes("utf-8"));
 
        // insert
        client.insert("Keyspace1", key_user_id, cp, "Ran".getBytes("UTF-8"),
                timestamp, ConsistencyLevel.ONE);
 
        // read
        ColumnOrSuperColumn got = client.get("Keyspace1", key_user_id, cp,
                ConsistencyLevel.ONE);
 
        // assert
        assertNotNull("Got a null ColumnOrSuperColumn", got);
        assertEquals("Ran", new String(got.getColumn().getValue(), "utf-8"));
    }
 
    /**
     * Gets a connection to the localhost client
     *
     * @return
     * @throws TTransportException
     */
    private Cassandra.Client getClient() throws TTransportException {
        TTransport tr = new TSocket("localhost", 9170);
        TProtocol proto = new TBinaryProtocol(tr);
        Cassandra.Client client = new Cassandra.Client(proto);
        tr.open();
        return client;
    }
}

To use this source code in v0.5.0 a small package rename is required:
org.apache.cassandra.io.util.FileUtils => org.apache.cassandra.utils.FileUtils
org.apache.thrift.transport.TTransportException => org.apache.transport.TTransportException
org.apache.cassandra.thrift.CassandraDaemon => org.apache.cassandra.CassandraDaemon

One nifty detail: When running multiple tests serially, make sure to spawn each test in a separate JVM (fork mode) since cassandra doesn’t shut down all threads immediately. Running each in separate jvm ensures the previous test dies before the next one begins.


Introduction to NOSQL and cassandra, part 2

In part 1 of this talk I presented few of the theoretical concepts behind nosql and cassandra.

In this talk we deep dive into the Cassandra API and implementation. The video is again in Hebrew, but the slides are multilingual ;-)

  • Started with a short recap of some of RDBMS and SQL properties, such as ADIC, why SQL if very programmer friendly, but is also limited in its support for large scale systems.
  • Short recap of the CAP theorem
  • Short recap of what N/R/W are
  • Cassandra Data Model: Cassandra is a column oriented DB which follows a similar data model to Google’s BigTable
  • Do you know SQL? So you better start forgetting it, Cassandra is a different game.
  • Vocabulary:
    • Keyspace – a logical buffer for application data. For example – Billing keyspace, or statistics keyspace, appX keyspace etc
    • ColumnFamily – similar to SQL tables. Aggregates columns and rows
    • Keys (or Rows). Each set of columns is identified by a key. A key is unique per Column Family
    • Columns – the actual values. Columns are represented by triplets – (name, value, timestamp)
    • Super-Columns – Facebook’s addition to the BigTable model SuperColumns are columns who’s values is a list of Columns. (but this is not recursive, you can only have one level of super-columns)
  • One way to think of cassandra is as a key-value store, but with extra functionality:
    • Each key has multiple values. In Cassandra jargon those are Columns
    • When reading or writing data it’s possible to read/write a set of columns for one specific key (row) atomically. This set of columns may either be a specified by the list column names, or by a slice predicate, assuming the columns are sorted in some way (that’s a configuration parameter)
    • In a addition, a multi-get operation is supported and a row-range-read operation is supported as well.
    • Row-range-read operations are supported only of a partitioner is defined which supports that (configuration parameter)
  • Key concept: In SQL you add your data first and then retrieve it in ad-hoc manner using select queries and where clauses; In Cassandra you can’t do that. Data can only be retrieved by it’s row key, so you have to think about how you’re going to be reading your data before you insert it. This is a conceptual diff b/w SQL and Cassandra.
  • I covered the Cassandra API methods:
    • get
    • get_slice
    • multiget
    • multiget_slice
    • get_count
    • get_range_slice
    • insert
    • batch_insert
    • delete
    • (these are the 0.4 api method. In 0.5 it’s a little different)
  • Between N/R/W, N is set per keyspace; R is defined per each read operation (get/multiget/etc) and W is defined per write operation (insert/batch_insert/delete)
  • Applications play with their R/W values to get different effects, for example they use QUORUM to get high consistency levels, or DC_QUORUM for a balance of high consistency and performance, W=0 to have async writes with reduced consistency.
  • Cassandra defines different sorting orders on it’s columns. Sort order may be defined at the ColumnFamily level and is used to get a slice of columns, for example, read all columns that start with a… and end with z…
  • There are several out of the box sort types, such as ascii, utf, numeric and date; Applications may also add their own sorters; This is as far as I recall the only place where Cassandra allows external code to be hooked in.
  • Thrift is a protocol and a library for cross-process communication and is used by Cassandra. You define a thrift interface and then compile it to the language of your choosing – C++, Java, Python, PHP etc. This makes it very easy for cross-language processes to talk to each other.
  • Thrift is also very efficient serializing and  deserializing objects and is also space-efficient (much more than Java serialization is).
  • I did not have enough time to cover the Gossip protocol used by Cassandra internally to learn about the health of its hosts.
  • I also did not have enough time to cover the Repair-on-reads algorithm used by Cassandra to repair data inconsistencies lazily.
  • I did not have time to talk about consistent hashing, which is what cassandra implements internally to reduce overhead of joined or dropped hosts occurrences.

So, as you can see, this was an overloaded, 1h+ talk with a lot to grasp. Wish me luck implementing Cassandra into outbrain!


Maven Code Quality Dashboard and TeamCity

I’ve recently implemented a code-quality dashboard at outbrain for maven java projects and hooked it into the our TeamCity continuous integration server. I was very pleased with the result, but the process had a few hickups, so I thought I’d mention them here for future generations.

A code quality dashboard includes the following components:

  • Tests status – failed, passed and  skipped count along with good looking graphs
  • Code coverage report detailing all covered and uncovered lines and branches, including nice coverage graphs
  • Copy-Paste detection by CPD
  • FindBugs report
  • jDepend report

The process had two phases: phase one is where I add the dashboard report to maven’s site goal in my pom.xml and phase two is where I make this report available at TeamCity, which is a bit of a manual work bot not too bad.

To add those nice reports, edit your pom.xml to add:

  <reporting>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>cobertura-maven-plugin</artifactId>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-pmd-plugin</artifactId>
        <version>2.3</version>
        <configuration>
          <linkXref>true</linkXref>
          <targetJdk>1.5</targetJdk>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-report-plugin</artifactId>
        <version>2.4.2</version>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>jdepend-maven-plugin</artifactId>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>findbugs-maven-plugin</artifactId>
        <version>2.0.1</version>
        <configuration>
          <xmlOutput>true</xmlOutput>
          <effort>Max</effort>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>dashboard-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </reporting>

Now, in theory, that would have been all. All you have to do is run mvn site and bang – you have the reports under target/site. That’s why maven is nice.

However, if you’re running a multi-module project then mvn-site is buggy… all links to the subproject are broken links. But no despair, here’s the solution – configure the site plugin to place its generated content where the site plugin expects it to be… yeah, I know it sounds confusing, the thing is that the site plugin has a bug so it’s links to the submodule projects are broken, but here’s an easy fix that worked for me (as long as the projects are only one directory deep under the parent pom.xml). In the parent pom.xml add:

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-site-plugin</artifactId>
        <configuration>
          <outputDirectory>../target/site/${project.name}</outputDirectory>
        </configuration>
      </plugin>

Now the reports are fixed.

Next step is to add them into TeamCity.

Step one: Tell teamcity to collect the site artifacts (html, css, js…). Go to the build configuration and under Artifacts Paths add **/target/site/**/*

Step two: Add a Code Quality tab to the build results. You do that by ssh-ing to the teamc host and editing

vi /teamc/TeamCity/.BuildServer/config/main-config.xml

to add

<report-tab title="Code Quality" basePath="target/site/" startPage="dashboard-report-details.html" />

Here’s the result:

That’s it! Now run your build with mvn site and get those gorgeous looking reports right in your teamcity build results page.


Moved hosting away from #godaddy #sucks


This blog has moved away from GoDaddy hosting to bluehost. I don’t know how good bluehost is (so far it’s been OK) but I know for sure that GoDaddy is pretty darn awful.

Awful as in
  • So slow that it’s a nightmare to be editing posts online. I had to do them offline and then copy-paste (and reformat), what a waste of time.
  • So fragile that my pingdom monitor reports it unavailable for more than 5 minutes at least twice a day.
  • So unresponsive that I’m sometimes ashamed to share permalinks to my blog in fear it would be offline. Why did I even pay them?

I didn’t wait for the one year I paid up front to end, just packed my stuff and moved over to bluehost. I don’t know how good bluehost is, but at least it’s fun again to be editing online and my pingdom monitor hasn’t told me anything bad yet, so knock on wood, looking good so far.


Introduction to NOSQL and cassandra, part 1

I recently gave a talk at outbrain, where I work, about an introduction to no-sql and Cassandra as we’re looking for alternatives of scaling out our database solution to match our incredible growth rate.

NOSQL is a general name for many non relational databases and Cassandra is one of them.

This was the first session of two in which I introduced the theoretical background and explained few of the important concepts of nosql. In the second session, due next week, I’ll talk more specifically about Cassandra.

The talk is on youtube, video below, but it’s in Hebrew so I’ll share it’s outline in English here. Slides are enclosed as well.


  • SQL and relational DBs in general offer is a very good general purpose solution for many  applications such as blogs, banking, my cat’s site etc.
  • RDBMS provide ACID: Atomicity, Consistency, Isolation and Durability
  • RDBMS + SQL (the query language) + ACID provide a very nice and clean programming interface, suitable for banks, online merchants and many other applications, but not all applications really actually do require full ACID and one has to realize that ACID and SQL features are not without costs when systems need to scale out. Cost is not only in $$, it’s also in application performance and features.
  • The new generation of internet scale applications put very high demands on DB systems when it comes to scale and speed of operation but they don’t necessariry require all the good that’s in RDBMS, such as Full Consistency or Atomicity.
  • So, a new brand of DB systems has grown over the past 5 or so years – nosql, which either stands for No-SQL or Not-Only-SQL.
  • Leading actors in the nosql arena are Google with its BigTable, Amazon with Dynamo, Facebook with Cassandra and there’s more.
  • I presented intermediate solutions before going no-sql, namely RDBMS sharding which is very common and FriendFeed’s particularly interesting solution of application level indexing for using mysql with a schema-less data model.
  • CAP Theorem: At large scale systems you may only choose 2 out of the 3 desired attributes: Consistency, Availability and Partition-Tolerance. All three may not go hand in hand and application designers need to realize that.
  • A Consistent and Available system with no Partition-tolerance is a RDBMS system that comes to a halt if one of it’s hosts is down. That’s a very commonly used solution and perfect for small systems. This blog, for example, which uses Wordpress, also uses a single mysql server which, if happens to be down, will also take the blog down. However, for internet scale systems where at almost any point in time there’s a good chance that one of the nodes is either down, or there are network disruptions, the No-Partition-Tolerance approach just isn’t going to cut it and they will have to choose a different approach for providing their SLAs.
  • Systems that are Available at all times and are capable of handling Partitions must sacrifice their consistency. As it turns out, though, this isn’t bad as it seems, as there are pretty good alternatives for lower levels of consistently, one such solution is Eventual Consistency, which actually works pretty nicely for “social applications” such as Google’s Facebook’s and Outbrain’s
  • I introduced the concept of NRW – N is the number of database replicas data is copied to one must replicate data in order to withstand partitions. W is the number of replicas a write operation would block on until it returns to it’s caller and is “successful” and R is the number of replicas a read operation would block on before returning to its caller.
  • N, R and W are crucial when dealing with Eventual Consistency as their values usually determine the level of consistency you’re going to have. For example, when N=R=W you have a full consistency (which isn’t tolerant to partitions or course). When W=0 you have async writes, which is the lowest level of consistency (you never know when the write operation actually finishes)
  • I introduced the concept of Quorum, which means R=W=ceil((N+1)/2)
  • Introduced a (very partial) list of currently available nosql solutions, such as Cassandra, BigTable, HBase, Dynamo, Voldemort, Riak, CouchDB, MongoDB and more.

Overall this was a very interesting talk, a lot of (fun and interesting) theory. The next part is going to be specific about Cassandra – how all this theory fits into Cassandra and how does one use Cassandra’s API, so stay tuned.


StringTemplate – a step forward to a better web MVC

MVCMVC, Model View Controller is a well known design patten from the field of UI frameworks. It advocates the separation of a Model, an application specific data and business logic, Controller, which takes user input, consults the model and determines the correct view to present a user based on its result and a View, the actual UI component the user interacts with.

In the context of web applications it’s common to consider a Database along with the application business logic as the Model, a web framework, such as Struts, as the Controller and the rendering engine, such as JSP as the View. MVC are widely used in both web development as well as in desktop application development.

StringTemplate is a rendering engine, a View, I’ve recently became familiar with and immediately fell in love with. StringTemplate is a step forward true MVC implementation, but before presenting the solution, let’s see what the problem is.

The MVC design pattern states that in a UI framework there should be 3 components – the Model, the View and the Controller. It also states that the Controller should have direct access to the Model and the View, the View have direct access to the Model when presenting the data as seen in the diagram below.

MVC diagram

There are many MVC implementations in many languages. In Java only, there are more than 17 mentioned on the Wiki page. Many of the frameworks use JSP as their rendering engine and add their specific features to it, so for example struts2 implements a very nice controller and as a rendering engine uses JSP with either struts2 tags or another tag library. The problem lies within JSP.

JSP, similar to PHP, ASP and many other simple and fast-start rendering engines, compromise the MVC model; they allows too much in their View component.

JSP allows code to be executed within the context of the page (using the <% %> notation), which is very nice when you want to hack something fast but is extremely dangerous from code maintenance perspective and is a clear violation of the MVC agreement. If code can be executed within a page, that code can easily alter the model or take actions a controller should have taken. A View should be able to READ the model, but not ALTER it. Even the most disciplined programmers who adhere to clean JSP code by not allowing actual Java code inside their pages (using the <% %>) actually suffer from the same problem without even knowing it… The alternative to the <%  and the <%= constructs are tags, such as JSTL tags, struts2 tags etc. These tags commonly access the model by invoking its getters, but the real problem with them is that the order in which they execute is very important – read it again – the order in which they are displayed on the page is crucial to the correctness of the values returned by their backing model. More about this here. So with JSP, when using tags, the View implementor has to understand how a Model works in order to succeed. That’s both inconsistent with the pure MVC model and inconvenient to the UI designer. Lastly are side effect, which cannot be ignored. Views can create side effects by calling methods (even getters can have side effects!) , which I think there’s no need to mention, is very bad.

StringTemplate comes to the rescue. As a matter of fact, when I programmed django MVC in python, as well as Cheetah in python, I have to say that both MVCs were much stricter than JSP and were therefore a lot more programmer-friendly. But in Java we had Velocity, which is strict, but also less powerful and now we have StringTemplate which is both strict and powerful. (and no – freemarker isn’t any better than just plain JSP, sorry).

At outbrain we use struts2 as our MVC driver and so to be able to use StringTemplate as the View engine I’ve implemented a struts2 View Renderer. Full code and details below. This code is “unstable” which means it’s been developed and tested, so far no bugs or missing features, but hasn’t gone to production yet.

struts.xml:

<struts>
<include file="webwork-default.xml" />
<package name="regular" namespace="/" extends="struts-default">
<result-types>
<result-type name="stringtemplate" class="org.apache.struts2.dispatcher.StringTemplateResult"/>
</result-types>
<action name="st" class="com.mysite.StringTemplateTestAction">
<result name="success" type="stringtemplate">/WEB-INF/st/page.st</result>
</action>
</package>
</struts>
Java source code:
package org.apache.struts2.dispatcher;
 
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
 
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import org.antlr.stringtemplate.NoIndentWriter;
import org.antlr.stringtemplate.StringTemplate;
import org.antlr.stringtemplate.StringTemplateGroup;
import org.antlr.stringtemplate.StringTemplateWriter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsConstants;
import org.apache.struts2.views.util.ContextUtil;
import org.apache.struts2.views.util.ResourceUtil;
 
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.LocaleProvider;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.ValueStack;
 
import freemarker.template.Configuration;
import freemarker.template.TemplateException;
 
/**
 * Defines the StringTemplate result type for struts2.
 *
 * To use this result type add the following configuration to your struts.xml:
 *
 * <code>
 * &lt;result-types&gt;
 *   &lt;result-type name="stringtemplate"
 *       class="org.apache.struts2.dispatcher.StringTemplateResult"/&gt;
 * &lt;/result-types&gt;
 *</code>
 *
 * Template files should be located relative to /WEB-INF/st/, so for example a common layout
 * would be:
 *
<ul>
 *
	<li>/WEB-INF/st/pages/page1.st</li>
*
	<li>/WEB-INF/st/layouts/layout1.st</li>
*
	<li>/WEB-INF/st/snippets/header.st</li>
*
	<li>/WEB-INF/st/snippets/footer.st</li>
*</ul>
*
 * So page1.st would look like:
 * <code>
 * $layouts/layout1(header=snippets/header(), footer=snippets/footer())$
 * </code>
 *
 * And the associated struts action would be:
 *
 * <code>
 * &lt;action name="page1"
 *      class="com.mycompany.Page1Action"&gt;
 *        &lt;result name="success"
 *          type="stringtemplate"&gt;/WEB-INF/st/pages/page1.st&lt;/result&gt;
 * &lt;/action&gt;
 * </code>
 *
 * Localization:
 * All string property files should be packed into the classpath (in one of the jars) at
 * /lang/.
 * For example:
 *
<ul>
 *
	<li>/lang/en_US.properties</li>
*
	<li>/lang/fr_FR.properties</li>
*</ul>
*
 * @author Ran Tavory (ran@outbrain.com)
 *
 */
public class StringTemplateResult extends StrutsResultSupport {
 
  /**
   * Base path of StringTemplate template files.
   * This is usually something like /WEB-INF/ or /WEB-INF/st/.
   * Must end with /.
   * All templates should reside in subdirectories of this base path and when referencing
   * each other the reference point should be relative to this path.
   * For example, if you have /WEB-INF/pages/page1.st and /WEB-INF/layouts/layout1.st, and assuming
   * the base path is at /WEB-INF then page1 is pages/page1 and layout1 is layouts/layout1.
   * To reference layout1 from page1: $layouts/layout1()$
   */
  public static final String TEMPLATES_BASE =
      "/WEB-INF/st/";
 
  /**
   * Path to the language resource files within the classpath.
   *
   * Resource should be packed inside a jar under /lang/.
   * For example: /lang/en_US.properties
   */
  public static final String LANG_RESOURCE_BASE = "/lang/";
 
  /**
   * If there was an exception during execution it's accessible via $exception$
   */
  public static final String KEY_EXCEPTION = "exception";
 
  /**
   * Session values are accessible via $session.key$
   */
  public static final String KEY_SESSION = "session";
 
  /**
   * All localized strings are accessible via $strings.string_key$
   */
  public static final String KEY_STRINGS = "strings";
 
  /**
   * Request parameters are accessible via $params.key$
   */
  public static final String KEY_REQUEST_PARAMETERS = "params";
 
  /**
   * Request attributes are accessible via $request.attribute$
   */
  public static final String KEY_REQUEST = "request";
 
  private static final Log log = LogFactory.getLog(StringTemplateResult.class);
 
  private static final long serialVersionUID = -2390940981629097944L;
 
  private static final Locale DEFAULT_LOCALE = Locale.US;
 
  /*
   * Struts results are constructed for each result execution
   *
   * the current context is available to subclasses via these protected fields
   */
  private String contentType = "text/html";
 
  private String defaultEncoding;
 
  public StringTemplateResult() {
    super();
  }
 
  public StringTemplateResult(String location) {
    super(location);
  }
 
  public void setContentType(String aContentType) {
    contentType = aContentType;
  }
 
  /**
   * allow parameterization of the contentType the default being text/html
   */
  public String getContentType() {
    return contentType;
  }
 
  @Inject(StrutsConstants.STRUTS_I18N_ENCODING)
  public void setDefaultEncoding(String val) {
    defaultEncoding = val;
  }
 
  /**
   * Execute this result, using the specified template location.
   *
 
   * The template location has already been interpolated for any variable
   * substitutions.
   *
   * NOTE: The current implementation is still under development and has several restrictions.
   *
<ul>
   *
	<li>All template files must end with .st</li>
*</ul>
*/
  public void doExecute(String location, ActionInvocation invocation) throws IOException,
      TemplateException {
 
    final HttpServletRequest request = ServletActionContext.getRequest();
    final HttpServletResponse response = ServletActionContext.getResponse();
 
    if (!location.startsWith("/")) {
      // Create a fully qualified resource name.
      // final ActionContext ctx = invocation.getInvocationContext();
      final String base = ResourceUtil.getResourceBase(request);
      location = base + "/" + location;
    }
 
    final String encoding = getEncoding(location);
    String contentType = getContentType(location);
 
    if (encoding != null) {
      contentType = contentType + ";charset=" + encoding;
    }
 
    response.setContentType(contentType);
 
    final String basePath = ServletActionContext.getServletContext().getRealPath(TEMPLATES_BASE);
    final StringTemplateGroup group = new StringTemplateGroup("webpages", basePath);
    String fileName = location;
    if (fileName.endsWith(".st")) {
      // If filename ends with .st, remove it.
      fileName = fileName.substring(0, fileName.length() - ".st".length());
    }
    if (fileName.startsWith(TEMPLATES_BASE)) {
      // If filename includes the base dir then remove it.
      fileName = fileName.substring(TEMPLATES_BASE.length());
    }
    final StringTemplate template = group.getInstanceOf(fileName);
 
    final Map model = createModel(invocation);
    template.setAttributes(model);
 
    // Output to client
    final Writer responseWriter = response.getWriter();
    final StringTemplateWriter templateWriter = new NoIndentWriter(responseWriter);
    template.write(templateWriter);
    // Flush'n'close
    responseWriter.flush();
    responseWriter.close();
  }
 
  /**
   * Retrieve the encoding for this template.
   *
   * People can override this method if they want to provide specific encodings
   * for specific templates.
   *
   * @return The encoding associated with this template (defaults to the value
   *         of 'struts.i18n.encoding' property)
   */
  protected String getEncoding(String templateLocation) {
 
    String encoding = defaultEncoding;
    if (encoding == null) {
      encoding = System.getProperty("file.encoding");
    }
    if (encoding == null) {
      encoding = "UTF-8";
    }
    return encoding;
  }
 
  /**
   * Retrieve the content type for this template.
   *
   * People can override this method if they want to provide specific content
   * types for specific templates (eg text/xml).
   *
   * @return The content type associated with this template (default
   *         "text/html")
   */
  protected String getContentType(String templateLocation) {
    return "text/html";
  }
 
  /**
   * Build the instance of the ScopesHashModel, including JspTagLib support
   *
   * Objects added to the model are
   *
   *
<ul>
   *
	<li>Application - servlet context attributes hash model</li>
*
	<li>JspTaglibs - jsp tag lib factory model</li>
*
	<li>Request - request attributes hash model</li>
*
	<li>Session - session attributes hash model</li>
*
	<li>request - the HttpServletRequst object for direct access</li>
*
	<li>response - the HttpServletResponse object for direct access</li>
*
	<li>stack - the OgnLValueStack instance for direct access</li>
*
	<li>ognl - the instance of the OgnlTool</li>
*
	<li>action - the action itself</li>
*
	<li>exception - optional : the JSP or Servlet exception as per the servlet
   * spec (for JSP Exception pages)
   *</li>
*
	<li>struts - instance of the StrutsUtil class
   *</li>
*</ul>
*/
  protected Map createModel(ActionInvocation invocation) {
 
    ServletContext servletContext = ServletActionContext.getServletContext();
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();
    ValueStack stack = ServletActionContext.getContext().getValueStack();
 
    Object action = null;
    if (invocation != null) {
      action = invocation.getAction();
    }
    return buildTemplateModel(stack, action, servletContext, request, response, invocation);
  }
 
  private Map buildTemplateModel(ValueStack stack, Object action,
                                                 ServletContext servletContext,
                                                 HttpServletRequest request,
                                                 HttpServletResponse response,
                                                 ActionInvocation invocation) {
 
    Map model = buildScopesHashModel(servletContext, request, response, stack);
    populateContext(model, stack, action, request, response);
    populateStrings(model, deduceLocale(invocation));
    return model;
  }
 
  /**
   * Populates the <code>strings</code> attribute of the model according to the current locale
   * value.
   * @param model
   * @param local
   */
  private void populateStrings(Map model, Locale locale) {
    log.debug("Local: " + locale);
    Properties p;
    try {
      p = getLanguageProperties(locale);
      model.put(KEY_STRINGS, p);
      return;
    } catch (IOException e) {
      if (locale.equals(DEFAULT_LOCALE)) {
        log.error("Unable to load language file for the default locale " + locale);
        return;
      } else {
        log.warn("Unable to load language file for " + locale + ". Will try to load for the " +
            "default locale");
      }
    }
 
    // Try once again with the default locale.
    populateStrings(model, DEFAULT_LOCALE);
  }
 
  /**
   * Tries to load language properties for the given locale.
   *
   * The file is loaded from /LANG_RESOURCE_BASE/locale.properties in the classpath, so for example
   * that may be /lang/en_US.properties
   *
   * @param locale
   * @return
   * @throws IOException When the language file isn't found or can't read it.
   */
  private Properties getLanguageProperties(Locale locale) throws IOException {
    final InputStream in =
      getClass().getClassLoader().getResourceAsStream(LANG_RESOURCE_BASE + locale + ".properties");
    final Properties prop = new Properties();
    prop.load(in);
    return prop;
  }
 
  protected Map buildScopesHashModel(ServletContext servletContext,
                                                     HttpServletRequest request,
                                                     HttpServletResponse response,
                                                     ValueStack stack) {
 
    Map model = new HashMap();
 
    // Add session information
    HttpSession session = request.getSession(false);
    if (session != null) {
      model.put(KEY_SESSION, generateAttributeMapForSession(session));
    }
 
    // Add requests attributes
    model.put(KEY_REQUEST, generateAttributeMapFromRequest(request));
 
    // Add request parameters.
    model.put(KEY_REQUEST_PARAMETERS, request.getParameterMap());
 
    return model;
  }
 
  @SuppressWarnings("unchecked")
  private Map generateAttributeMapForSession(HttpSession session) {
 
    Map attributes = new HashMap();
    for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) {
      String name = (String) e.nextElement();
      attributes.put(name, session.getAttribute(name));
    }
    return attributes;
  }
 
  @SuppressWarnings("unchecked")
  private Map generateAttributeMapFromRequest(HttpServletRequest request) {
 
    Map attributes = new HashMap();
    for (Enumeration e = request.getAttributeNames(); e.hasMoreElements();) {
      String name = (String) e.nextElement();
      attributes.put(name, request.getAttribute(name));
    }
    return attributes;
  }
 
  @SuppressWarnings("unchecked")
  protected void populateContext(Map model, ValueStack stack, Object action,
                                 HttpServletRequest request, HttpServletResponse response) {
 
    // put the same objects into the context that the velocity result uses
    Map standard = ContextUtil.getStandardContext(stack, request, response);
    model.putAll(standard);
 
    // Support for JSP exception pages, exposing the servlet or JSP exception
    Throwable exception = (Throwable) request.getAttribute("javax.servlet.error.exception");
    if (exception == null) {
      exception = (Throwable) request.getAttribute("javax.servlet.error.JspException");
    }
 
    if (exception != null) {
      model.put(KEY_EXCEPTION, exception);
    }
 
    // Add action model.
    if (action instanceof StringTemplateAction) {
      StringTemplateAction stAction = (StringTemplateAction) action;
      model.putAll(stAction.getModel());
    }
  }
 
  /**
   * Returns the locale used for the
   * {@link Configuration#getTemplate(String, Locale)} call. The base
   * implementation simply returns the locale setting of the action (assuming
   * the action implements {@link LocaleProvider}) or, if the action does not
   * the {@link #DEFAULT_LOCALE}
   */
  protected Locale deduceLocale(ActionInvocation invocation) {
 
    if (invocation.getAction() instanceof LocaleProvider) {
      return ((LocaleProvider) invocation.getAction()).getLocale();
    } else {
      return DEFAULT_LOCALE;
    }
  }
}
 
package org.apache.struts2.dispatcher;
 
import java.util.Map;
 
/**
 * Interface defining the required behavior from a StringTemplate result type.
 *
 * The result should prepare the model for the page to display.
 * The model is a map of attributes -&gt; Objects where each object may either be a simple string, int,
 * etc or another map.
 * So. for example $username$ is accessible from the template of the model contains a String under
 * the value "username" and $strings.hello$ is accessible if the model contains a map under the key
 * "strings" and this map contains an attribute under the key "hello"
 *
 * @author Ran Tavory (ran@outbrain.com)
 *
 */
public interface StringTemplateAction {
 
  /**
   * Get the root of the display model.
   *
   * The display model is a map of attributes interpolated by StringTemplate at runtime by
   * substituting the $values$ in the template source.
   * For example to replace $user$ with Ran add
   * <code>map.put("user", "Ran");</code>
   * @return A map of attributes used by StringTemplate to replace in the template.
   */
  public Map getModel();
}