Matt RaibleMatt Raible is a writer with a passion for software. Connect with him on LinkedIn.

The Angular Mini-Book The Angular Mini-Book is a guide to getting started with Angular. You'll learn how to develop a bare-bones application, test it, and deploy it. Then you'll move on to adding Bootstrap, Angular Material, continuous integration, and authentication.

Spring Boot is a popular framework for building REST APIs. You'll learn how to integrate Angular with Spring Boot and use security best practices like HTTPS and a content security policy.

For book updates, follow @angular_book on Twitter.

The JHipster Mini-Book The JHipster Mini-Book is a guide to getting started with hip technologies today: Angular, Bootstrap, and Spring Boot. All of these frameworks are wrapped up in an easy-to-use project called JHipster.

This book shows you how to build an app with JHipster, and guides you through the plethora of tools, techniques and options you can use. Furthermore, it explains the UI and API building blocks so you understand the underpinnings of your great application.

For book updates, follow @jhipster-book on Twitter.

10+ YEARS


Over 10 years ago, I wrote my first blog post. Since then, I've authored books, had kids, traveled the world, found Trish and blogged about it all.
You searched this site for "read Economics 22nd Edition online free". 1,100 entries found.

You can also try this same search on Google.

Our Engaging Trip to Paris and Antwerp

If you're a technologist, you should attend the Devoxx conference at least once in your life. It's one of the finest conferences on the planet. If you're a fan of Belgian beer, you owe it to yourself to visit Belgium to savor a taste. If you're a romantic, Paris is a recommended destination. Since I'm a technologist, love Belgian beer and consider myself a romantic, I went for the trifecta a couple weeks ago on what's becoming an annual trek to Devoxx. When Trish and I traveled to Devoxx last year, we flew to Amsterdam and took the train to Antwerp. This year, we decided to fly to Paris and take the train.

Much like last year, we witnessed another Broncos over Chiefs victory the Sunday before we left. That night, I stayed up until the wee hours of the morning finishing my Devoxx presentation. We left Denver around noon and met up with James Ward at the Red Carpet Club in Chicago. While sipping cocktails and catching up, I wrote a blog post about how PhoneGap rescued me a couple days earlier.

We slept soundly on the flight over, thanks to little sleep the night before. After arriving in Paris, we took the train to the the Notre Dame de Paris and had some breakfast nearby.

Notre Dame Cathedral Paris

We were planning on exploring throughout the day, but quickly realized that hauling our bags around was no fun and headed to Gare du Nord to catch a Thalys train to Brussels. We gasped at the cost of two first-class tickets, but soon forgot when we settled into our seats with free wi-fi, Belgian beers and power. After talking a local train to Antwerp, we finished our 21-hour journey by checking into the Hilton Antwerp in the city center. We were warmly welcomed with excellent Belgian beers on ice in our room and celebrated with a delicious meal at De Godevaart.

On Wednesday, I headed to Devoxx and attended a couple of great talks: Play 2.0, A web framework for a new era and PhoneGap for Hybrid App Development. As you can imagine, both talks were extremely interesting for me since I'd been using Play for several months and was recently saved by PhoneGap. Play 2.0 Beta was announced just before the Play talk and my blog post about the Play 2.0 session was picked up by Hacker News and the hits rolled in.

That afternoon, I headed back to my hotel with James Ward and met up with Trish for a couple beers. We spent a few hours in our hotel lobby updating presentations, editing videos, editing photos and getting ready for our talks on Thursday. That evening, we enjoyed a scrumptious dinner in the dungeon-like Pelgrom and conversations with Kevin Nilson, Sadek Drobi, Guillaume Bort and David Geary. I was pleased to find out from Sadek and Guillaume that Play 2.0 will include many fast website best practices, including concatenation, minification and gzipping of static assets. We retired early to get a good night's sleep before my talk on Thursday.

Kwak Kwak Kwak! Candle at Pelgrom

Matt Raible and Crew at Devoxx dinner Matt Raible at Pelgrom

On Thursday, both Trish and I journeyed to Devoxx to watch James Ward talk about how to deploy Java, Play Framework, and Scala apps on Heroku. My talk was an hour later and I gulped as I stood up front and watched the (very large) auditorium fill up with Devoxxians. Since I'd never rehearsed my talk or timed it, I was a bit nervous. Luckily, it ended up being one of my best-timed performances and there was even time for Q and A at the end. You can imagine the smile on my face as AC/DC's Thunderstruck blasted through the speakers during my video demo. After my talk finished, it was great to see all the positive feedback on Twitter and enjoy an "Atlas Beer" while watching Java Posse Live.

James Ward speaking on Heroku at Devoxx Matt Raible speaking at Devoxx Belgium 2011

Audience at Matt Raible's Presentation Devoxx Belgium

That evening, we had dinner with the Java Posse crew and James Ward before heading to the Devoxx Party @ Noxx.

Devoxx Party @ Noxx

Yes, we had an awesome time at Devoxx. I was pleased with the positive response from my talk and learned a bunch from the few talks I attended. Thanks to Stephan for inviting me and organizing one of the best conferences I've ever attended. For our last night in Antwerp, we dined at Huis De Colvenier and especially enjoyed our aperitif in the 19th-century wine cellar.

Huis De Colvenier Huis De Colvenier Huis De Colvenier Huis De Colvenier

Riverside in Antwerp Antwerp Town Square

Mmmm, Belgium Beer... We love Belgian Beer

Paris and Beyond
This brings us to my favorite part of this story. I was pretty stressed leading up to our departure to Devoxx because I had so many deadlines. I had a deadline with my current client to finish up some features before I left, I had to finish my Devoxx presentation (and app developed for the talk) and I had a secret deadline to finish my proposal to Trish. That's right, I was planning on proposing marriage to my dream girl. I mean, we were going to the diamond capital of the world (Antwerp) and one of Earth's most romantic cities (Paris). It seemed like the perfect opportunity to ask her to marry me. We did some ring shopping before we left Denver, but she didn't realize I had purchased one before we left.

We're both big music fans, so I decided months earlier that I would propose with lines from songs we both liked. Of course, I waited until the last minute to compose my prose, but I did finish it before we left for Europe. However, with all the Devoxx shenanigans, I didn't have time to memorize my proposal. Instead, I recorded it using the "Voice Memos" on my iPhone. I did this in the wee hours of the morning on Friday, while I was watching the Broncos game on the internet.

Saturday afternoon, we traveled to Paris via Thalys and checked into our hotel around sunset. When we stepped outside an hour later, I remember saying to Trish, "the Eiffel Tower looks pretty small, I thought it'd be bigger". After walking for a bit, it turned from small to big to huge. My plan that night was to propose on the tower. As Trish snapped pictures along our walk, I was taking out the piece of paper I had the proposal printed on and trying to memorize it. As you can imagine, I had to to this stealthily and by the time we reached the Eiffel Tower, I had enough memorized to propose. We arrived around midnight and were disappointed to find it was closed. This terminated my proposal plans for that night, but we still enjoyed the sparkling tower lights and took several pictures.

The Eiffel Tower The Eiffel Tower

The next day, Sunday, we traveled to the Château de Versailles. This was a recommendation from my good friend Eric, who had recently traveled to Paris with his wife, Heather. In fact, I owe a lot to Eric. He recommended we extend our trip to Paris (he'd traveled there disgruntled about not doing a beach vacation, then fell in love with the city) and suggested a number of great locations to visit. He also recommended proposing in the Gardens of Versailles, a very romantic location according to him. I had this in the back of my mind as we did an audio tour through the Palace of Versailles. As we ventured out into the Orangerie, I started hatching a plan to get Trish down to the gardens and try to rent bikes. We both love biking and the outdoors, so I figured it'd be a nice way to spend our memorable moment. As we strolled closer and I didn't see bikes to rent, I spotted the Grand Canal and noticed they had row boats.

The Versailles Orangerie Château de Versailles Gardens of Versailles Trees in the Versailles Gardens

Bassin d’Apollon – the Apollo Fountain

When we first arrived at the boat dock, there was a long line, but it magically disappeared moments later. We stepped into the boat, rowed to the center of the canal and paused for a bit to take in the beautiful day and the setting sun. Trish asked me to row to a better spot so she could photograph the sunset, but instead I said "here, listen to this" and handed her my headphones. I pressed play and watched her face light up as she heard my voice in her ears. 90 seconds later, I asked "Trish McGinity, will you marry me?" She responded with, "Of course!" :)

Happy Versailles Sunset

The rest of our trip in Paris was quite romantic and fun. We decided to wait until we got back to The States before telling anyone we were engaged. This meant we had three days of just us, Paris and some of the most beautiful art in the world. We explored the Louvre for 5-hours on Monday, marveling at the low-rider on display near the entrance and all the famous paintings.

Trish and the Louvre At The Louvre Lowrider in the Louvre Liberty Leading the People

Louvre

We imbibed in $40 martinis at The Hemingway Bar and scarfed down some delicious pizza at Gambino's. We had breakfast at Angelina's, toured La Sainte-Chapelle, hiked up Arc de Triomphe and wandered through the shopping districts Champs-Élysées and Faubourg St-Honoré. Yes, we fell in love with Paris and can't wait to return for Devoxx France in April.

Arc de Triumph

We departed Paris on the Wednesday morning before Thanksgiving and arrived in Boston that evening. We spent the next three days with Trish's family and our good friends, Chris, Julie, Lili and Wes. We did a 5K Turkey Trot on Thursday morning, followed by football watching and eating succulent turkey while basking in everyone's joy for us. We smiled, giggled, laughed, guffawed, smiled some more and had an all-around great time the rest of the weekend.

We returned home on Sunday evening, departing Boston's Logan airport only minutes after the Broncos kicked a field goal in overtime to beat the Chargers. Our flight was delayed just long enough (3 hours) that we got to watch almost the whole game. It was the perfect ending to a phenomenal trip.

To see more pictures from this adventure, see Trish's fantastic photos and mine on Flickr.

Posted in General at Dec 04 2011, 04:02:34 PM MST 12 Comments

My HTML5 with Play Scala, CoffeeScript and Jade Presentation from Devoxx 2011

This week, I had the pleasure of traveling to one of my favorite places in the world: Antwerp, Belgium. Like last year, I traveled with the lovely Trish McGinity and spoke at Devoxx 2011. This year, my talk was on developing a web/mobile app with HTML5, Play, Scala, CoffeeScript and Jade. I was inspired to learn Scala at the beginning of this year and added CoffeeScript and Jade to my learning list after talking to James Strachan at TSSJS 2011. You can read more about how my journey began in my first post about learning these technologies.

I started developing with these technologies in August and wrote about my learnings throughout the process. Last week, while writing my presentation, I decided it'd be fun to make my presentation into more of a story-telling-session than a learn-about-new-technologies session. To do this, I focused on talking a bit about the technologies, but more about my experience learning them. I also came up with a challenging idea: create a video that showed the development process, how hard it was to test the app and (hopefully) my success in getting it to work.

It was all a very close call, but I'm happy to say I pulled it off! I got the app to work on an iPhone (thanks to PhoneGap) last Saturday, finished the first draft of my presentation on Sunday night (after pulling an all-nighter) and finished editing the demo video on Wednesday night. My talk was on Thursday afternoon and I had a blast talking about my experience to such a large, enthusiastic audience. You can see the presentation below, on Slideshare or download the PDF.

You can find the "demo" for this talk on YouTube or watch it below.

One of the reasons I really enjoyed this talk is it only represents one milestone in my learning process. I plan on continuing to develop this application and learning more about HTML5, Scala, Play and CoffeeScript and Scalate/Jade. Now that Play 2.0 Beta has been released, I plan on upgrading to it and leveraging its native CoffeeScript and LESS support. I hope to continue using Scalate and its Jade format. And it's very likely PhoneGap will continue to be the bridge that allows everything to run in the background.

I've been talking with the Jfokus folks about doing this talk in Sweden in Feburary and Devoxx France about presenting there in April.

Learning all these technologies has been a challenging, but fun experience so far. As the last slide in my presentation says, I encourage you to do something similar. Pick something new to learn, have fun doing it, but more importantly - get out there and Play!

Update Dec. 20th: A video of this presentation is now available on Parleys.com.

Posted in Java at Nov 18 2011, 11:18:38 AM MST 7 Comments

Deploying Java and Play Framework Apps to the Cloud with James Ward

Yesterday, I attended James Ward's presentation on Deploying Java & Play Framework Apps to the Cloud at Devoxx. I arrived a bit late, but still managed to get there in time to see a lot of demos and learn more about Heroku. Below are my notes from James's talk.

When I arrived, James was doing a demo using Spring Roo. He was using Roo's Petclinic sample app and showed us how you could use Git to create a local repository of the new project and install Heroku's command line tool. From there, he ran the following command to create a new application on Heroku.

heroku create -s cedar

The Cedar Stack is what supports Java, Scala and Play Framework. It's the 3rd generation stack for Heroku. The command above created two endpoints, one for HTTP and one for Git. It picks from a list of randomly generated names, which all seem to have some humor in them. James ended up with "electric-sword-8877" for this demo.

From there, he ran git push heroku master to deploy the project to Heroku. Unfortunately, this resulted in a login error and there was an akward moment where we all thought the Demo Gods were angry. However, James was able to resolve this by using Heroku's sharing feature with the following command.

heroku sharing:add [email protected]

For Java projects, Heroku looks for a pom.xml file in the root directory and runs a Maven build on project. All the dependencies get downloaded on the cloud rather than put them into a WAR and requiring you to upload a large WAR file. You don't have to upload your source code to Heroku; James did it for the sake of the demo because it was faster.

After the build finishes, it creates a slug file. This file contains everything Heroku needs to run your application.

Next, James showed a demo of the running application and added a new Pet through its UI. Then he scaled it to two servers using the following command:

heroku scale web=2

He proved this was working by running heroku ps, which showed there were two running processes. He showed the app again, but noted that the record he added was missing. This is because when it started up a new dyno, Hibernate created the schema again and deleted all records. To fix, James changed Hibernate to only update the schema instead of create a new one. If you're a Hibernate user, you know this is as simple as changing:

hibernate.hbm2ddl.auto=create

to:

hibernate.hbm2ddl.auto=update

After committing this change, James redeployed using Git.

git push heroku master

The slug file got built again and Heroku deployed the new slug onto both dynos, automatically load balancing the app across two servers. James then ran heroku logs to see the logs of his dynos and prove that a request to his app's HTTP endpoint made requests to both dynos. The logging is powered by Logplex and you can read about how it works in the article Heroku Gets Sweet Logging.

James mentioned that Roo has a Heroku plugin, but after watching his talk and searching a bit on the internet, it seems it's just the jetty-runner setup as described in Getting Started with Spring MVC Hibernate on Heroku/Cedar.

What about autoscaling? There are some 3rd party tools that do this. Heroku's Management infrastructure has APIs that these tools talk too. Heroku hasn't built autoscaling into the platform because they don't know where the bottlenecks are in your application.

Heroku = Polyglot + PaaS + Cloud Components. It supports Ruby, node.js, Java, Clojure, Play and Scala and they're working on native Grails and Gradle support. There's currently 534,374 apps running on Heroku.

Heroku is a cloud application platform and there's 5 different components.

  1. Instant deployment
  2. HTTP Routing / Load Balancing
  3. Elastic Polyglot Runtime
  4. Management & Logging
  5. Component as a Service Ecosystem

For instant deployment, it's a pretty simple process:

  • You add files to a git repo
  • You provision the app on Heroku (heroku create)
  • You upload the files to Heroku (git push heroku master)
  • Heroku runs the build and assembles a "slug" file
  • Heroku starts a "dyno"
  • Heroku copies the "slug" to the "dyno"
  • Heroku starts the web application

Most apps will contain a Procfile that contains information about how to run the web process. For Spring Roo, it has:

web: java $JAVA_OPTS -jar target/dependency/jetty-runner.jar --port $PORT target/*.war

So how does Heroku decide what application server to use? It doesn't, you do. You need to get your application server into the slug file. The easiest way to do this is to specify your application server as a dependency in your pom.xml. In the Roo example, James uses the maven-dependency-plugin to get the jetty-runner dependency and copy it to the target directory. On Heroku, you bring your application server with you.

Heroku gives you 750 free dyno hours per app, per month. For developers, it's very easy to get started and use. Once you extend past one dyno, it's $.05 per dyno hour, which works out to around $30/month. It's only when you want to scale beyond one dyno where you get charged by Heroku, no matter how much data you transfer. Scalatest is running on Heroku. It has one dyno and is doing fine with that. Bill Venners doesn't have to pay anything for it.

java.herokuapp.com is a site James created that allows you to clone example apps and get started quickly with Heroku's Cedar Stack.

For HTTP Routing, Heroku uses an Erlang-based routing system to route all the HTTP requests across your dynos. Heroku doesn't support sticky sessions. Distributed session management does not work well, because it does not scale well. Heroku recommends you use a stateless web architecture or move your state into something like memcached. Jetty has (in the latest version) the ability to automatically serialize your session into a Mongo system. This works fine on Heroku. The problem with this is if you have 2 dynos running, each request can hit a different dyno and get different session state. Hence the recommendation for an external storage mechanism that can synchronize between dynos.

You can also run non-web applications on Heroku. You can have one web process, but as many non-web processes as you want.

Heroku has native support for the Play framework. To detect Play applications, it look for a conf/application.conf file. You don't need to have a Procfile in your root directory because Heroku knows how to start a Play application.

At this point, James created a new Play application, created a new Heroku app (he got "young-night-7104" this time) and pushed it to Heroku. He created a simple model object, a controller to allow adding new data and then wrote some jQuery to show new records via Ajax and JSON. He also showed how to configure the application to talk to Heroku's PostgreSQL database using the DATABASE_URL environment variable. He explained how you can use the heroku config command to see your environment variables.

The reason they use environment variables is so Heroku can update DATABASE_URL (and other variables) without having to call up all their customers and have them change them in their source code.

Play on Heroku supports Scala if you create your app with Scala. Play 2.0 uses Scala, Akka and SBT. Heroku added support for SBT a couple month ago, so everything will work just fine.

Heroku also supports Scala, detecting it by looking for the build.sbt file in the root directory. Heroku supports SBT 0.11.0 and it builds the 'stage' task. It currently does not support Lift because Lift uses an older version of SBT and because it's a very stateful framework that would require sticky sessions. Use Play, BlueEyes or Scalatra if you want Scala on Heroku.

Heroku has addons for adding functionality to your application, including Custom DNS, HTTPS, Amazon RDS, NoSQL and many more. They're also working on making their add-on and management APIs available via Java, so you'll (hopefully) be able to use them from your IDE in the future.

From there, James showed us how Heroku keeps slug files around so you can do rollbacks with heroku rollback. He also showed how you can use:

heroku run "your bash command"
to run any Bash command on the cloud.

Summary
I attended James's talk because he's a good friend, but also because I've been using Heroku to host my latest adventures with Play, Scala, CoffeeScript and Jade. I'm glad I attended because I learned some good tips and tricks and more about how Heroku works.

Heroku seems like a great development tool to me. In my experience, it's been really nice to have instant deployments using Git. In fact, I've created a 'push' alias so I can push to my project's repo and heroku at the same time.

alias push='git push origin master && git push heroku master'

I'd like to see more organizations embrace something like Heroku for developers. It'd be great if everyone had their own sandbox that business owners and product managers could see. I can't help but think this would be awesome for demos, prototyping, etc.

There were some other talks I wanted to attend at the same time, particularly Martin Odersky's What's in store for Scala? and WWW: World Wide Wait? A Performance Comparison of Java Web Frameworks. The WWW talk has posted their presentation but I'm sure it'd be more fun to watch.

It's pretty awesome that all the talks from Devoxx 2011 will be up on Parleys.com soon.

Update: James has posted his slides from this talk.

Posted in Java at Nov 18 2011, 08:14:45 AM MST 2 Comments

PhoneGap for Hybrid App Development

This afternoon, I attended Brian LeRoux's talk on PhoneGap for Hybrid App Development at Devoxx. You might remember that I tried PhoneGap last week and really enjoyed my experience. Below are my notes from Brian's talk.

PhoneGap is a project for creating native applications using HTML, CSS and JavaScript. PhoneGap started out as a hack. In 2007, Apple shipped the iPhone and Steve Jobs told everyone they should develop webapps. PhoneGap started in 2008 as a lofty summertime hack and gained traction as a concept at Nitobi with Android and Blackberry implementations in the fall. In 2009, people started to pay attention when PhoneGap got rejected by Apple. They added Symbian and webOS support and Sony Ericsson started contributing to the project. They got rejected because all PhoneGap-developed apps were named "PhoneGap". This turned out to be good press for the project and Apple let them in shortly after.

In 2010, IBM began tag-teaming with Nitobi and added 5 developers to the project after meeting them at OSCON. In 2011, RIM started contributing as well as Microsoft. Then Adobe bought the company, so they're obviously contributing.

PhoneGaps Goals: the web is a first class platform, so let people create installable web apps. Their second goal is to cease to exist and get browsers to adopt their model.

PhoneGap is NOT a runtime or a compiler/transpiler. It's not an IDE or predefined framework or proprietary lockin. It's Apache, MIT and BSD licensed to guarantee it's as free as free software gets. You can do whatever you want to do with it. PhoneGap has recently been contributed to the Apache Software Foundation.

As far as Adobe vs. PhoneGap is concerned, the Nitobi team remains contributors to PhoneGap. Adobe is a software tools company and has Apache and WebKit contributors. PhoneGap/Build integration will be added to Creative Cloud.

The biggest issues with contributing PhoneGap to Apache is renaming the project and source control. I'm not sure why it needs to be renamed, but it's likely that Apache Callback is out. There seems to be some consensus on Apache Cordova. Apache likes SVN and the PhoneGap community currently uses Git. They're trying to find a medium road there, but would prefer to stay on Git.

The PhoneGap technique is colloquially called "the bridge". It's a 3 step process: they instantiate a WebView, then they call JavaScript from native code, then they call native code from JavaScript. Apparently, all device APIs are available via JavaScript in a WebView.

The primary platforms supported are iOS >= 3, Android >= 1.5 and BlackBerry >= 5.x. They also support webOS, Symbian, Samsung Bada and Windows Phone. No mobile dev platform supports as many deploy targets as PhoneGap. Primary contributors are Adobe, IBM, RIM and Microsoft.

Documentation for PhoneGap is available at http://docs.phonegap.com. Device APIs for PhoneGap 1.0 included sensors, data and outputs, which all devices have. Examples of sensors are geolocation and camera. Data examples are the filesystem, contacts and media. Outputs are screens, speakers and the speaker jack. All PhoneGap APIs are plugins, but any native API is permitted.

What about security? Brian recommends looking at the HTML5 Security Cheatsheet. PhoneGap has added a lot of security measures since they've found the native API pretty much opens up everything.

PhoneGap doesn't bundle a UI framework, but they support any JavaScript framework that works in the browser. PhoneGap is just a fancy browser, so your code run in less fancy web browsers too. This means you can develop and test your app in your desktop browser and only use PhoneGap to package and distribute your app.

Competition? PhoneGap has no competition.

PhoneGap/Build is for compiling your apps in the cloud and free for open source projects. The biggest reason they did this is because they couldn't redistribute all the SDKs and it was a pain for developers to download and install SDKs in training classes.

For mobile app development, you should have a singular goal. Do one thing really well if you want to be successful. Great UX happens iteratively. You know that the web works and has been widely successfully cross-platform. It's likely you've already invested in the web. Start by building a mobile web client and use PhoneGap as a progressive enhancement technique.

Shipping and unit testing should be a daily activity. Automate everything so you can have one-click builds (test/dev/release). For web client design, constraints are your ally in the battle against complexity and "clients who are not chill". Phones suck and consume a lot: cpu, ram, bandwidth, battery, network... everything! Start with a benchmark of app performance and monitor that benchmark. If you have tons and tons of features, consider splitting into multiple apps.

The mobile web is not WebKit! Opera is huge, Firefox is making strides and IE still happens. For layouts: use flex-box rules (anyone got a link to these?), css media queries and meta tags for viewport. You should try to develop your app without frameworks because they come with a ton of code and can effect the size of your app.

Looks can kill: aesthetics that can hurt performance: border-radius, box-shadow and gradients can slow down your apps. Chances are, you really don't need these features. Design your app for your brand, not for the device manufacturer. An app that looks like an iPhone app on Android doesn't give a positive impression.

For JavaScript libraries, start with your problem, not a generic solution like Sencha or jQuery Mobile. Zepto and its older brother XUI are all you need to start. Jo is a fantastic option. Backbone and Spine are worth watching.

For testing, QUnit and Jasmine are pretty popular. For deployment, concat, minify and obfuscate your JavaScript and CSS. Or you can inline everything into the markup to minimize HTTP chatter. Gmail inlines and comments all their JavaScript and then evals it.

From there, Brian recommended leveraging HTML5's AppCache and and using RESTful JSON endpoints for legacy systems. Next, he tried to show us a demo of a photo sharing application. Unfortunately, the Demo Gods were grumpy and Brian couldn't get his computer to recognize his Android phone. He did show us the client code and it's pretty impressive you can use 1 line of code to take a picture on a phone.

The last thing we looked at was debug.phonegap.com. This is an app that's powered by weinre. It lets you enter a line of JavaScript in your client and then remotely debug it in a tool that looks like Chrome's Web Inspector. Very cool stuff if you ask me.

Summary
I really enjoyed learning more about PhoneGap, particularly because Brain emphasized all my web development skills can be used. I don't have to learn Objective-C or Android to develop native apps and I don't even have to install an SDK if I use PhoneGap/Build. Of course, my mobile developer friends might disagree with this approach. In the meantime, I look forward to using PhoneGap to turn my mobile web clients into native apps and finding out if it's really as good as they say it is.

Posted in The Web at Nov 16 2011, 10:22:16 AM MST 2 Comments

Play 2.0, A web framework for a new era

This week, I'm in Antwerp, Belgium for the annual Devoxx conference. After traveling 21 hours door-to-door yesterday, I woke up and came to the conference to attend some talks on Play and PhoneGap. I just got out of the session on Play 2.0, which was presented by Sadek Drobi and Guillaume Bort. Below are my notes from this presentation.

The Play 2.0 beta is out! You can read more about this release on the mailing list. This beta includes native support for both Scala and Java, meaning you can use both in the same project. The release also bundles Akka and SBT by default.

In other news, Play 2.0 is now part of the Typesafe Stack. Typesafe is the Scala company, started by the founder of Scala (Martin Odersky) and the founder of Akka (Jonas Bonér). Guillaume is also joining the Typesafe Advisory Board.

Sadek and Guillaume both work at zenexity, where Play is the secret weapon for the web applications they've built for the last decade. Play was born in the real world. They kept listening to the market to see what they should add to the project. At some point, they realized they couldn't keep adding to the old model and they needed to create something new.

The web has evolved from static pages to dynamic pages (ASP, PHP). From there, we moved to structured web applications with frameworks and MVC. Then the web moved to Ajax and long-polling to more real-time, live features. And this changes everything.

Now we need to adapt our tools. We need to handle tremendous flows of data. Need to improve expressiveness for concurrent code. We need to pick the appropriate datastore for the problem (not only SQL). We need to integrate with rapidly-evolving client side technologies like JavaScript, CoffeeScript, and Dart. We need to use elastic deployment that allows scaling up and scaling down.

zenexity wanted to integrated all of these modern web needs into Play 2.0. But they also wanted to keep Play approachable. They wanted to maintain fast turnaround so you can change your code and hit reload to see the changes. They wanted to keep it as a full stack framework with support for JSON, XML, Web Services, Jobs, etc. And they wanted to continue to use and conventions over configuration.

At this point, Guillaume did a Play 2.0 Beta demo, show us how it uses SBT and has a console so everything so it runs really fast. You can have both Scala and Java files in the same project. Play 2.0 templates are based on Scala, but you don't need to know Scala to use them. You might have to learn how to write a for loop in Scala, but it's just a subset of Scala for templates and views. SBT is used for the build system, but you don't have to learn or know SBT. All the old play commands still work, they're just powered by a different system.

After the demo, Sadek took over and started discussing the key features of Play 2.0.

To handle tremendous amounts of data, you need to do chunking of data and be able to process a stream of data, not just wait until it's finished. Java's InputStream is outdated and too low level. Its read() method reads the next byte of data from the input and this method can block until input data is available.

To solve this, Play includes a reactive programming feature, which they borrowed from Haskell. It uses Iteratee/Enumerator IO and leverages inversion of control (not like dependency injection, but more like not micro-managing). The feature allows you to have control when you need it so you don't have to wait for the input stream to complete. The Enumerator is the component that sends data and the Iteratee is the component that receives data. The Iteratee does incremental processing and can tell the Enumerator when it's done. The Iteratee can also send back a continuation, where it tells the Enumerator it wants more data and how to give it. With this paradigm, you can do a lot of cool stuff without consuming resources and blocking data flow.

Akka is an actor system that is a great model for doing concurrent code. An Actor could be both an Enumerator and an Iteratee. This vastly improves the expressiveness for concurrent code. For example, here's how you'd use Akka in Play:

def search(keyword: String) = Action {
  AsyncResult {
    // do something with result
  }
}

Play does not try to abstract data access because datastores are different now. You don't want to think of everything as objects if you're using something like MongoDB or navigating a Social Graph. Play 2.0 will provide some default modules for the different datastores, but they also expect a lot of contributed modules. Anorm will be the default SQL implementation for Play Scala and Ebean will be the default ORM implementation for Play Java. The reason they've moved away from Hibernate is because they needed something that was more stateless.

On the client side, there's so many technologies (LESS, CoffeeScript, DART, Backbone.js, jQuery, SASS), they didn't want to bundle any because they move too fast. Instead, there's plugins you can add that help you leverage these technologies. There's a lot of richness you can take advantage of on the client side and you need to have the tools for that.

Lastly, there's a new type of deployment: container-less deployment to the cloud. Akka allows you to distribute your jobs across many servers and Heroku is an implementation of elastic deployment that has built-in support for Play.

They've explained what they tried to design and the results of this new, clean architecture have been suprising. Side effects include: type-safety everywhere for rock-solid applications. There's an awesome performance boost from Scala. There's easier integration with existing projects via SBT. And it only takes 10 lines of code to develop an HTTP Server that responds to web requests.

The memory consumption is amazing: only 2MB of heap is used when a Play 2.0 app is started. Tests on Guillaume's laptop have shown that it can handle up to 40,000 requests per second, without any optimization of the JVM. Not only that, but after the requests subside, garbage collection cleans up everything and reduces the memory consumption back to 2MB.

At this point, Guillaume did another demo, showing how everything is type-safe in 2.0, including the routes file. If you mistype (or comment one out) any routes, the compiler will find it and notify you. Play 2.0 also contains a compiled assets feature. This allows you to use Google's Closure Compiler, CoffeeScript and LESS. If you put your LESS files in app/assets/stylesheets, compilation errors will show up in your browser. If you put JavaScript files in app/assets/javascripts, the Closure compiler will be used and compilation errors will show up in your browser.

Play 2.0 ships with 3 different sample applications, all implemented in both Java and Scala. HelloWorld is more than just text in a browser, it includes a form that shows how validation works. Another app is computer-database. When Guillaume started it, we saw how evolutions were used to create the database schema from the browser. The Play Team has done their best to make the development process a browser-based experience rather than having to look in your console. The computer-database is a nice example of how to do CRUD and leverages Twitter's Bootstrap for its look and feel.

The last sample application is zentasks. It uses Ajax and implements security so you can see how to create a login form. It uses LESS for CSS and CoffeeScript and contains features like in-place editing. If you'd like to see any of these applications in action, you can stop by the Typesafe booth this week at Devoxx.

Unfortunately, there will be no migrating path for Play 1.x applications. The API seems very similar, but there are subtle changes that make this difficult. The biggest thing is how templating has changed from Groovy to Scala. To migrate from 1.2.x would be mostly a copy/paste, modify process. There are folks working on getting Groovy templates working in 2.0. The good news is zenexity has hundreds of 1.x applications in production, so 1.x will likely be maintained for many years.

Summary
This was a great talk on what's new in Play 2.0. I especially like the native support for LESS and CoffeeScript and the emphasis on trying to keep developers using two tools: their editor and the browser. The sample apps look great, but the documentation look sparse. I doubt I'll get a chance to migrate my Play 1.2.3 app to 2.0 this month, but I hope to try migrating sometime before the end of the year.

Posted in Java at Nov 16 2011, 05:58:09 AM MST 11 Comments

More Scalate Goodness for Play

Scalate This article is the 6th in a series on about my adventures developing a web application with HTML5, Play Scala, CoffeeScript and Jade. Previous articles can be found at:

  1. Integrating Scalate and Jade with Play 1.2.3
  2. Trying to make CoffeeScript work with Scalate and Play
  3. Integrating HTML5 Boilerplate with Scalate and Play
  4. Developing with HTML5, CoffeeScript and Twitter's Bootstrap
  5. Play Scala's Anorm, Heroku and PostgreSQL Issues

Last week, I wrote about my adventures with Anorm and mentioned I'd made some improvements to Scalate Play interoperability. First of all, I've been using a Scalate trait and ScalateTemplate class to render Jade templates in my application. I described this setup in my first article on Scalate and Play.

Adding SiteMesh Features and Default Variables
When I started making my app look good with CSS, I started longing for a feature I've used in SiteMesh. That is, to have a body id or class that can identify the page and allow per-page CSS rules. To do this with SiteMesh, you'd have something like the following in your page:

  
<body id="signup"/>

And then read it in your decorator:

<body<decorator:getProperty property="body.class" writeEntireProperty="true"/>>

As I started looking into how to do this, I came across Play Scala's ScalaController and how it was populating Play's default variables (request, response, flash, params, etc.). Based on this newfound knowledge, I added a populateRenderArgs() method to set all the default variables and my desired bodyClass variable.

def populateRenderArgs(args: (Symbol, Any)*): Map[String, Any] = {
  val renderArgs = Scope.RenderArgs.current();

  args.foreach {
    o =>
      renderArgs.put(o._1.name, o._2)
  }

  renderArgs.put("session", Scope.Session.current())
  renderArgs.put("request", Http.Request.current())
  renderArgs.put("flash", Scope.Flash.current())
  renderArgs.put("params", Scope.Params.current())
  renderArgs.put("errors", validationErrors)
  renderArgs.put("config", Play.configuration)

  // CSS class to add to body
  renderArgs.put("bodyClass", Http.Request.current().action.replace(".", " ").toLowerCase)
  renderArgs.data.toMap
}

implicit def validationErrors:Map[String,play.data.validation.Error] = {
  import scala.collection.JavaConverters._
  Map.empty[String,play.data.validation.Error] ++ 
    Validation.errors.asScala.map( e => (e.getKey, e) )
}

After adding this method, I was able to access these values in my templates by defining them at the top:

-@ val bodyClass: String 
-@ val params: play.mvc.Scope.Params
-@ val flash: play.mvc.Scope.Flash

And then reading their values in my template:

body(class=bodyClass)
...
- if (flash.get("success") != null) {
  div(class="alert-message success" data-alert="alert")
    a(class="close" href="#") &×
    | #{flash.get("success")}
- }
...
  fieldset
    legend Leave a comment →
    div.clearfix
      label(for="author") Your name:
      input(type="text" name="author" class="xlarge" value={params.get("author")})
    div.clearfix
      label(for="content") Your message:
      textarea(name="content" class="xlarge") #{params.get("content")}
    div.actions
      button(type="submit" class="btn primary") Submit your comment
      button(type="reset" class="btn") Cancel

For a request like Home/index, the body tag is now rendered as:

<body class="home index">
This allows you to group CSS styles by Controller names as well as by method names.

Next, I started developing forms and validation logic. I quickly discovered I needed an action() method like the one defined in ScalaTemplate's TemplateMagic class.

def action(action: => Any) = {
  new play.mvc.results.ScalaAction(action).actionDefinition.url
}

Since TemplateMagic is an inner class, I determined that copying the method into my ScalateTemplate class was the easiest workaround. After doing this, I was able to import the method and use it in my templates.

-import controllers.ScalateTemplate._
...
form(method="post" class="form-stacked" id="commentForm"
     action={action(controllers.Profile.postComment(workout._1.id()))})

After getting the proper URL written into my form's action attribute, I encountered a new problem. The Play Scala Tutorial explains validation flow as follows:

if (Validation.hasErrors) {
  show(postId)
} else {
  Comment.create(Comment(postId, author, content))
  Action(show(postId))
}

However, when I had validation errors, I end up with the following error:

Could not load resource: [Timeline/postComment.jade]

To fix this, I added logic to my Scalate trait that looks for a "template" variable before using Http.Request.current().action.replace(".", "/") for the name. After making this change, I was able to use the following code to display validation errors.

if (Validation.hasErrors) {
  renderArgs.put("template", "Timeline/show")
  show(postId)
} else {
  Comment.create(Comment(postId, author, content))
  Action(show(postId))
}

Next, I wanted to give child pages the ability to set content in parent pages. With SiteMesh, I could use the <content> tag as follows:

<content tag="underground">
  HTML goes here
</content>

This HTML could then be retrieved in the decorator using the <decorator:getProperty> tag:

<decorator:getProperty property="page.underground"/>

With Scalate, I found it equally easy using the captureAttribute() method. For example, here's how I captured a list of an athlete's workouts for display in a sidebar.

- captureAttribute("sidebar")
  - Option(older).filterNot(_.isEmpty).map { workouts =>
    .older-workouts
      h3
        | Older workouts
        span.from from this app
      - workouts.map { workout =>
        - render("workout.jade", Map('workout -> workout, 'mode -> "teaser"))
      - }
  - }
- }

Then in my layout, I was able to retrieve this and display it. Below is a snippet from the layout I'm using (copied from Twitter's Bootstrap example). You can see how the sidebar is included in the .span4 at the end.

-@ val sidebar: String = ""
...
.container
  .content
    .page-header
      h1
        = pageHeader
        small
          = pageTagline
    .row
      .span10
        !~~ body
      .span4
        = unescape(sidebar)
  footer

View vs. Render in Scalate
In the sidebar code above, you might notice the render() call. This is the Scalate version of server-side includes. It works well, but there's also a view() shortcut you can use if you want to have templates for rendering your model objects. I quickly discovered it might be difficult to use this feature in my app because my object was Option[(models.Workout, models.Athlete, Seq[models.Comment])] instead of a simple object. You can read the view vs. render thread on the Scalate Google Group if you're interested in learning more.

Scalate as a Module
The last enhancement I attempted to make was to put Scalate support into a Play module. At first, I tried overriding Play's Template class but ran into compilation issues. Then Guillaume Bort (Play's lead developer) recommended I stick with the trait approach and I was able to get everything working. I looked at the outdated play-scalate module to figure out how to add Scala support to build.xml and copied its 500.scaml page for error reporting.

In order to get line-precise error reporting working, I had to wrap a try/catch around calling Scalate's TemplateEngine.layout() method. Again, most of this code was copied from the outdated play-scalate module.

case class Template(name: String) {
  
  def render(args: (Symbol, Any)*) = {
    val argsMap = populateRenderArgs(args: _*)
    
    val buffer = new StringWriter()
    var context = new DefaultRenderContext(name, scalateEngine, new PrintWriter(buffer))
    
    try {
      val templatePath = new File(Play.applicationPath+"/app/views","/"+name).toString
        .replace(new File(Play.applicationPath+"/app/views").toString,"")
      scalateEngine.layout(templatePath + scalateType, argsMap)
    } catch {
      case ex:TemplateNotFoundException => {
        if(ex.isSourceAvailable) {
          throw ex
        }
        val element = PlayException.getInterestingStrackTraceElement(ex)
        if (element != null) {
           throw new TemplateNotFoundException(name, 
             Play.classes.getApplicationClass(element.getClassName()), element.getLineNumber());
        } else {
           throw ex
        }
      }  
      case ex:InvalidSyntaxException => handleSpecialError(context,ex)
      case ex:CompilerException => handleSpecialError(context,ex)
      case ex:Exception => handleSpecialError(context,ex)
    } finally {
      if (buffer.toString.length > 0)
        throw new ScalateResult(buffer.toString,name)
    }
  }
}
...
private def handleSpecialError(context:DefaultRenderContext,ex:Exception) {
  context.attributes("javax.servlet.error.exception") = ex
  context.attributes("javax.servlet.error.message") = ex.getMessage
  try {
    scalateEngine.layout(scalateEngine.load(errorTemplate), context)
  } catch {
    case ex:Exception =>
      // TODO use logging API from Play here...
      println("Caught: " + ex)
      ex.printStackTrace
  }
}

private def errorTemplate:String = {
  val fullPath = new File(Play.applicationPath,"/app/views/errors/500.scaml").toString 
  fullPath.replace(new File(Play.applicationPath+"/app/views").toString,"")
}

Once I had this in place, error messages from Scalate are much better. Not only do I see the error in my browser, but I can click on the offending line to open it directly in TextMate.

Play Scalate Error Reporting

I've published my play-scalate module on GitHub so others can try it out. To give it a whirl, add the following to your dependencies.yml:

    - upgrades -> play-scalate 0.1

repositories:
    - upgrades:
        type: http
        artifact: "http://static.raibledesigns.com/[module]-[revision].zip"
        contains:
            - upgrades -> *

Then add with play.modules.scalate.Scalate to your controllers and call the render() method.

Summary
After using Scalate and Play for almost 3 months, I'm really enjoying the combination. When I first integrated Scalate with a simple trait, the error messages were always in the console. Now that I've borrowed some smarts from Play's ScalaController and play-scalate's error reporting, I feel like it's practically a built-in solution. I was easily able to integrate my desired SiteMesh features and it even allows reusable template blocks. In the end, it's just Scala and Scalate does a good job of allowing you to leverage that.

Other thoughts:

  • If you're writing a lot of Jade and familiar with HTML, Don Park's html2jade is a great tool that comes with Scalate support.
  • I'm really enjoying writing CSS with LESS, particularly the ability to nest rules and have programming features. The only issue I've seen is IntelliJ's LESS plugin only does code-completion for variables rather than CSS values.
  • The Play Framework Cookbook is a great reference for learning how to write modules. Not only does it explain how to create modules, it has some great real-world examples for doing bytecode enhancement, implementing message queues, using Solr and how to do production monitoring.

If this series of articles has intrigued you and you'll be at Devoxx next week, you should stop by my talk on Thursday afternoon. In addition, there's several other Play talks at Devoxx and a possible meetup on Wednesday. Check out the Devoxx, anyone? thread for more information.

Update: There's one thing I forgot to mention about the Play Scalate Module. When I had Scalate integrated in my app with a trait, I only included the scalate-core and scalate-util JARs in dependencies.yml:

- org.fusesource.scalate -> scalate-core 1.5.2-scala_2.8.1:
    transitive: false
- org.fusesource.scalate -> scalate-util 1.5.2-scala_2.8.1:
    transitive: false

However, when I created the play-scalate module, I allowed more dependencies.

- org.fusesource.scalate -> scalate-core 1.5.2-scala_2.8.1:
    exclude:
        - javax.servlet -> *
        - com.sun.jersey -> *
        - org.osgi -> *
- org.fusesource.scalate -> scalate-util 1.5.2-scala_2.8.1
Because Scalate depends on Logback, debug messages started showing up in my console. To fix this, I created conf/logback.xml in my project and filled it with the following XML.

<configuration>
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
      <encoder>
          <pattern>%msg%n</pattern>
      </encoder>
  </appender>

  <root level="info">
    <appender-ref ref="STDOUT" />
  </root>
</configuration>

This reduces the logging and allows me to increase Scalate's logging if I ever have the need.

Posted in Java at Nov 07 2011, 02:07:40 PM MST Add a Comment

Mahalo Kauai

I've heard great things about Hawaii for most of my life. My Dad was stationed at Barbers Point when he was in the Navy. His sister, my Aunt Mary, was born there. My sister and I sent my parents to Hawaii for their 30th Wedding Anniversary. You can imagine my excitement when Trish sent me an email on January 25th:

It's only 40,000 miles for both of us to fly to Kauai!! I picked the week after Labor Day just for fun :)

My response:

WAHOOOOOO! BOOK IT!!

She booked it that night. For $10.

We left for Kuaui the morning after the disappointing Broncos home opener and a fun sports weekend with Abbie and Jack. Our trip started out great, sneaking into the Red Carpet Club for free at LAX and getting a slew of free drinks from a super-cool flight attendant (Anthony) on our flight from LAX to Kauai.

After landing and marveling at the open-air airport, we picked up our rental Jeep and drove to the north side of the island. A friend recommended we stay at the St. Regis Princeville Resort and we were very impressed when we checked into our room overlooking Hanalei Bay.

The next morning, we vowed to do nothing but relax by the pool. We enjoyed a scrumptious breakfast at the Mekana Terrace, complete with Bloody Mary's. We had to have Bloody's since the St. Regis in NYC claims to have invented them. We spent the rest of the day napping, swimming, sunbathing, snorkeling and sipping on Mai Tai's.

Breakfast From the St. Regis Hanalei Bay The Pool Relaxing

After enjoying a beautiful sunset ...

HDR Sunset next to the palm trees on the beach at Hanalei Bay

... we visited the concierge to book some activities for the rest of our trip. We wanted to take things up a notch and enjoy all the cool stuff Kuai had to offer. So we arranged for Stand Up Paddling and the Mailani Dinner Shown on Thursday, golf on Friday, a doorless helicopter ride on Saturday and a kayak trip along the Na Pali coast on Sunday.

We woke up Thursday refreshed and ready to go. Our view out the window was exceptional.

Aloha in the morning at the St Regis Hanalei Bay

After a delicious room service breakfast in our room, we wandered down to the beach to meet our SUP guide. He warned us that girls were generally better than guys at SUP and we proceeded to prove him correct. Trish never got her hair wet and I had to abandon ship several times.

Ready for SUP! Breakfast with a view
Board Meeting

That afternoon, we headed to the The Kalalau Trail for a hike. Our SUP guide recommended it and said it was "so easy, your grandma could do it". His Grandma must be a lot younger than most, because the trail was not easy, but we certainly enjoyed the challenge.

Beautiful trail to Hanakapi'ai Beach and looking down the Napali Coast An easy 5' x 5' spot to land your helicopter?
Trish at Kalalau Beach Kalalau Beach

We were rewarded with some spectular views at Kalalau Beach.

Kalalau Beach Kalalau Beach

We made it back to the hotel just in time for the dinner show and another marvelous Hanalei sunset.

Hanalei Bay Sunset

At the dinner show, we sat with honeymooners from Houston that worked at NASA. Since they both spoke Russian, we had fun discussing Russia, our trips there and how we learned the language. The dinner show was great and they featured quite a few of the top Hula dancers in Hawaii.

Mailani Dinner show Hula dancer from side Kauai Mailani Dinner show Hula dancer with fire St Regis Kauai
Mailani Dinner show Hula dancers with Kala'au rhythm sticks and Hui'hui feathered rattles St Regis Kauai
Mailani Dinner show male performer St Regis Kauai
Mailani Dinner Show
Polynesian fireknife dancer with a fire knife Mailani Dinner Show
Mailani Dinner show firedancer with poi Kauai 3

The next morning, we grabbed Huevos Rancheros in Princeville and headed to the Makai Golf Club for a one-of-a-kind experience. Not only did they let us bring our full-stocked cooler on the course, but they rented us some fantastic Callaway clubs. We golfed for hours with no one in front, and no one trailing behind.

The famous third tee drop on the Makai Golf Course over looking Hanalei Bay Kauai - Matt's drive was perfect right onto the green below Makai Golf Club my pitch out of the sand is next to the pin.  Matt's is on the edge of the green :) Matt's drive headed toward the ravine on Makai Golf course!
This one is a gonner too! Heaven at Makai Golf Course!

Trish's photo of the Bougainvillia on the back nine is one of my favorites.

Bougainvillia on the Makai Golf course looking across Hanalei Bay

We enjoyed some Blue Hawaii's at the St. Regis afterward, in a cabana that's normally reserved for $1000/day. We snuck in and even got the honeymooner's discount from a hometown waiter.

2 Blue Hawai'i on the beach in Hanalei Bay

On Saturday, I booked a tour at the Ahonui Botanical Gardens. The gardens where amazing, built by Bill and Lucinda Robertson. They converted a jungle of 8 acres into an elaborate garden with trees, flowers and plants from around the world. Since you can grow almost anything on The Garden Isle, they planted many exotic fruit trees that we had the pleasure of snacking on throughout our 3-hour tour. About halfway through, Lucinda treated us to an adventure in making and tasting delicious chocolates.

Heart of Palm - Paul Michell uses this in their products - it's a wonderful clear light lotion and great for hair too! Ahonui Botanical Gardens Ahonui Botanical Gardens Whoa, this is an Apple banana native to Hawai'i and tastes much better than regular Del Monte bananas!

Lucinda Robertson gave us a great Chocolate tasting and history of chocolate.  The chocolate they made was the best of the bunch! Bill Robertson, the owner gave us the tour which they just started doing publically in June 2011.  It was a great experience!

We rushed from the garden tour to the helicopter ride on the other side of the island. The concierge had booked us with Jack Harter Helicopters, because they were the only ones that flew without doors (for better pictures). As soon as we lifted off, I knew it was going to be an experience of a lifetime. We flew over the Waimea Canyon, along the Na Pali Coast, over Hanalei Bay and back into the mountains to the wettest place on earth. It felt like an amusement park ride combined with an IMAX movie. Our pilot was a Hawaii native that knew the whole island and gave us an excellent tour of its features. I cannot recommend this tour enough if you're ever in Kauai.

Bell 500 here we come! Honopu Valley - King Kong was filmed in this area.

Rainbow to Kalalau Valley Napali Coast State Park

Looking back toward Makuaiki Point Wailua Falls - yep from Fantasy Island

The next morning, we had to get up early for our kayak trip. We had a wakeup call at 4:30, breakfast via room service arrived at 5 and we were packed and checked out of the hotel at 5:30. We arrived at Na Pali Kayak at 6 and quickly realized we had our work cut out for us. Both Trish and I expected the kayak trip to be like paddling across a lake and didn't know we were in for the Everest of kayaking - a 17-mile journey that would take most of the day.

Our Put in point for Napali Coast Kayak Tour.  I couldn't bring the D700 on the kayak and the waterproof camera was futile.  I thought they would have gotten better by now? We borrowed some sea-sickness medication, bought some water from our hosts and got ready for a good challenge. Unfortunately, we couldn't take Trish's camera, and the waterproof camera she bought took mediocre pictures. However, we did get to see two schools of dolphins (one even jumped into the air for us) and a couple turtles along the way. Having to paddle in unison turned out to be great couples therapy too.

We enjoyed lunch on a beach along the coast around 1, took a nap and hopped back in the boats for the last 5 miles. We pulled out around 4 and were on the road by 5 for the 2.5 hour drive back to Hanalei Bay. It was country dark when we arrived. We hopped in the Jeep and drove an hour back across the island to stay at the Sheraton Kauai (the St. Regis was full) for our last night.

At the Sheraton, we had one of their best rooms and enjoyed awesome views and a final relaxing day before heading home.

View from The Sheraton Hibiscus!

The Tunnel of Trees on the way to the airport was one last reminder of how beautiful Kauai is.

The Tunnel of Trees Kauai!

Mahalo Kauai. You are one of the most breathtaking places I have ever been too. Your views, your waves, your rainbows - all spectacular. Trish and I will be back, you've made an impression on us that will last forever.

If you'd like to see many of the places we visited in a movie, check out Soul Surfer. It takes place in Hanalei Bay and we recognized many of the locations while watching it. For more pictures, see my Shareholders Meeting in Kauai or Trish's magnificent photos.

Posted in General at Sep 26 2011, 10:19:54 AM MDT 3 Comments

Integrating Scalate and Jade with Play 1.2.3

At the beginning of this year, I decided I wanted to learn Scala. Since I'm a Web Frameworks Aficionado, I figured the best way to do that would be to learn Lift. I entered these two items on my todo list and let them lie for a couple months. After attending TSSJS 2011 and having a conversation with James Strachan, I added a couple more technologies to my learning list. James had great things to say about both CoffeeScript and Jade and I decided to learn those as well.

In May, Devoxx announced their Call For Papers and I started reminiscing about how awesome last year's trip was. I decided I'd try to get accepted again and started brainstorming about talks I'd like to give. I came up with "Comparing Scala Web Frameworks" and "HTML5 with Play Scala, CoffeeScript and Jade". The reason I chose Play over Lift for the latter talk is because I think it fits a lot more with the MVC mindset I have and the easy-to-learn nature of web frameworks I enjoy using. Both topics sounded very interesting to me, and I figured they'd also inspire me to learn the technologies in a brute-force fashion; where I was under a time constraint and would be embarrassed in front of a large audience if I didn't succeed.

In mid-July, I got an email from Stephan inviting me to speak again at the 10th edition of Devoxx. I smile splashed across my face and I quickly realized I had a lot to learn. Since I was still in vacation mode after summer vacation in Montana, I decided to wait until I returned from Cape Cod to start studying. While on my 2nd summer vacation, I received an email from Devoxx stating that they'd like me present "HTML5 with Play/Scala, CoffeeScript and Jade".

To learn all these technologies, I decided on an In Anger approach - where I would study minimally and learn mostly by doing. I ordered CoffeeScript on August 8th and Programming in Scala, 2nd Edition the following week (August 17th). I started reading both books while traveling the following week (I found CoffeeScript and Scala to be very similar, so I don't know if I'd recommend learning them at the same time). That same week, I started integrating Scalate (Jade) into a new Play Scala application.

Scalate advertises on their homepage that it works with Play via the play-scalate module. They neglect to mention that this module hasn't been updated in over a year or what version of Play it works with. I tried to use the scalate-0.7.2 version and quickly ran into issues. I posted a message to the Scalate Google Group explaining my compilation issues and stacktraces. The response? Crickets.

Next, I tried posting to the Play Google Group and got a much better response. Here's what they said:

Looking at the Scalate module code, I don't think it can work as is with Play Scala 0.9.1. The latest version is more than 1 year old, and we have made a lot of changes in the API.
...
The integration of Scalate is pretty difficult if you plan to get the same kind of experience than the native Play scala template regarding auto-reload and error reports.

You can try to port the module to 0.9.1, basically all it has to do is to provide a plugin that detect changes to scaml file, and recompile them. No special integration with the Play API is needed.

After learning that play-scalate was out-of-date, I contacted the project owner via GitHub and tried to get everything working with Play 1.2.3 and Scalate 1.5.1. I updated the dependencies in the project, fixed compilation issues and tried to build. No dice:

build: 
    [mkdir] Created dir: /Users/mraible/dev/play-scalate/tmp/classes 
   [scalac] Compiling 7 source files to /Users/mraible/dev/play-scalate/tmp/classes 
   [scalac] error: class file needed by Binding is missing. 
   [scalac] reference type Serializable of package scala refers to nonexisting symbol. 
   [scalac] one error found

I posted this error to the Play Group, discovered it was caused by Scalate 1.5.1 requiring Scala 2.9. I downgraded to Scalate 2.4.1 and got another nice cryptic error:

build: 
    [mkdir] Created dir: /Users/mraible/dev/play-scalate/tmp/classes 
   [scalac] Compiling 7 source files to /Users/mraible/dev/play-scalate/tmp/classes 
   [scalac] error: class file needed by ScalaController is missing. 
   [scalac] reference value dispatch of package <root> refers to nonexisting symbol. 
   [scalac] one error found

Apparently, this was caused by another Scala versioning issue and I was offered a much simpler solution for integrating Scalate. Below are the steps I performed to integrate Scalate 1.4.1 with Play 1.2.3.

  1. Updated dependencies.yml to references Scala and Scalate dependencies.
    require:
        - play
        - play -> scala 0.9.1
        - org.fusesource.scalate -> scalate-core 1.4.1:
            transitive: false
        - org.fusesource.scalate -> scalate-util 1.4.1:
            transitive: false
    
  2. Added Scalate configuration elements to application.conf.
    scalate=jade
    jvm.memory=-Xmx256M
    
  3. Created a ScalateTemplate class to contain the Scalate Engine and render the template.
    package controllers
    
    import play.Play
    
    object ScalateTemplate {
    
      import org.fusesource.scalate._
      import org.fusesource.scalate.util._
    
      lazy val scalateEngine = {
        val engine = new TemplateEngine
        engine.resourceLoader = new FileResourceLoader(Some(Play.getFile("/app/views")))
        engine.classpath = Play.getFile("/tmp/classes").getAbsolutePath
        engine.workingDirectory = Play.getFile("tmp")
        engine.combinedClassPath = true
        engine.classLoader = Play.classloader
        engine
      }
    
      case class Template(name: String) {
        val scalateType = "." + Play.configuration.get("scalate");
    
        def render(args: (Symbol, Any)*) = {
          scalateEngine.layout(name + scalateType, args.map {
            case (k, v) => k.name -> v
          } toMap)
        }
      }
    
      def apply(template: String) = Template(template)
    }
    
  4. Created a Scalate trait to override the render() method in Play's Controller class.
    package controllers
    
    import play.mvc.Http
    
    trait Scalate {
    
      def render(args: (Symbol, Any)*) = {
        def defaultTemplate = Http.Request.current().action.replace(".", "/")
        ScalateTemplate(defaultTemplate).render(args: _*);
      }
    }
    
  5. Created an Application.scala controller with a default index method.
    package controllers
    
    import play.mvc._
    import models._
    
    object Application extends Controller with Scalate {
    
      def index = {
        render('user -> User("Raible"))
      }
    }
    
    The models/User.scala class is very simple:
    package models
    
    case class User(name:String)
    
  6. Lastly, I created an index.jade file in views/Application.
    -@ var user: models.User
    p Hi #{user.name},
    - for(i <- 1 to 3)
      p= i
    p See, I can count!
    

After getting all this working, I decided it was time to get it into production. As luck would have it, Heroku had just announced Play support a few days earlier. I heard through the grapevine that Play Scala would work, so I gave it a try. It was amazingly easy. All I had to do was create an account, create a "Procfile" in my application's root directory and run a heroku command followed by a git push. It all looked great until Play tried to compile my Jade templates as Groovy templates:

Cannot start in PROD mode with errors 
Template compilation error (In /app/views/Application/index.jade around line 2) 
The template /app/views/Application/index.jade does not compile : #{user.name} is not closed. 
play.exceptions.TemplateCompilationException: #{user.name} is not closed. 
       at play.templates.TemplateCompiler.generate(TemplateCompiler.java:102) 
       at play.templates.TemplateCompiler.compile(TemplateCompiler.java:15) 
       at play.templates.GroovyTemplateCompiler.compile(GroovyTemplateCompiler.java:4 1)

The solution from Guillaume was simple enough and I renamed my "views" directory to "templates" and updated ScalateTemplate.scala accordingly. You can see the deployed application at http://play-more.herokuapp.com.

The next steps in my Play Scala adventure will be trying to get the CoffeeScript module to work. I also hope to integrate HTML5 Boilerplate with Jade and Scalate Layouts. I'll be doing this with the mindset that HTML and JavaScript aren't that bad. I expect a lot from CoffeeScript and Jade and hope I enjoy them as much as Strachan. ;-)

In the meantime, here's some interesting links I've seen recently encountered that discuss Scala and/or Play. I dig the passion and activity that exists in these communities.

Posted in Java at Sep 07 2011, 01:21:41 PM MDT 10 Comments

Oregon, Cape Cod and Fun in Winter Park

Silver Falls State Park I'm proud to say it's been almost a month since my last blog entry. This can only mean one thing → I've been having too much fun to blog. The good news is I finally found time to write about our recent adventures, so grab yourself a tasty beverage and read on.

Within hours of my last blog post, Trish and I hopped on a plane to visit my good friends, Clint and Autumn, in Oregon. We flew into Portland and spent the weekend hiking in Silver Falls and drinking good beer at the Oregon Brewers Festival and Edgefield. Edgefield is one my favorite places on Earth, encapsulating a farm/resort environment with 27 different features. The features range from a soaking pool to a winery to a pool hall to scotch tasting in a shack next to a garden.

Thirsty Field of Flowers

The weekend was especially fun since Autumn was pregnant and it was two weeks before the due date of their first child. Broderick Jordan Wilburn Foster was born yesterday and I hear the whole family is doing well.

Trish and I spent the night at Edgefield on Saturday and caught an early flight from Portland to Boston the next morning. Her brother (also named Matt) lives near Boston and we drove our rental Volvo convertible (to fit in with the New Englanders) to his house Sunday night. On the Hertz Bus from the airport met Nigel Parry, a professional photographer. Not just anybody, but someone that's shot pictures of some very famous people. Trish is also a photographer, so they had a long conversation and it inspired her to resign from her sales job last week. Actually, it wasn't that meeting, she's been wanting to be a famous photographer since she was in high school. Now that dream shall happen. She's awesome.

On Monday afternoon, we picked up Abbie and Jack from the Boston airport. They flew up from West Palm Beach on their first unaccompanied minors flight. We drove them to Cape Cod and settled into Trish's parents house near the water. The rest of the week, we had a blast with our friends Chris and Julie and the entire McGinity clan. We boated, grilled, flew down the water slides, played miniature golf and toured Martha's Vineyard. We had a pool party, played some pool and sang our hearts out at karaoke. Trish's brother's kids are the same age as mine, so you couldn't wipe the smiles off our kids' faces, especially when we had the tunes cranked with the top down on the convertible.

Wheeee!! Hercules! Michael and Jack

Monkey Shadows

For more pictures of this super-fun trip, see Summer Fun in Oregon and Cape Cod part 1 and 2.

After returning from Boston, we had a week without kids and lived it to the fullest with a John Butler Trio concert at Red Rocks and the Winter Park Beer Festival. Trish's friend Joanna and my good friend, "The Professor" joined us for a weekend of mountain biking and sweet mountain views. We even got to hang out with James Ward and his wife Jenny at the beer festival. Sunday, we hiked up the beautiful Columbine Lake Trail. Trish's dog, Sagan (named after Carl) chased sticks and was his crazy self as usual.

Cheers! Crazy Sagan!

We drove back Monday morning to be there for the kids first day of school. They sure start early these days don't they?

First Day of 2nd and 3rd Grade

I rode my bike 168 miles to and from work throughout the following week. The next weekend, we took the kids up to the Ski Shack for their first time. I hired a guy to make queen-size bunk beds for them, so they had a blast in their new roomy beds. On Saturday, we had a garage sale since the previous owners left a bunch of beds and couches and we didn't need all that furniture. The turnout was great and we got to hang out with Jodi and James, Suzie, and The Lamonts. All of these folks are old friends that just happened to be in the mountains for the weekend. One of Trish's best friends, Chris, has a place less than a mile from us and we had a blast with her on Saturday night. Thanks for the fun memories Chris!

On Sunday, we took the kids the Winter Park Base Area where they have Disneyland in the Mountains as I like to call it. An alpine slide, miniature golf, a maze, a climbing wall and a Chili Cook-Off to keep Daddy happy. We met our good friend Suzie there and had a lot of fun with Chris, Brice and their crazy kids. Enjoying an Avery White Rascal at the Cheeky Monk's happy hour was the perfect way to end the day.

Abbie and Jack on the Cabriolet Chili Cook Off! Abbie on the Trampoline

Nice flip Jack!

Sunday night, we were graced with the presence of a beautiful sunset.

Sunset Views from the shack

Happy Kids Sunday Sunset

That pretty much catches you up-to-date with the goings on in my life. As you can tell, it's been a great summer so far. I'm really looking forward to the fall too. Broncos season, a trip to Hawaii, learning new technologies, talking about them at Devoxx and a new gig.

I've decided to leave Overstock because I'm a die-hard Broncos fan and I can't work for a company that supports the Raiders during football season. There's a good chance I'll be back after the season, just in time for The Greatest Snow on Earth. ;)

This weekend, my parents are meeting us in Winter Park for Labor Day weekend. We plan on fishing, hiking, smiling and enjoying each other's company a whole lot. Tomorrow is Jack's birthday. I gotta run ... it's time to go buy a bike, play a little golf, hit the pool and go to the BBQ before tonight's CD Release Party.

Posted in General at Aug 27 2011, 01:50:52 PM MDT 1 Comment

How do you get started in programming?

I recently received the email below from someone asking how he might get started in programming. I think this is a popular topic, especially given the current economic situation in the US (unemployment is high, but not in the tech industry). For that reason, I figured I'd post my response here and allow others to chime in with their advice.

I read about you on LinkedIn, forgive my intrusion. Since you seem like an expert in the field of designing websites I wanted to know your thoughts on switching into this field late in life. I am 41 and looking to make the move from an unrelated field (finance) to programming. So far I have learned HTML, CSS and some Javascript. I have taken classes on C and Java. I have made some basic Android phone apps.

What languages do you think I should focus on? What is the fastest way to get up to speed to make a career of it? Classes? Take a entry level job? Study on my own?

Thanks for any insights….

My reply:

It's interesting that you're switching from finance to programming. I did the same thing early on in my career, but I was fortunate enough to do it in college (I have degrees in Russian, International Business and Finance) and therefore able to audit some CS classes before I graduated.

I think the most valuable skills these days are front-end skills (HTML, CSS and JavaScript). If you can combine those skills with the ability to design websites, you'll go along way. I've taken a different approach where I have excellent front-end skills, but also know a lot about the backend.

While it helps to have a Java background these days, the real sweat spot is the JVM and the containers that run on it like Tomcat and Jetty. A lot of Java developers are learning Groovy and Scala, but unfortunately a lot of their documentation/books are targeted towards Java developers.

The fastest way to get up-to-speed on it is to start your own project (if you can't get a company to hire you to do it). I'd suggest creating a webapp that solves a problem that you have, makes your life easier, etc. If you open source it and build a community around it, that's just as good as working for a company as far as experience goes. Combine this with studying on your own and you can likely come up to speed very quickly.

As a programmer, what advice do you have for someone looking to switch careers, or get into our industry fresh out of college?

Posted in Java at Jul 28 2011, 11:12:09 AM MDT 8 Comments