Kanban at Mindcandy

Operations & Agile Kanban

Here at Mind Candy we use an Agile development process called Scrum, and it suits our business needs very well. But this suits the development process and not IT operations. Because we find it hard to commit to a two week sprint,  iterations don’t make too much sense. Our work is a mix of reactive & proactive maintenance, and mostly we are working on whatever is most urgent for the day/week. Yes, we do work on infrastructure projects which are more iterative, but team members aren’t dedicated to projects, so they could still get pulled off project tasks to deal with any urgent issues.

We needed a workflow that was more adaptive but complimented the Agile processes we already had in place. Welcome to the world of Kanban.

I’m not going to go into explaining Kanban in detail given that there is an excellent article already written by Henrik Kniberg and Mattias Skarin. This can be downloaded here http://www.infoq.com/minibooks/kanban-scrum-minibook.

When deciding to use Kanban, some of the key differences were really important for this to work for our team.

  • Timeboxed iterations are optional & tasks on the board can be event driven

  • Estimation of time to complete is optional

  • A Kanban board is persistent & not reset every sprint

  • We can add and remove tasks from the board as capacity or business needs change

  • Tasks can easily feed in from different development teams on diverse projects

  • We can prioritise our own work alongside other parts of the business.

Backlog

If you use Scrum you will have a backlog of tasks that needs to be prioritised & fed into the next Sprint. You will need to estimate points/time for each story & break them down into smaller tasks that you can complete within one iteration. For Kanban you can have a prioritization scheme or just go with the flow. You may or may not have a backlog, but here we use Jira* and we feed the backlog for the week from this. Users can raise tickets and set importance using the defined Jira priority scheme. However, not all tasks have to be in Jira, for example frequent maintenance tasks, quick fire issues & deploys can be added to the board directly. Priorities are negotiable and I will arbitrate between teams.

 *At the time of adopting KanBan we were still using Trac before moving to Jira. Greenhopper is mentioned later on.

The Board

A Kanban board doesn’t look much different to a Scrum board and in basic form has a ‘To do’, Work In Progress (WIP) & Done column and the tasks flow from left to right. I wanted to break it down into different lanes so I could focus on different types of tasks or a current project. The lanes should always be reconfigurable. For this I set  the board to flow vertically rather than left to right so I could add more lanes.

The big difference from Scrum is the limits on each state. In Scrum there is no rule preventing how many tasks are ‘Work In Progress’, the limit is defined in sprint planning with  a fixed scope …you can’t add more tasks part way through. ( Well you shouldn’t !) Kanban limits per workflow state, so in this case we defined a ‘To Do’ limit of 15 and a WIP limit of 6. In our first KanBan board we used different colour post-its to define difficulty/effort as well.

Green = Tasks < 1 hour

Orange = 1 Day

Yellow = 3 Days

Purple = 5 Days

Each post-it had a start and finish date written on it so I could track cycle time and efficiency. ( This was prior to using Jira and Leankit ). Also, we broke down the backlog into ‘This week’ & ‘Next Week’ so we could see upcoming date related tasks way in advance.

We added magnetic Avatars and used these to indicate the owner of the task.

( First attempt )

The Rules of the jungle …

  • Always take the top item from the To Do list

  • Take any item

  • Don’t take consecutive purple tasks ( let others share the bigs ones ! )

  • Work on one ticket at a time unless its green then go for it

  • If you start another task and the current one is on hold move it to the right place

  • No more than 6 post-its in WIP

  • Every week a dedicated person to deal with the deploy lane

  • Every week a dedicated person to deal with the Tech support lane

  • Daily standup at 10am

First thoughts

So we were relatively happy with the KanBan process but felt we could add some further improvements and tweaks.

  • Writing out post-its became a bore

  • People would forget to go to the board and move post-its

  • Post-its fall off. Even super sticky ones !

  • Anyone working remotely couldn’t see the board

  • It looked messy

  • Tracking efficiency was a pain.

Heelllllloooo Virtual Whiteboard….

I started looking around for a way to replace the board with an electronic version. I’d used Greenhopper before in Jira but at this point we hadn’t yet adopted Jira. I looked at a few software solutions as well as online ones. I re-visited Jira but found Greenhopper not configurable enough for my needs…simply put I wanted an exact replica of my whiteboard with post-its.

Welcome to Leankit http://leankit.com/


Leankit is a great tool, lots of board templates for Scrum or Kanban and can be configured very easily. I can create, remove and adjust lanes on the fly, and totally customise the format of cards. Here are some of the features which have transformed the way we use the board.

Card features such as avatars, colour coding, priority indicators, task size & date make the board easy to read and use.

 Mini-boards – You can break down bigger tasks into sub-tasks with its own mini board.



Reports

Conclusion

After adopting KanBan we found it greatly improved our visibility on our day to day work, and gave other teams a better understanding of how we worked. The daily stand ups encouraged better team communication through task reviews, sharing issues & bouncing ideas off each other.

Having the limits on the workflow meant we never over committed our work and made it easier to negotiate with project managers regarding last minute requests. In turn it helped them to understand that something had to give in order to facilitate an expedited task.

New GitHub pages and more open source!

We’ve recently updated our github org page with a summary page of the open source projects we have written. We will soon be open-sourcing more of our work here and wanted to spring clean first! So be sure to check back for more announcements soon!

We periodically run game jams both internally and at festivals. We’ve found that its really useful to have starter games to work on top of and have put together a mindcandy-events github org that collects these in one handy place! Please feel free to use / contribute for your own game jams! We’d love to hear what you get up to!

Meet the QA Team

Image

With frequent releases of new game contents and features across different platforms plus associated marketing campaigns, Quality Assurance (QA) is extremely important to ensure that the software going out to the public is of the highest quality standard.  For this we have a bunch of tea-drinking, always smiling, board game winning, lightning-fast-responding, super-talented and friendly QAs at the Mind Candy HQ in London as well as some highly trained QA ninjas in other countries. Here I present to you the Mind Candy QA Team (and their favourite super powers).

Person
What they work on
Hobbies
Favourite Super Power
Favourite films
Gav Chaudri Currently work on Payments and Bonus Codes. Pretty much done a tour in all teams. In my spare time, I grow vegetables and trees and ask lots of questions. Empathy / Telepathy Waking Life, Vanilla Sky, Elf, K-PAX, The Darjeeling Limited.
Akira Cheng I coordinate QA resources in 3 different countries to ensure all Mind Candy projects receive the QA-loving that they deserve. I teach BodyCombat(tm) gym classes and I’m a qualified personal trainer. I also LOVE traveling, exploring new places in search for new & exotic sweets. Mind Reading The Day after Tomorrow, Twister, Deep Impact (see the pattern there?)
Alistair Broomhead I write automated test scripts and integrate automated test tools I like writing code, playing computer games, and I’m currently getting back into Judo after a long break. Intuitive Comprehension (as in Syler from Heroes) LOTR, The Matrix, Star Wars, basically any good sci-fi.
David Higgins I have been testing Moshi missions as well as helping with some mobile testing. I play football, watch football and then there’s a load of geeky stuff… Anime, Manga and Gaming All of them! Who framed Roger Rabbit (First film I ever saw at the cinema), Big trouble in little china, Never ending story… (The memories are definitely better than the films)
Julia Brown I am currently working across the web and mobile teams. In my spare time I like playing games, watching movies, playing football and taking photos. When I get the chance I like to go snowboarding, diving and kayaking. Shapeshifter I love any good animation, superhero, sci-fi, or end of the world type movies.

Scala Exchange 2012

At the start of last week a few of us here at Mind Candy attended a fantastic 2-day Skills Matter conference on Scala, with a fascinating keynote by Martin Odersky highlighting just how much Scala adoption is on the rise as of late.

To give you an idea of how mainstream Scala is now (sorry hipsters!), it has been adopted by the likes of Twitter, Foursquare, Tumblr, LinkedId, Intel, Amazon and eBay. Odersky recently ran a Coursera course on Functional Programming Principles in Scala, which received over 50,000 sign ups, of which around 20% submitted solutions to the problems (scoring an average of 8/10 for each problem) – in case you don’t know, this is remarkably high for a free course!

But why has it gained such popularity? Odersky attributed this rise in adoption to 2 main reasons:

  1. Moore’s Law is now achieved by increasing the number of cores rather than clock cycles
  2. Modern applications have to deal with huge workloads that require horizontal scalability

These 2 factors bring about a “triple challenge” of dealing with parallelism, asynchronous events, and distributed systems. By programming functionally and not using mutable state, we can make these challenges that much simpler, and this is becoming clearer to those of us in the industry.

Odersky’s covered this in his Keynote as well as a brief history of Scala (talking about how the early adopters were using Scala because of its XML support of all things!), along with some discussion of upcoming features in Scala 2.10 (including string interpolation, futures and implicit classes).

Other Interesting Talks

All of the talks from the conference are available here, but to save you some time, the following are the more interesting / useful talks from the conference:

  • Philipp Haller gave a great talk on Futures and Promises, talking about have they been implemented in several existing libraries (causing much fragmentation), and the motivation behind bringing them into Scala 2.10 [SIP-14]. To clarify, a Future is a container for some result that may exist at some point, and a Promise is an abstraction that (only once) allows you to put a value into that container – together they provide a concurrency abstraction that allows determinism in your system.
  • Viktor Klang gave some pragmatic tips for Evolving a Scala Project to avoid tech debt and save time chasing bugs that have worked for his team whilst working on the Akka project (a lot of these tips are actually pretty language agnostic). Make sure to watch out for the useful Scalac options provided towards the end!
  • Daniel Spiewak‘s talk on Functional Compilers was probably one of the best of the conference. To be able to give a talk on such a dry subject and yet manage to hold the audience’s attention for the entirety is quite an accomplishment. Maybe it was something to do with his use of interpretive dance throughout…
  • Alex Prokopec gave a talk on a Scala Performance Regression Testing suite called Scalameter, and talked about how it can help deal with some of the issues of performance testing on the JVM can be made tricky by dynamic optimisation, JIT compilation and garbage collection.
  • Roland Kuhn explained the use of Clusters in Akka Coltrane, explaining how they are used to manage actor hierarchies to make remote deployment a lot nicer in Akka 2.2, as well as improving actor migration and replication, and node failover
  • Stefan Zeiger introduced Typesafe’s Slick Database Access and Query library, which was designed to be the successor to ScalaQuery (check it out here)
  • Jon Pretty told us about Rapture I/O, a general library for handling IO, with some very nice JSON support (get it here)

Also worth mentioning was the Akka Kata hosted by Henrik Engstrom and Roland Kuhn, which is definitely worth checking out if you’re interested in trying out actors.

Using giter8 to build Scala REST projects with Unfiltered, Netty and Gatling load testing

At Mind Candy we have a number of different Scala REST services to provide common aspects to our games, for example authentication and moderation.

A standard we have developed is to use an Unfiltered Netty standalone server wrapped with the apache-commons daemon library. Also, we want our services to be well tested, easily deployable, and stable under heavy load. For ease of deployment we use Fabric scripts, and for load testing we use Gatling to hammer the services under different stress-tests to check they are up to standard.

We have quite a few services that have a similar setup, and it was getting tedious to create and configure a new project. So, we created a giter8 script to do it all for us!

Giter8

Giter8 is an awesome command line tool which can create a template project structure for you with example files and sbt configuration.

There are quite a few templates contributed by the community already but none did exactly what we want, so we created our own which we’d like to share.

The template will create an example sbt project that:

  • Uses unfiltered and netty to give you a very simple starting endpoint service which will output ‘Hello, <project>’ when hit
  • Gives you some basic test stubs using Specs2
  • Is setup with gatling load testing with an example scenario
  • Is configured with the sbt-idea plugin (IntelliJ IDEA is our preferred IDE)
  • Is configured with the sbt-assemblysbt-release, and sbt-dependency-graph plugins
  • Has a simple fabric deploy file, unix start/stop scripts, and an example init script

The generated project is structured with 3 sub projects:

  • project-example
    • example-core // Business logic
    • example-resources // Containing the Unfiltered Netty request plan
    • example-server // To control the server hosting the plan

Usage:

First make sure you have setup giter8 using the instructions here. Then fire open a terminal and run:

g8 mindcandy/unfiltered-rest-gatling

There are some options to enter, but most can be left as default (See here for more info). The important ones are:

name => The main projects name
project => The name prepended to each of the sub projects
organization => Used as the basis for packages

Once you’ve entered the properties, giter8 will do its magic and whip you up a full sbt project. After it completes, you can cd to the directory, and run sbt.

Test it:

sbt test

Run it:

sbt run

Now open up your favourite browser and go to http://localhost:8889/<project> where <project> is whatever you specified above, and you should get a “hello, project” message back.

Load test it:

Start the server running in one terminal. In another terminal do:

cd yourproject
sbt
project <project>-server
test-load:run

You should get presented with a choice of different classes to run:

  • Engine → Executes the gatling Engine in interactive mode prompting you which scenario to run
  • BatchEngine → Runs all simulations available in a batch with no user prompts
  • Recorder → Starts the pretty cool Gatling recorder which you can use to create scenarios. Basically, you setup your web browser to use the recorder’s proxy, and then just browse as normal on your webpage. Gatling records all of your actions as a scenario that can be replayed and customised.
Hit the option for BatchEngine, then load the results in your browser to see something like:

Results from Gatling are put in the gatling/results directory. In the example scenario in the giter8 skeleton we simulate 10 users hitting the simple endpoint, ramping up over a 3s duration. The results are rendered in a nice html page with graphs showing exactly what happened during the simulation. The full gatling feature set is quite extensive and worth checking out.

Create IntelliJ IDEA project files:

sbt gen-idea

Run from start script:

First setup jsvc. Then :

sbt assembly
cd bin
chmod +x start.sh
./start.sh

This has the same affect as ‘sbt run’, but using the apache-commons daemon wrapper. Try opening the service in your browser again and it should work as before. Don’t forget to stop the server when you’re done with the ../stop.sh script :)

Other pieces:

There is also a sample init script that is configured for the skeleton in the bin folder, which is a good starting point for creating a complete init script.

Last to mention is there is a small fabric file that provides a (very) basic setup for copying over the built assembly onto a test/integration server. You’d need to configure your host and change the paths as appropriate to use it, but it’s useful as a starting point.

Let us know if you find this useful, and thanks to n8han for providing a great tool!

BAFTA Career Surgery at Eurogamer Expo

One of the great things about Eurogamer Expo is that it’s not just a place you can play the latest games before they come out, it’s also a place you can meet and chat with people in the Game industry!  In particular, BAFTA run a Career Surgery where you can book 20 minutes of time with an industry expert to talk about how they got into games and get advice on how you can do it as well!

This year, I was very honoured to be asked to take part and so I found myself chatting for two lively hours to groups of 5-6 young developers, coming from all disciplines – programming, game design, art, game audio and even PR! Some had just finished a university degree, some were just starting and one very enterprising fellow had started his own business. What united them all was their passion for creating games!

People asked me if it was required to have a degree, or if it was worthwhile. I would always answer Yes to this. The game and tech industry in general is always changing and you will have to constantly be learning new things and solving new problems. A degree is proof that you’re good at learning ‘stuff’ and self-organised enough to finish things you’ve started. After all, it’s not like there aren’t other distractions at university.

Even though it’s a tough economy right now, I argue its still a great time to be a game developer. There are more opportunities than ever to create amazing games and get them into the hands of players directly – via the web, on Mac/PC or mobile phones. Incredible game engines are now free to use or available at very reasonable prices (such as the excellent Unity3d which we use at Mind Candy, but others are available). Kickstarter and its ilk offer an alternative to working with a Publisher from day one.

So that’s why the main piece of advice I gave to budding game developers was simply this: make games now! Don’t wait to be given a job, you can start your career right now by making a game. It can be by yourself or with friends, or even other job-hunters. Making a game is great experience – you will be solving the same problems and hitting many of the same issues that you would if you were doing it for a job. You can then use the game as part of your portfolio, or if it’s good enough, self-publish it and make your millions that way! (Just ask Notch)

Of course this is a simplification to some extent – it’s not easy to make anything of value and it’s not easy to get a job in games – but you have to start somewhere and employers value people who have the passion to go for it! Happily, Valve’s Chet Faliszek made much the same point the next day, so evidently I’m not alone in giving that advice.

If you want to find people to collaborate with, then I highly recommend ‘Game Jams’ that have real-world meet-ups (like ludum dare or what would molydeux), your local IGDA chapter or the monthly London Indie Game Meet up.

People learn best from experience, so start building yours today!

(Oh, and check out the current vacancies here at Mind Candy too, of course! Don’t forget to bring in your game when you come in for an interview…)

FOWD 2012: Future of Web Design

The Future of Web Design is one of the biggest and well respected annual web conferences in the world and recently the Mind Candy web team (Davide, Leo, Jenny, James and David) had the pleasure of attending. What follows isn’t a full-on summary of the event as that wouldn’t do it justice. It’s very well documented over the internet already. Instead, in a Q & A interview style, we talk about what areas of the conference stood out most for each of us.

FOWD 2012

Q. What was your favourite talk and why?

David: I particularly enjoyed Mark Boulton’s talk about “Failing and Doing It Well”, he highlighted the importance of embracing failure and maximising the learning process by taking risks and understanding that part of that, is not always succeeding. Putting the emphasis on learning creates for a better work environment and ultimately better work :).

He also highlighted issues with what he perceives as an issue of being overly ambitious; in the sense that you can never achieve your goal and be satisfied. He advises “don’t be ambitious, be a dreamer” because dreamers try to change the world but are content if they don’t succeed.

Jenny: I had a few, but the stand out ones tended to encapsulate my own current position in the industry, and my own future ambitions. I’d say a heady mix of Remy Sharp’s “Dr Weblove / How I learned to stop worrying about Photoshop and love designers”, Jonathan Berger’s “Code Literacy for Designers”, Sarah Parmenter’s “Future of Beautiful iOS Design”, and Jon Tan’s talk on Web Typography.

James: Laura Kalbag gave a great talk, I found her approach to adaptive responsive design both practical and pragmatic. She gave some great advice, such as: design around your images, don’t design straight into the browser because you’ll end up with blocky designs and it’s OK to design the desktop version of a site first.

I also really enjoyed Jon Tan’s talk on web typography, he made the point that badly set type isn’t harder to read, it just puts the user in a bad mood, which makes them much less likely to do what you want them to do.

Davide: The talks given by Bill Buxton and The Standardistas: they were inspiring: the former because it was a clear push toward the future and gave me an insight on how and were new ideas are born; the latter, because in an overconnected society like ours, we easily run the risk of simply collecting superficial information (like the squirrel) without digesting anything and missing the true power of a learning experience: incubation.

Q. Most exciting thing that you’re looking forward to?

Davide: The BIG Innovations intruduced in The HTML5 JS API: Geolocation, WebWorkers, WebSockets, Canvas, Local Storage, Indexed DB; Pushing forward for bringing Javascript in the Backend with NodeJS (Railway, Express etc..); Moreover, the wide adoption of CoffeeScript as the official successor for Javascript and seeing it supported natively by browser implementors.

Jenny: The final death throes of Internet Explorer 6.

Leo: Martin Beeby is a Microsoft web evangelist/developer and his talk blew me away! He introduced one of Microsoft’s current HTML5 developments: ‘Soundwave – Using the Doppler effect to sense gestures’ and if it realises its promise then I think it’s going to revolutionise the way we interact with the web.

In Microsoft’s words, SoundWave is a real-time sensing technique that leverages a device’s speaker and microphone to robustly sense in-air gestures and motion. So via clever use of existing device sensors, we can start to imagine and define new ways to touch, speak, move and interact with a web app as demonstrated in the link below.

http://www.youtube.com/watch?v=rFM59B3tYI4

Muscle memory is quicker and more intuitive than keyboard/mouse alone so in future I fully expect faster and richer human interactions with HTML5 web apps. Add to this the cutting edge advances in utilising a computer’s webcam via getUserMedia(), and the possibility of all these sensors working together in future, we can really start to imagine more involved and immersive web experiences and interactions. It’s still early days, but very exciting!

Q. What is the future of web design?

Davide: Maybe to change and include one of the new trends, that see Web Applications becoming more and more full fledged ‘Desktop’ Applications simply running into a web container. Web Design, in this perspective, will become more of a ‘Web’ branch of ‘application’ design.

Jenny: It’s everywhere we look and in everything we do. It’s a wealth of information made beautiful to look at. It’s the internet in our pocket and the world at our fingertips. It’s us, totally involved.

James: That there is no set best process for designing flexible adaptive sites – this is something I find incredibly exciting.

Q. Will this change the way you work/think in future?

Jenny: It’d be difficult for it not to. The arena we throw ourselves around in is constantly in a state of update, and it’s really important to keep our eyes open for the game-changing stuff :)

I personally came away with a whole bunch of practices and angles that I’d not thought about before, and that are already making a big difference. The speakers at FOWD know their onions, it’d be silly not to take notice!

Davide: Yes; I’ll start looking around me for hints of the future (see Bill Buxton talk) and I’ll probably try to focus on one topic at a time instead of consuming most of my time wandering around and ammassing information (that I never consume).

Q. Tweet or quote of the day?

Leo: “Don’t think. FEEL. It’s like a finger pointing at the moon. Do not concentrate on the finger or you will miss all of the heavenly glory!” Bruce Lee

Jon Tan talked about the emotive qualities of typography and how it is felt rather than just seen, so I think using a Bruce Lee quote to end a talk on Web Typography was awesome!

Jenny: I have a few…! I’ll settle with these:
“No matter what the tech is now, no matter what it is in the future, it will always be about communicating” – @blueleafchris

“Ideas don’t form in a vacuum. Without constant input, the outputs will inevitably remain the same” – @standardistas

David: “Now we can do anything, what should we do?” – Bill Buxton

Bill Buxton’s talk was one of the most future driven and he highlighted that technology is rarely what holds back progress; the limiting factor is often our imaginations.

Q. The one thing that you took away from the conference?

Jenny: I’m really big on learning new skills and becoming better at ones I already have. I like to be an InfoSponge™.

So I love how those in our industry (and especially the startup tech world) are excited to share information and fresh thinking – I believe we encourage that more than any other industry. It’s given me a lot of motivation to do the same, and rather wonderfully, learn a lot in the process.

Q Are you a superstar, ninja or rockstar?

Davide: Ninja, quickly moving in the shadows and sharpening my blades for the big battles to come.

James: I like to think of myself as a tramp with a house and a job.

Jenny: I’m just a massive nerd, and damn proud of it.

All in all, it was a brain-cramming, eye-opening and inspirational 2 days that provided a lot of insight and food for thought. Here at Mind Candy, we’ve already started to modify our design/development processes as a result of what we learnt and the results so far have been massively positive! With so much going on and so much to look forward to, it also ignited a renewed sense of excitement and enthusiasm for the web. So for these reasons alone, it’s been a highly invaluable experience and we’re very much looking forward to the next one! Roll on, FOWD 2013!

We now have access to all the videos so get in touch if you’d like to talk more! In the meantime, here are several interesting people to e-stalk:

@standardistas
@mrjoe
@USA2DAY
@rem
@jontangerine
@sazzy
@markboulton
@laurakalbag
@boagworld
@ryancarson
@Dstroii
@hellofisher

Migrating a Play 1.2 website to Play 2.0

At Mind Candy there are a number of internal websites used for reporting and communication. For example – reading automated build/test status via some REST APIs and turning this into a nice visual status display for large ‘build screens’. These have been authored in Scala using the Play Framework 1.2.x.

Recently, version 2.0 of the Play Framework came out of beta and so I wanted to convert the existing Play 1.2 websites over to it. Amongst other reasons, the ability to build to a .jar file makes for simpler deployment, which I was keen to have.

I couldn’t find a good guide for migrating from 1.x -> 2.0 so I am sharing my experiences of porting a Scala Play 1.2.x application. I expected that it wouldn’t be too hard as I was already using Scala Templates and controllers. That was mostly true, with a couple of issues.

I did find a handy conversion guide on the Play 2 wiki which can help converting some uses (it has some unfortunate formatting though so I’d recommend copying and pasting it)

Starting the project

I’d previously installed Play via brew so an upgrade was as simple as
brew update
brew upgrade play

This installed Play 2 whilst leaving Play 1.2.4 also installed for easy roll-back for developing older stuff if I need it.

For simplicity and because there were various code changes that I knew I needed to make, I created a new site in a new location using play new. However I then used svn copy to copy over source assets and code before modifying. This means in the future I can pull updates down using “svn merge” as work continued on the old site whilst I was porting it over!

All of the public files which aren’t built – javascript, css, images – were simply copied across. In the future I’ll check Play’s support for LESS CSS and the Google Closure JS compiler but for now I just want to get things working.

Initially I copied across all the controllers, models and views and configuration files, though I expected to have to fix those up as the syntax had changed.

After a quick run of play compile I had a whole host of build errors, unsurprisingly. So to cut these down I commented out a lot of the logic – all the routes except the home page /, all the templates and all the controllers except for those needed by the home page.

I fixed up controller in turn and gradually re-enabled the routes, until I hit an issue with Database models that stopped me from migrating the rest of my application (see below)

Migrating dependencies

There were a number of java libraries used by the web app, for example to talk to a Subversion server. (This is one of the reasons I really like Scala – it’s easy to pull in useful Java libraries) In Play 1 that was defined in dependencies.yml, e.g.:

require:
- org.tmatesoft.svnkit -> svnkit 1.3.7
- org.tmatesoft.svnkit -> svnkit-javahl16 1.3.7

repositories:
- tmatesoft:
  type: iBiblio
  root: "http://maven.studio:8081/nexus/content/repositories/tmatesoft"
  contains:
  - org.tmatesoft.svnkit -> *</code>

Play 2 now uses sbt as its build system and thus uses the standard sbt syntax for dependencies, so I edited the the project/Build.scala file to add dependencies:

object ApplicationBuild extends Build {
  // some definitions omitted

  val appDependencies = Seq(
    "org.tmatesoft.svnkit" % "svnkit" % "1.7.4",
    "org.tmatesoft.svnkit" % "svnkit-javahl16" % "1.7.4",
  )

  val main = PlayProject(appName, appVersion, appDependencies, mainLang = SCALA).settings(
    resolvers += "TmateSoft Repository" at "http://maven.tmatesoft.com/content/repositories/releases/",
  )
}

Once the sbt syntax is understood it’s a reasonably simple process to convert dependencies across.

The original play run / test / start / stop command still work, which is helpful. It’s also quite useful to simply run play to get an sbt console and then run ~test which runs test and then re-runs them anytime a source file changes, which is very useful.

For IDE integration, I use IntelliJ IDEA and happily there is an idea command in Play’s SBT which generates an IntelliJ module which has any library dependencies included. However, your code has to build correctly before this works and you probably need to remember to re-run this every time you modify a dependency. If you don’t the IDE won’t show types correctly – typically you will get more ‘false negatives’ of errors showing up in the IDE which will not happen within Play itself.

Migrating the routes file

For some reason the old Routes file had an explicit 404 for the for the favicon. There didn’t seem to be an obvious pure route-based replacement for this and I didn’t need that behaviour so removed the route.

I had to add controllers. to all routes as the full package reference seems to be required now.
e.g. home page changed from
GET / Application.index
to
GET / controllers.Application.index

The syntax for ‘public’ files has changed so I replaced
GET /public/ staticDir:public
with
GET /public/*file controllers.Assets.at(path="/public", file)

I was also serving a single file elsewhere – multiple Assets.at() in the routes file didn’t go well, but I was able to call to add a new method to the Application e.g. ‘serveMyFile’ and then set the routing to be controller.Application.serveMyFile in routes and then have that call the Assets.at() method
e.g.
GET /myfile controllers.Application.serveMyFile
in the Application controller:
def serveMyFile = controllers.Assets.at(path="/path/to/it", file="myfilename.json")

The syntax for parameters in routes has changed and I found that I needed to move the default parameter definitions from the Controller out to the Routes file, using the ?= syntax instead of the Option[T] syntax I had before. That wasn’t hard to do but was slightly irritating in some ways – I’m still not sure if I like having so it in the routes file.

Minor changes to the syntax for parsing out ids from the URL, for example:
GET /versionone/stories/{projectId} versionone.Printer.storiesById
changed to
GET /versionone/stories/:projectId controllers.versionone.Printer.storiesById(projectId: String, timeboxId: String ?= "", template: String ?= "")

Note the additional default parameters being passed. Also in this instance the Id is actually a string, not an Int.

Migrating Controllers

A lot of the package names have changed e.g. play -> play.api so some of the imports needed to be fixed up with the new ‘api’

replaced
import play._
import play.mvc._

with
import play.api._
import play.api.mvc._

With the paths to generated views also changed, I removed lines like import views.Application._

Then with imports fixed up I could then fix up the actual controller code to return an Action and
adding Ok(views.html. … )
e.g. from
def index = {
html.index()
}

to
def index = Action {
Ok(views.html.Application.index())
}

As I mentioned earlier, some changes to controllers were needed because the routes file now supplies default parameters, and I took out some use of the Option[T] type — though as this was generally a String, the empty string works very well as an equivalent to None.

In some controllers I’ve implemented an OAuth callback to read from a Google Calendar – eventually I’d like to play with the built-in OAuth support in Play 2 but in the interest of getting things working quickly I wanted to port over my current code. In order to send a url for Google auth to use as a callback I am calling Router.getFullUrl() but this doesn’t work in Play 2, instead one calls the automatically generated route classes instead. To turn this into a full url you call .absoluteUrl(), but you must remember to add the implicit request to your controller code in order to give this the context needed to generate the url.
e.g. the original code was approximately:

object MyController extends Controller {
  def request = {
    val callbackUrl = Router.getFullUrl(“MyController.callback”)
    // send web request using callbackUrl
  }

  def callback = {
    // handle request
  }
}

the new Play 2 code is:

object MyController extends Controller {
  def request = Action { implicit request =>
    val callbackUrl = routes.MyController.callback().absoluteURL()
    // send web request using callbackUrl
  }

  def callback = Action {
    // handle request
  }
}

This is more robust because that reverse-lookup is now checked at compile time, rather than runtime. However if your code doesn’t build, your IDE will give you errors as the reverse routes don’t exist. I did occasionally have to do a clean build to force regeneration of reverse-lookups, if the code structure had changed significantly.

Migrating Views

I had to replace @asset() with @routes.Assets.at()

Old references to actions can now be replaced with the compile-time checked generated routing objects. But the snag that isn’t documented is that if you are using a sub-project, the routes are generated within the scope of that sub-project.

e.g. replace @action(svn.Sizes.index()) with @controllers.svn.routes.Sizes.index()
This was mentioned on the Play discussion group here.

Migrating Tests

Unfortunately the bundled Play test framework has changed from scalatest to specs2. I could possibly have set up scalatest to work but decided to migrate the tests instead as the new functional tests look useful, as is the ‘property’ support in specs2.

A few imports change – I had to get rid of the scalatest imports and add in:

import org.specs2.mutable._
import play.api.test._
import play.api.test.Helpers._

The test class now simply extends Specification and I had to fiddle around with the syntax, replacing it with a noun and adding some more braces. should be(x) was replaced with mustEqual x

For example:

it should "retrieve svn server prefix" in {
  val svnServers = SvnServer.find().list()
  svnServers.length should be > (0)
}

becomes:

"SvnServer" should {
  "retrieve svn server prefix" in {
    val svnServers = SvnServer.find().list()
    svnServers.length must be_>(0)
  }
}

There is a good list of all the matchers in specs2 at the specs2 site which I found very useful.

I migrated some very basic selenium tests to the new functional test framework – documented here. The advantage of this is that you can separately test the controller, view and the whole thing together with the router.

The old selenium test was

#{selenium 'Home page'}
// Open the home page, and check that no error occured
open('/')
assertNotTitle('Application error')
#{/selenium}

So a simple test that the home page works is:

class ApplicationTest extends Specification {

  "The Application" should {
    "render template correctly " in {

      val html = views.html.Application.index()

      contentType(html) must equalTo("text/html")

      val content = contentAsString(html)
      content must contain ("Welcome to the Tools website")
      content must not contain ("Application error")
    }

    "have a working controller" in {
      val result = controllers.Application.index()(FakeRequest())

      status(result) must equalTo(OK)
      contentType(result) must beSome("text/html")
      charset(result) must beSome("utf-8")

      val content = contentAsString(result)
      content must contain ("Welcome to the Tools website")
      content must not contain ("Application error")
    }

    "run in a server" in {
      running(TestServer(3333)) {

        await(WS.url("http://localhost:3333").get()).status must equalTo(OK)

      }
    }
  }
}

Migrating the Database Models – problems!

Now for the bad news… our database models were making heavy use of the Magic[T] class and that simply isn’t present in Play 2.0 at the moment (Apparently it featured in a beta version but was removed). What Magic[T] did was generate a lot of the code for the CRUD operations from a simple case class. For reference in the old documentation for the play-scala-0.9.1, this is what Magic did.

Whilst I could write all of this code myself, I have about 40 classes to do this for, so this is a non-trivial amount of work.

I also discovered that the DB evolution hashes are different, so play wanted to revert and re-apply all of my DB schema changes, which would have trashed the DB contents. Apparently this is now fixed in the trunk in Play 2 so hopefully that change will be in a release soon.

Because I don’t have the time to rewrite all the DB classes, I decided to split my application into two parts, as there are a number of very independent reports in the site which do not use the DB. The reports will be in a play 2 site and the older code that uses the DB will stay as a Play 1.2 site.

In the future I would like to port everything to Play 2. I’m hoping that someone will reintroduce Magic[T], either into the core of Play 2 or as an additional bit of code / plugin. Alternatively I’ll have to do all the grunt work myself, which would be a shame. It’s the kind of work I like to avoid simply because there is very little value I can add – it will either keep working or (more likely) I will break something! So the best option is to leave this old ‘legacy’ site as play 1.2 until there is an easier/safer upgrade path.

However, I will definitely be using Play 2.0 for new development!

Google and HTML5 – Simplicity, Security and Speed

HTML5

HTML5 has been around for a while, but only since recent times however, has it emerged as the major web technology of choice moving forward. Browsers are catching up, increasingly adding HTML5 feature support and there is an emergence of tools offering near-comprehensive compatibility with older browsers and platforms. Not to mention the massive support and investment from tech powerhouses such as Google and Apple, HTML5 really is fast becoming the defacto standard for building powerful, cross-compatible web apps.

This new age of HTML5 powered web apps means we can recreate a seamless native app experience from within the browser. However this time, there’s no flash, no plugins, nor any downloads. Instead, with the help of new HTML5 features such as drag and drop, local storage, multimedia (canvas, svg, video and audio), geolocation, offline and real time communication (webRTC), along with CSS3 and various Javascript API’s, we now have one technology stack that is usable across multiple platforms and devices.

Google

Google have pioneered in this area for a while, having led the way with a plethora of powerful, game-changing, web apps such as Docs and Sites to name but a few. They recently invited a group of geeks/web developers to their London offices in Victoria for a talk about HTML5 and some of the things they’ve been working on. I was part of this group.

The offices are pretty cool. From the famous Google ‘don’t be evil’ posters to the life-size London red bus to the fully catered kitchen and astro-turfed meeting room. It all supported the fun, creative and inspiring vibe floating around the place and this is what Google is about from a cultural point of view. What Google are all about technologically, can be loosely categorised into 3 areas: simplicity, security and speed. These are the primary focuses for the Chrome OS and also for their user-centric designs.

Simplicity

New breed of Web apps: One technology stack that is interoperable between multiple devices and platforms without the need for downloads or cross platform and OS adaptations. Add powerful features such as offline use, canvas and touch event API’s, and the categorisation between a website and web app becomes more converged. FT and Kindle are good examples of this new breed of HTML5 web app.

Chromeframe:  There are a lot of cool new HTML5 features which aren’t compatible with older browsers such as Internet Explorer 6 & 7 and this can be costly to support for developers. One option to reduce this headache is to prompt users to install Google Chromeframe which enables Chrome to work inside Internet Explorer. Instant compatibility.

WebIntents: Web Intents make it easier to share data and web services across apps. E.g. ‘share a link with Twitter’ or ‘edit a photo with image editor before sending’. Instead of integrating each and every one of these web services with your app, the user is empowered with their own choice. The idea is that your service registers an intent to handle an action such as sharing or editing, and the system will learn to find the appropriate services for the user to use based on the user’s preferences. Less integrating, more sharing.

Security

Content Security Policy (CSP): CSP tackles malicious cross site scripting by allowing web pages to limit where external content can be loaded from. Additionally, inline javascript and CSS are not allowed. As well as providing a good security measure, this also helps maintain good semantics.

3Dtin: This is an entirely web based 3D modelling app where anyone can jump in and start creating 3D models. If extra functionality is required, it offers an openID signup using Google Identity Toolkit which adds a layer of security onto the login part of the process. This ‘try now, sign in after’ approach enhances the user experience by allowing users to first engage, then commit after.

Browsers: A good browser makes all the difference. Chrome pushes updates automatically which ensures that the user always has the latest version with all the latest security patches. It also offers comprehensive sandboxing and plugin security for extra layers of protection.

Speed

Offline: HTML5 provides a better way of implementing offline availability and local storage. Previously this was done using cookies and offline emulation (gears). Now, it can be done using application caching and HTML5 storage. Application Cache is like a beefed up implementation of the browser cache, storing references to all required resources in a cache manifest file. HTML5 storage includes API’s such as Web Storage and IndexedDB, which store user state (such as state of play in a game) on the user’s local database for later use.

Frameworks/Templates: The idea of using frameworks and templates isn’t new, nor are they a requisite for building HTML5 web apps, but the ‘do more with less code’ benefits are certainly worth a mention. For Javascript, popular MVC frameworks include Backbone.js and Javascript MVC. SASS and LESS are some of the more well known CSS frameworks. Underscore and Mustache are great for templating. If you want to start building an HTML5 website from a template, then HTML5 Boilerplate is the daddy.

Bleeding Edge Technologies: This is what the Google developers refer to when talking about work on more-cutting-than-cutting-edge technologies (i.e. not well supported!) These include:

  • pageVisibility API: This determines if your web app is actively in view of the user. If not (i.e. user is on another tab), then the non-active pages are paused, hence optimising performance.
  • prerendering API: This predicts where the user will navigate next and pre-loads the page so that it appears to load instantly when it is clicked.
  • Fullscreen API: Fullscreen without the need for flash. All individual DOM elements are styleable which leads to lots more control and customisation.
  • Gamepad API: With powerful multimedia capabilities such as canvas and SVG gaining momentum, games running in the browser are only going to get more sophisticated. This API maps gamepad button events and empowers the user with a more traditional gaming experience.
  • webRTC: This is real time communication through browser alone i.e. plugin-free. It’s based on p2p and a handshake through to the server, and uses the getUserMedia API to talk to the user’s camera/microphone. This has the possibility to create much richer web-browser social video based experiences than was possible before.
  • Speech Input API: With the ability to transcribe voice into text, this will be a game-changer… once the voice recognition technology improves. An extremely exciting prospect for the near future.
  • Video subititles: Using the <track> tag and a linked .vtt file, video subtitles can be implemented. Great for accessibility, with potential for timed metadata and deep-linking into exact points on a video. Perhaps, on-the-fly localised subtitles using multiple .vtt files and the speech input API in the near future?

Conclusion

Technology moves fast. In my time at Google, buggy demos were shown, Chrome extensions were written on the fly and new features were released that the top developers didn’t even know about. The motto of the day seemed to be ‘There are a few bugs, but it works’ and ‘That’s a bug, I’ll fix it’. It’s what happens when you’re at the front of a new technology. But it’s through innovation and fast-paced iterations in which cool things develop…

So it’s a wonder why Microsoft have been so slow in providing HTML5 support for Internet Explorer. With its large market share, mainstream adoption of HTML5 has been massively held back. However, this is all set to change, with the imminent arrival of IE10. Less time will be spent dealing with cross platform and device issues, messing with legacy browser woes and hacking polyfiller shims together. More time will be spent innovating, and building richer, more sophisticated web apps that run through the browser alone. Exciting times to be a web developer! Developers are just scratching the surface of what is possible and as the HTML5 standard matures, as will our web apps. And if we adhere to the 3 S’s and acknowledge that users want things simple, secure and speedy, the future of the web is already in better shape. Exciting times ahead indeed!

Many thanks to Google and the team Sam Dutton, Paul Kinlan, Ido Green and Alex Russell

Useful Links

Building testing tools against REST APIs with node.js and Coffeescript

During the dev cycle here at Mind Candy it is useful to have tools to help automate some of the more repetitive tasks, for example, registering a user. The great thing about test tools is that they are a great excuse to try out new technologies too! In this blog post, I’ll be telling you about a tool we wrote to register new users. It uses node.js, the non-blocking I/O server side JavaScript platform that is powered by Google’s V8 VM.

The reasons why I chose node.js for this project are as follows:

  1. It makes working with I/O operations an absolute breeze. Every I/O operation is required to be non-blocking, so its perfectly valid to keep a request open from a client such as a web browser while you make a bunch of (sometimes concurrent) calls off to REST APIs, databases, external systems etc, wait for them to call back to your code and then return a response. All of this happens without occupying a thread per request, unlike your standard java servlet. In fact, node.js is single threaded and uses an event loop, so as long as your expensive I/O operations are non blocking, the event loop just keeps ticking over and your system stays responsive.
  2. While node.js is a comparatively new technology, it has a HUGE and vibrant community behind it. There are so many 3rd party modules that if you need to interface with any other thing, there is most likely a module already written! Node also has an awesome package manager in npm, which makes declaring and downloading modules super easy.
  3. The holy nirvana – the same language running on the server and the client. Since the app is going to be deployed for the web, and therefore going to be powered by javascript, there are no problems with things such as serialising and deserialising objects between client and server (they all natively speak JSON), or different paradigms between languages giving you an impedance mismatch.

The whole project is actually written in a language called Coffescript. For those who haven’t heard of it, Coffeescript is a language that compiles down to javascript. It abstracts away some of the more grizzly parts of javascript, has a nice, clear and concise syntax and has a bunch of useful syntax features built in, such as loop comprehensions, conditional and multiple assignment and a simple class system. It’s like a bunch of best practices for javascript!

So let’s have a look at some of the code. For example, here is how we talk to the Adoption endpoint:

request = require('request')
xmlbuilder = require('xmlbuilder')

class Adoption
    constructor: (@host) ->

    start: (username, password, email, cb) ->
        adoption = xmlbuilder.create()

        adoption.begin('adoption')
            .ele('email').txt(email).up()
            .ele('password').txt(password).up()
            .ele('username').txt(username).up()

        adoptionXml = adoption.toString({pretty: true})

        request({
            method: 'POST',
            uri: "http://#{@host}/my/rest/service",
            body: adoptionXml,
            headers: {
                'Content-type': 'application/xml'
            }
        }, (err, resp, body) ->
            cb(err) if err

            if(body.search(/<error name="username" rule="is_not_unique"\/>/) > 0)
                usernameError = {
                    message: 'username is already taken'
                }

            cb(usernameError)
        )

module.exports = Adoption

First thing to note is indenting and whitespace is important! You MUST use spaces instead of tabs here, otherwise the compiler complains! Here we’re creating a ‘class’ called Adoption. Javascript doesn’t really have classes, but Coffeescript translates that into some javascript that gives you class-like behaviour. At line 5, we declare the class constructor function. In Coffeescript, functions are a very small declaration: just the function arguments in brackets and then an arrow. Anything after the arrow is the function body. The constructor is very simple, all it’s doing is setting the arguments of the function as member variables of that object. Looking at the javascript generated from the Coffeescript compiler illustrates this:

function Adoption(host) {
    this.host = host;
}

The start function (line 7) takes a bunch of parameters of data from the user and a callback function as the last argument. In node.js, if we are doing any async operation such as calling a REST endpoint, we cannot return the response data from that function since that would block the event loop. Instead, we are provided with a callback function which we can then call with the response once the server responds.

On line 10 we build up the xml payload to the Moshi Monsters REST endpoint, using a module called xmlbuilder. It would be a lot simpler if the endpoint accepted JSON! Next (line 17) we send the request to the endpoint itself. Here, we use the excellent request module. If you are familiar with how you perform ajax requests with jQuery, this should look quite familiar to you! Its another example of how node.js makes full stack development a lot less trouble for your developers as so many of the techniques used on the client side can be applied to your server side code.

The request function takes an object with the options for that request, and a callback that gets called upon error or success. The convention in node.js is to always expect the first argument to your callback function as a possible error, since if the async operation fails, you can check that parameter for the exception. On line 25 there is an example of Coffeescript’s postfix form of the if operator.

We then check for some response xml with a regular expression (line 27) and call the callback with the possible error object if the regex matches. Notice we do not have to declare variables before we use them. If we did this in raw javascript, they would end up becoming global variables, but Coffeescript handily declares them up front for us.
The last line is how we expose our class to the rest of the program. Node.js uses the CommonJS module system, so every file loaded is self contained as a module. We can expose our class by assigning it to the module.exports variable. This allows us to instantiate an Adoption object in another file:

Adoption = require('./path/to/adoption.coffee')

I used the brilliant express http server to serve this webapp. It has the concept of ‘middleware’ – effectively a bunch of functions that every request and response pass through. This means it is super easy to add functionality to express like caching, static file serving, and even asset pipelining as we will see later! We can set up a handler for our adoption request like so:

express = require('express')
Adoption = require('./adoption') #note that the file extension is optional!
app = express.createServer()

app.set('view engine', 'jade')

app.use(express.bodyParser())

adoption = new Adoption('www.moshimonsters.com')

app.post('/adopt', (req, res) ->
    username = req.body.username
    password = req.body.password
    email = req.body.email
    adoption.start(username, password, email, (err) ->
        if(err)
            res.json(err.message, 500)
        else
            res.send()
   )
)

app.listen(3000)

We’re using a template language called jade for the client side HTML markup. Jade is a simple, lightweight alternative to html. Here’s an example straight from their website:

doctype 5
html(lang="en")
  head
    title= pageTitle
    script(type='text/javascript')
      if (foo) {
         bar()
      }
  body
    h1 Jade - node template engine
    #container
      if youAreUsingJade
        p You are amazing
      else
        p Get on it!

Jade is nice and lightweight, but you can also do more hardcore stuff like scripting in the templates if you wish. It supports layouts and partials and all kinds of other nice stuff. Check out the website to learn more about it!

The client side javascript for this tool is written in Coffeescript too! But how does the browser understand it? The answer is that it doesn’t – we have to compile it first into javascript. You could do this as part of the build, but we have a better solution available to us.

There is a middleware module for express called connect-assets. This middleware adds asset pipelining to connect, so that you can write your code in Coffeescript and it will compile it on the fly and serve it to the browser, without you having to do anything! It can even minify the resulting javascript. You add it like this:

connectAssets = require('connect-assets')

...

# set build to true to minify the js
app.use(connectAssets({build: false}))

…and then we add a macro into our jade template:

doctype 5
html(lang="en")
  head
    // add macro in the head of your html document
    != js('adoption')

    // rest of your markup below

…passing in the name of your Coffeescript file (minus the .coffee) extension.

Obviously this is not the whole of the source code of the tool, but hopefully it has been a taster of how awesome modern javascript development can be! In the last few years, javascript has gone from being an unliked toy language into something a lot more powerful and expressive. Here at Mind Candy we hope to leverage amazing new tools like node.js and coffeescript in our future work to allow us to become a more happy and productive development team!